1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
|
\chapter{Python API\label{pythonapi}}
\section{Multiple Interpreters\label{pyapi-interps}}
When working with mod_python, it is important to be aware of a feature
of Python that is normally not used when using the language for
writing scripts to be run from command line. This feature is not
available from within Python itself and can only be accessed through
the \citetitle[http://www.python.org/doc/current/api/api.html]{C
language API}.
Python C API provides the ability to create \dfn{subinterpreters}. A
more detailed description of a subinterpreter is given in the
documentation for the
\citetitle[http://www.python.org/doc/current/api/initialization.html]{\cfunction{Py_NewInterpreter()}}
function. For this discussion, it will suffice to say that each
subinterpreter has its own separate namespace, not accessible from
other subinterpreters. Subinterpreters are very useful to make sure
that separate programs running under the same Apache server do not
interfere with one another..
At server start-up or mod_python initialization time, mod_python
initializes an interpreter called \dfn{main} interpreter. The main
interpreter contains a dictionary of subinterpreters. Initially, this
dictionary is empty. With every hit, as needed, subinterpreters are
created, and references to them are stored in this dictionary. The
dictionary is keyed on a string, also known as \emph{interpreter
name}. This name can be any string. The main interpreter is named
\samp{main_interpreter}. The way all other interpreters are named can
be controlled by
\code{PythonInterp*} directives. Default behaviour is to name interpreters
using the Apache virtual server name (\code{ServerName}
directive). This means that all scripts in the same vrtual server
execute in the same subinterpreter, but scripts in different virtual
servers execute in different subinterpreters with completely separate
namespaces.
\citetitle[dir-other-ipd.html]{\code{PythonInterpPerDirectory}} and
\citetitle[dir-other-ipdv.html]{\code{PythonInterpPerDirective}}
directives alter the naming convention to use the absolute path of the
directory being accessed, or the directory in which the
\code{Python*Handler} was encountered, respectively.
\citetitle[dir-other-pi.html]{\code{PythonInterpreter}} can be used to
force the interpreter name to a specific string overriding any naming
conventions.
Once created, a subinterpreter will be reused for subsequent requests.
It is never destroyed and exists until the Apache child process dies.
\begin{seealso}
\seetitle[http://www.python.org/doc/current/api/api.html]
{Python C Language API}{Python C Language API}
\end{seealso}
\section{Overview of a Handler\label{pyapi-handler}}
A \dfn{handler} is a function that processes a particular phase of a
request. Apache processes requests in phases - read the request,
process headers, provide content, etc. For every phase, it will call
handlers, provided by either the Apache core or one of its modules,
such as mod_python, which passes control to functions provided b the
user and written in Python. A handler written in Python is not any
different than a handler written in C, and follows these rules:
\index{req}
\indexii{Request}{object}
A handler function will always be passed a reference to a
\class{Request} object. (Throughout this manual, the \class{Request}
object is often referred to by the \code{req} variable.)
Every handler can return:
\begin{itemize}
\item
\constant{apache.OK}, meaning this phase of the request was handled by this
handler and no errors occurred.
\item
\constant{apache.DECLINED}, meaning this handler refused to handle this phase of
the requestand Apache needs to look for another handler.
\item
\constant{apache.\emph{HTTP_ERROR}}, meaning an HTTP error occurred.
\var{HTTP_ERROR} can be:
\begin{verbatim}
HTTP_CONTINUE = 100
HTTP_SWITCHING_PROTOCOLS = 101
HTTP_PROCESSING = 102
HTTP_OK = 200
HTTP_CREATED = 201
HTTP_ACCEPTED = 202
HTTP_NON_AUTHORITATIVE = 203
HTTP_NO_CONTENT = 204
HTTP_RESET_CONTENT = 205
HTTP_PARTIAL_CONTENT = 206
HTTP_MULTI_STATUS = 207
HTTP_MULTIPLE_CHOICES = 300
HTTP_MOVED_PERMANENTLY = 301
HTTP_MOVED_TEMPORARILY = 302
HTTP_SEE_OTHER = 303
HTTP_NOT_MODIFIED = 304
HTTP_USE_PROXY = 305
HTTP_TEMPORARY_REDIRECT = 307
HTTP_BAD_REQUEST = 400
HTTP_UNAUTHORIZED = 401
HTTP_PAYMENT_REQUIRED = 402
HTTP_FORBIDDEN = 403
HTTP_NOT_FOUND = 404
HTTP_METHOD_NOT_ALLOWED = 405
HTTP_NOT_ACCEPTABLE = 406
HTTP_PROXY_AUTHENTICATION_REQUIRED= 407
HTTP_REQUEST_TIME_OUT = 408
HTTP_CONFLICT = 409
HTTP_GONE = 410
HTTP_LENGTH_REQUIRED = 411
HTTP_PRECONDITION_FAILED = 412
HTTP_REQUEST_ENTITY_TOO_LARGE = 413
HTTP_REQUEST_URI_TOO_LARGE = 414
HTTP_UNSUPPORTED_MEDIA_TYPE = 415
HTTP_RANGE_NOT_SATISFIABLE = 416
HTTP_EXPECTATION_FAILED = 417
HTTP_UNPROCESSABLE_ENTITY = 422
HTTP_LOCKED = 423
HTTP_FAILED_DEPENDENCY = 424
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_NOT_IMPLEMENTED = 501
HTTP_BAD_GATEWAY = 502
HTTP_SERVICE_UNAVAILABLE = 503
HTTP_GATEWAY_TIME_OUT = 504
HTTP_VERSION_NOT_SUPPORTED = 505
HTTP_VARIANT_ALSO_VARIES = 506
HTTP_INSUFFICIENT_STORAGE = 507
HTTP_NOT_EXTENDED = 510
\end{verbatim}
\end{itemize}
As an alternative to \emph{returning} an HTTP error code, handlers can
signal an error by \emph{raising} the \constant{apache.SERVER_RETURN}
exception, and providing an HTTP error code as the exception value,
e.g.
\begin{verbatim}
raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN
\end{verbatim}
Handlers can send content to the client using the \method{Request.write()}
method. Before sending the body of the response, headers must be
sent using the \method{Request.send_http_header()} method.
Client data, such as POST requests, can be read by using the
\method{Request.read()} function.
\strong{NOTE:} The directory of the Apache \code{Python*Handler}
directive in effect is prepended to the \code{sys.path}. If the
directive was specified in a server config file outside any
\code{<Directory>}, then the directory is unknown and not prepended.
An example of a minimalistic handler might be:
\begin{verbatim}
from mod_python import apache
def requesthandler(req):
req.content_type = "text/plain"
req.send_http_header()
req.write("Hello World!")
return apache.OK
\end{verbatim}
\section{\module{apache} -- Access to Apache Internals.}
\declaremodule[apache]{extension}{apache}
\modulesynopsis{Access to Apache Internals}
\moduleauthor{Gregory Trubetskoy}{grisha@modpython.org}
The Python Application Programmer interface to Apache internals is
contained in a module appropriately named \module{apache}, located inside the
\module{mod_python} package. This module provides some important objects that
map to Apache internal structures, as well as some useful functions,
all documented below.
\indexii{_apache}{module}
The \module{apache} module can only be imported by a script running under
mod_python. This is because it depends on a built-in module
\module{_apache} provided by mod_python. It is best imported like this:
\begin{verbatim}
from mod_python import apache
\end{verbatim}
\module{mod_python.apache} module defines the following objects and
functions. For a more in-depth look at Apache internals, see the
\citetitle[http://dev.apache.org/API.html]{Shambhala API Notes}
\begin{funcdesc}{log_error}{message\optional{, level, server}}
An interface to the Apache
\citetitle[http://dev.apache.org/apidoc/apidoc_ap_log_error.html]{ap_log_error()}
function. \var{message} is a string with the error message, \var{level} is
one of the following constants:
\begin{verbatim}
APLOG_EMERG
APLOG_ALERT
APLOG_CRIT
APLOG_ERR
APLOG_WARNING
APLOG_NOTICE
APLOG_INFO
APLOG_DEBUG
APLOG_NOERRNO
\end{verbatim}
\var{server} is a reference to a \member{Request.server} object. If
\var{server} is not specified, then the error will be logged to the default
error log, otherwise it will be written to the error log for the
appropriate virtual server.
\end{funcdesc}
\begin{funcdesc}{make_table}{}
Returns a new empty object of type \code{mp_table}. See Section \ref{pyapi-mptable}
for a description of a table object.
\end{funcdesc}
\subsection{Table Object (mp_table)\obindex{table}\label{pyapi-mptable}}
The table object is a Python mapping to the Apache table. The table
object performs just like a dictionary, with the only difference that
key lookups are case insensitive.
Much of the information that Apache uses is stored in tables. For
example, \member{Request.header_in} and \member{Request.headers_out}.
All the tables that mod_python provides inside the \class{Request}
object are actual mappings to the Apache structures, so changing the
Python table also changes the underlying Apache table.
In addition to normal dictionary-like behavior, the table object also
has the following method:
\begin{methoddesc}[table]{add}{key, val}
\function{add()} allows for creating duplicate keys, which is useful
when multiple headers, such as \code{Set-Cookie:} are required.
\end{methoddesc}
\subsection{Request Object\index{Request}\label{pyapi-mprequest}}
The request object is a Python mapping to the Apache
\code{request_rec} structure.
The request object is a real Python object. You can dynamically
assign attributes to it as a way to communicate between handlers.
When a handler is invoked, it is always passed a single argument - the
\class{Request} object.
\subsubsection{Request Methods\label{pyapi-mprequest-meth}}
\begin{methoddesc}[Request]{add_handler}{htype, handler\optional{, dir}}
Allows dynamic handler registration. \var{htype} is a string
containing the name of any of the apache \code{Python*Handler}
directives, e.g. \samp{PythonHandler}. \var{handler} is a string
containing the name of the module and the handler function. Optional
\var{dir} is a string containing the name of the directory to be added
to the pythonpath. If no directory is specified, then, if there is
already a handler of the same type specified, its directory is
inherited, otherwise the directory of the presently executing handler
is used.
A handler added this way only persists throughout the life of the
request. It is possible to register more handlers while inside the
handler of the same type. One has to be careful as to not to create an
infinite loop this way.
Dynamic handler registration is a useful technique that allows the
code to dynamically decide what will happen next. A typical example
might be a \code{PythonAuthenHandler} that will assign different
\code{PythonHandlers} based on the authorization level, something like:
\begin{verbatim}
if manager:
req.add_handler("PythonHandler", "menu::admin")
else:
req.add_handler("PythonHandler", "menu::basic")
\end{verbatim}
Note: There is no checking being done on the validity of the handler
name. If you pass this function an invalid handler it will simply be
ignored.
\end{methoddesc}
\begin{methoddesc}[Request]{add_common_vars}{}
Calls the Apache \cfunction{ap_add_common_vars()} function. After a
call to this method, \member{Request.subprocess_env} will contain a
lot of CGI information.
\end{methoddesc}
\begin{methoddesc}[Request]{child_terminate}{}
Terminate a child process. This should terminate the current child
process in a nice fashion.
This method does nothing in multithreaded environments (e.g. Windows).
\end{methoddesc}
\begin{methoddesc}[Request]{get_basic_auth_pw}{}
Returns a string containing the password when Basic authentication is
used.
\end{methoddesc}
\begin{methoddesc}[Request]{get_config}{}
Returns a reference to the table object containing the configuration
in effect for this request. The table has directives as keys, and
their values, if any, as values.
\end{methoddesc}
\begin{methoddesc}[Request]{get_dirs}{}
Returns a reference to the table object keyed by directives currently
in effect and having directory names of where the particular directive
was last encountered as values. For every key in the table returned by
\method{get_config()}, there will be a key in this table. If the directive was
in one of the server config files outside of any \code{<Directory>},
then the value will be an empty string.
\end{methoddesc}
\begin{methoddesc}[Request]{get_remote_host}{type}
Returns the a string with the remote client's DNS name or IP or
\code{None} on failure. The first call to this function may entail a
DNS look up, but subsequent calls will use the cached result from the
first call.
The optional type argument can specify the following:
\begin{itemize}
\item
\code{apache.REMOTE_HOST} Look up the DNS name. Fail if Apache
directive \code{HostNameLookups} is \code{off} or the hostname cannot
be determined.
\item
\code{apache.REMOTE_NAME} \emph{(Default)} Return the DNS name if
possible, or the IP (as a string in dotted decimal notation)
otherwise.
\item
\code{apache.REMOTE_NOLOOKUP} Don't perform a DNS lookup, return an
IP. Note: if a lookup was performed prior to this call, then the
cached host name is returned.
\item
\code{apache.REMOTE_DOUBLE_REV} Force a double-reverse lookup. On
failure, return None.
\end{itemize}
\end{methoddesc}
\begin{methoddesc}[Request]{get_options}{}
Returns a reference to the table object containing the options set by
the \code{PythonOption} directives.
\end{methoddesc}
\begin{methoddesc}[Request]{read}{\optional{len}}
Reads at most \var{len} bytes directly from the client, returning a
string with the data read. If the \var{len} argument is negative or
ommitted, reads all data given by the client.
This function is affected by the \code{Timeout} Apache configuration
directive. The read will be aborted and an \exception{IOError} raised
if the \code{Timeout} is reached while reading client data.
This function relies on the client providing the \code{Content-length}
header. Absense of the \code{Content-length} header will be treated as
if \code{Content-length: 0} was supplied.
Incorrect \code{Content-length} may cause the function to try to read
more data than available, which will make the function block until a
\code{Timeout} is reached.
\end{methoddesc}
\begin{methoddesc}[Request]{readline}{\optional{len}}
Like \function{read()} but reads until end of line.
Note that in accordance with the HTTP specification, most clients will
be terminating lines with "\textbackslash r\textbackslash n" rather
than simply "\textbackslash n".
\end{methoddesc}
\begin{methoddesc}[Request]{register_cleanup}{callable\optional{, data}}
Registers a cleanup. Argument \var{callable} can be any callable
object, the optional argument \var{data} can be any object (default is
\code{None}). At the very end of the request, just before the actual
request record is destroyed by Apache, \var{callable} will be called
with one argument, \var{data}.
\end{methoddesc}
\begin{methoddesc}[Request]{send_http_header}{}
Starts the output from the request by sending the HTTP headers. This
function has no effect when called more than once within the same
request. Any manipulation of \member{Request.headers_out} after this
function has been called is pointless since the headers have already
been sent to the client.
\end{methoddesc}
\begin{methoddesc}[Request]{write}{string}
Writes \var{string} directly to the client, then flushes the buffer.
\end{methoddesc}
\subsubsection{Request Members\label{pyapi-mprequest-mem}}
\begin{memberdesc}[Request]{connection}
A \code{connection} object associated with this request. See
Connection Object below for details.
\emph{(Read-Only)}
\end{memberdesc}
\begin{memberdesc}[Request]{server}
A server object associate with this request. See Server Object below
for details.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{next}
If this is an internal redirect, the \code{request} object we redirect to.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{prev}
If this is an internal redirect, the \code{request} object we redirect from.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{main}
If this is a sub-request, pointer to the main request.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{the_request}
String containing the first line of the request.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{assbackwards}
Is this an HTTP/0.9 "simple" request?
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{header_only}
A boolean value indicating HEAD request, as opposed to GET.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{protocol}
Protocol, as given by the client, or "HTTP/0.9". Same as CGI \envvar{SERVER_PROTOCOL}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{proto_num}
Integer. Number version of protocol; 1.1 = 1001
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{request_time}
A long integer. When request started.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{status_line}
Status line. E.g. "200 OK".
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{method}
A string containing the method - 'GET', 'HEAD', 'POST', etc.
Same as CGI \envvar{REQUEST_METHOD}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{method_number}
Integer containg the method number.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{allowed}
Integer. A bitvector of the allowed methods. Used in relation with
METHOD_NOT_ALLOWED.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{sent_body}
Integer. Byte count in stream is for body. (?)
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{bytes_sent}
Long integer. Number of bytes sent.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{mtime}
Long integer. Time the resource was last modified.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{boundary}
String. Multipart/byteranges boundary.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{range}
String. The \code{Range:} header.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{clength}
Long integer. The "real" content length. (I.e. can only be used after
the content's been read?)
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{remaining}
Long integer. Bytes left to read. (Only makes sense inside a read
operation.)
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{read_length}
Long integer. Number of bytes read.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{read_body}
Integer. How the request body should be read. (?)
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{read_chunked}
Boolean. Read chunked transfer coding.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{content_type}
String. The content type. Mod_python maintains an internal flag
(\member{_content_type_set}) to keep track of whether
\member{content_type} was set manually from within Python. The
publisher handler uses this flag; when \member{content_type} isn't
set, it attempts to guess the content type by examining the
first few bytes of the output.
\end{memberdesc}
\begin{memberdesc}[Request]{headers_in}
A table object containing headers sent by the client.
\end{memberdesc}
\begin{memberdesc}[Request]{headers_out}
A \code{table} object representing the headers to be sent to the
client. Note that manipulating this table after the
\method{Request.send_http_headers()} has been called is meaningless, since the
headers have already gone out to the client.
\end{memberdesc}
\begin{memberdesc}[Request]{err_headers_out}
These headers get send with the error response, instead of
headers_out.
\end{memberdesc}
\begin{memberdesc}[Request]{handler}
The hame of the handler currently being processed. In all cases with
mod_python, this should be "python-program".
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{content_encoding}
String. Content encoding.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{vlist_validator}
Integer. Variant list validator (if negotiated).
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{no_cache}
Boolean. No cache if true.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{no_local_copy}
Boolean. No local copy exists.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{unparsed_uri}
The URL without any parsing performed.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{uri}
The path portion of the URI.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{filename}
String. File name being requested.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{path_info}
String. What follows after the file name, but is before query args, if
anything. Same as CGI \envvar{PATH_INFO}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[Request]{args}
String. Same as CGI \envvar{QUERY_ARGS}.
\emph{(Read-Only})
\end{memberdesc}
\subsection{Connection Object (mp_conn)\obindex{connection}\label{pyapi-mpconn}}
The connection object is a Python mapping to the Apache conn_rec
structure.
\subsubsection{Connection Members\label{pyapi-mpconn-mem}}
\begin{memberdesc}[connection]{server}
A \code{server} object associated with this connection.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{base_server}
A \code{server} object for the physical vhost that this connection came in
through.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{child_num}
Integer. The number of the child handling the request.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{local_addr}
The (address, port) tuple for the server.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{remote_addr}
The (address, port) tuple for the client.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{remote_ip}
String with the IP of the client. Same as CGI \envvar{REMOTE_ADDR}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{remote_host}
String. The DNS name of the remote client. None if DNS has not been
checked, "" (empty string) if no name found. Same as CGI \envvar{REMOTE_HOST}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{remote_logname}
Remote name if using RFC1413 (ident). Same as CGI \envvar{REMOTE_IDENT}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{user}
If an authentication check is made, this will hold the user
name. \strong{NOTE:} You must call \code{get_basic_auth_pw()} before
using this value. Same as CGI \envvar{REMOTE_USER}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{ap_auth_type}
Authentication type. (None == basic?). Same as CGI \envvar{AUTH_TYPE}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{keepalives}
The number of times this connection has been used. (?)
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{local_ip}
String with the IP of the server.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[connection]{local_host}
DNS name of the server.
\emph{(Read-Only})
\end{memberdesc}
\subsection{Server Object (mp_server)\obindex{server}\label{pyapi-mpserver}}
The request object is a Python mapping to the Apache \code{request_rec}
structure. The server structure describes the server (possibly virtual
server) serving the request.
\subsubsection{Server Methods\label{pyapi-mpsrv-meth}}
\begin{methoddesc}[server]{register_cleanup}{request, callable\optional{, data}}
Registers a cleanup. Very similar to \function{req.register_cleanup()}, except
this cleanup will be executed at child termination time. This function
requires one extra argument - the request object.
\end{methoddesc}
\subsubsection{Server Members\label{pyapi-mpsrv-mem}}
\begin{memberdesc}[server]{defn_name}
String. The name of the configuration file where the server definition
was found.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{defn_line_number}
Integer. Line number in the config file where the server definition is
found.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{srm_confname}
Location of the srm config file.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{server_admin}
Value of the \code{ServerAdmin} directive.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{server_hostname}
Value of the \code{ServerName} directive. Same as CGI \envvar{SERVER_NAME}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{port}
Integer. TCP/IP port number. Same as CGI \envvar{SERVER_PORT}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{error_fname}
The name of the error log file for this server, if any.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{loglevel}
Integer. Logging level.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{is_virtual}
Boolean. True if this is a virtual server.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{timeout}
Integer. Value of the \code{Timeout} directive.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{keep_alive_timeout}
Integer. Keepalive timeout.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{keep_alive_max}
Maximum number of requests per keepalive.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{send_buffer_size}
Integer. Size of the TCP send buffer.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{path}
String. Path for \code{ServerPath}
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{pathlen}
Integer. Path length.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{server_uid}
UID under which the server is running.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[server]{server_gid}
GID under which the server is running.
\emph{(Read-Only})
\end{memberdesc}
\subsection{Debugging\label{pyapi-debug}}
Mod_python supports the ability to execute handlers within the Python
debugger (pdb) via the \code{PythonEnablePdb} Apache directive. Since
the debugger is an interactive tool, httpd must be invoked with the -X
option. (NB: When pdb starts, you will not see the usual \code{>>>}
prompt. Just type in the pdb commands like you would if there was
one.)
\subsection{Internal Callback Object\label{pyapi-callback}\index{obCallBack}}
The Apache server interfaces with the Python interpreter via a
callback object obCallBack. When a subinterpreter is created, an
instance of obCallBack is created in this
subinterpreter. Interestingly, obCallBack is not written in C, it is
written in Python and the code for it is in the apache module.
Mod_python only uses the C API to import apache and then instantiate
obCallBack, storing a reference to the instance in the interpreter
dictionary described above. Thus, the values in the interpreter
dictionary are callback object instances.
When a request handler is invoked by Apache, mod_python uses the
obCallBack reference to call its method Dispatch, passing it the name
of the handler being invoked as a string.
The Dispatch method then does the rest of the work of importing the
user module, resolving the callable object in it and calling it
passing it a request object.
\section{\module{util} -- Miscellaneous Utilities\label{pyapi-util}}
\declaremodule[util]{extension}{util}
\modulesynopsis{Miscellaneous Utilities}
\moduleauthor{Gregory Trubetskoy}{grisha@modpython.org}
The \module{util} module provides a number of utilities handy to a
web application developer.
The functionality provided by \module{util} is also available in the
standard Python library \module{cgi} module, but the
implementation in \module{cgi} is specific to the CGI environment,
making it not the most efficient one for mod_python. For example, the
code in \module{util} does not use the environment variables since
most of the information is available directly from the
\class{Request} object. Some of the functions in the \module{util}
module are implemented in C for even better performance.
The recommended way of using this module is:
\begin{verbatim}
from mod_python import util
\end{verbatim}
\begin{seealso}
\seetitle[http://CGI-Spec.Golux.Com/]
{Common Gateway Interface RFC Project Page}
{for detailed information on the CGI specification}
\end{seealso}
\subsection{FieldStorage class\label{pyapi-util-fstor}}
Access to form data is provided via the \class{FieldStorage}
class. This class is similar to the standard library module \module{cgi}
\class{FieldStorage} (but there are a few differences).
\begin{classdesc}{FieldStorage}{req\optional{, keep_blank_values, strict_parsing}}
This class provides uniform access to HTML form data submitted by the client.
\var{req} is an instance of the mod_python \class{Request} object.
The optional argument \var{keep_blank_values} is a flag indicating whether
blank values in URL encoded form data should be treated as blank strings. The
default is false, which means that blank values are ignored as if they were
not included.
The optional argument \var{strict_parsing} is not yet implemented.
\end{classdesc}
While being instantiated, the \class{FieldStorage} class reads all of
the data provided by the client. Since all data provided by the client
is consumed at this point, there should be no more than one
\class{FieldStorage} class instantiated per signle request, nor should
you make any attempts to read client data before or after
instantiating a \class{FieldStorage}.
The data read from the client is then parsed into separate fields
and packaged in \class{Field} objects, one per field. For HTML form
inputs of type \code{file}, a temporary file is created that can later be
accessed via the \member{file} attribute of a \class{Field} object.
The \class{FieldStorage} class has a mapping object interface, i.e. it
can be treated like a dictionary. When used as a dictionary, the dictionary
keys are form input names, and the returned dictionary value can be:
\begin{itemize}
\item
A string, containing the form input value. This is only when there is a single
value corresponding to the input name.
\item
An instances of a \class{Field} class, if the input is a file upload.
\item
A list of strings and/or \class{Field} objects. This is when multiple values
exist, such as for a \code{<select>} HTML form element.
\end{itemize}
Note that unlike the standard library \module{cgi} module
\class{FieldStorage} class, a
\class{Field} object is returned \emph{only} when it is a file
upload. This means that you do not need to use the \member{.value}
attribute to access values of fields in most cases.
In addition to standard mapping object methods, \class{FieldStorage} objects
have the following attributes:
\begin{memberdesc}{list}
This is a list of \class{Field} objects, one for each input. Multiple
inputs with the same name will have multiple elements in this list.
\end{memberdesc}
\subsubsection{Field class\label{pyapi-util-fstor-fld}}
\begin{classdesc}{Field}{}
This class is used internally by \class{FieldStorage} and is not
meant to be instantiated by the user. Each instance of a \class{Field}
class represents an HTML Form input.
\end{classdesc}
\class{Field} instances have the following attributes:
\begin{memberdesc}{name}
The input name.
\end{memberdesc}
\begin{memberdesc}{value}
The input value. This attribute can be used to read data from a file
upload as well, but one has to excercise caution when dealing with
large files since when accessed via \member{value}, the whole file is
read into memory.
\end{memberdesc}
\begin{memberdesc}{file}
This is a file object. For file uploads it points to a temporary file.
For simple values, it is a \class{StringIO} object, so you can read
simple string values via this attribute instead of using the \member{value}
attribute as well.
\end{memberdesc}
\begin{memberdesc}{filename}
The name of the file as provided by the client.
\end{memberdesc}
\begin{memberdesc}{type}
The content-type for this input as provided by the client.
\end{memberdesc}
\begin{memberdesc}{type_opyions}
This is what follows the actual content type in the \code{content-type}
header provided by the client, if anything. This is a dictionary.
\end{memberdesc}
\begin{memberdesc}{disposition}
The value of the first part of the \code{content-disposition} header.
\end{memberdesc}
\begin{memberdesc}{disposition_options}
The second part (if any) of the \code{content-disposition} header in
the form of a dictionary.
\end{memberdesc}
\begin{seealso}
\seerfc{1867}{Form-based File Upload in HTML}{for a description of
form-based file uploads}
\end{seealso}
\subsection{Other functions\label{pyapi-util-funcs}}
\begin{funcdesc}{parse_qs}{qs\optional{, keep_blank_values, strict_parsing}}
This functnion is functionally equivalent to the standard library
\module{cgi} \function{parse_qs}, except that it is written in C and is
much faster.
Parse a query string given as a string argument (data of type
\mimetype{application/x-www-form-urlencoded}). Data are
returned as a dictionary. The dictionary keys are the unique query
variable names and the values are lists of values for each name.
The optional argument \var{keep_blank_values} is a flag indicating
whether blank values in URL encoded queries should be treated as blank
strings. A true value indicates that blanks should be retained as
blank strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
\strong{Note:} The \var{strict_parsing} argument is not yet implemented.
\end{funcdesc}
\begin{funcdesc}{parse_qsl}{qs\optional{, keep_blank_values, strict_parsing}}
This functnion is functionally equivalent to the standard library
\module{cgi} \function{parse_qsl}, except that it is written in C and is
much faster.
Parse a query string given as a string argument (data of type
\mimetype{application/x-www-form-urlencoded}). Data are
returned as a list of name, value pairs.
The optional argument \var{keep_blank_values} is a flag indicating
whether blank values in URL encoded queries should be treated as blank
strings. A true value indicates that blanks should be retained as
blank strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
\strong{Note:} The \var{strict_parsing} argument is not yet implemented.
\end{funcdesc}
|