forked from grisha/mod_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodpython4.tex
More file actions
2683 lines (2133 loc) · 95.5 KB
/
Copy pathmodpython4.tex
File metadata and controls
2683 lines (2133 loc) · 95.5 KB
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
\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 request, 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
virtual 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 process dies.
You can find out the name of the interpreter under which you're
running by peeking at \member{req.interpreter}.
Note that if any third party module is being used which has a C code
component that uses the simplified API for access to the Global
Interpreter Lock (GIL) for Python extension modules, then the interpreter
name must be forcibly set to be \samp{main_interpreter}. This is necessary
as such a module will only work correctly if run within the context of
the first Python interpreter created by the process. If not forced to
run under the \samp{main_interpreter}, a range of Python errors can arise,
each typically referring to code being run in \emph{restricted mode}.
\begin{seealso}
\seetitle[http://www.python.org/doc/current/api/api.html]
{Python C Language API}{Python C Language API}
\seetitle[http://www.python.org/peps/pep-0311.html]
{PEP 0311 - Simplified Global Interpreter Lock Acquisition for Extensions}{PEP 0311 - Simplified Global Interpreter Lock Acquisition for Extensions}
\end{seealso}
\section{Overview of a Request Handler\label{pyapi-handler}}
\indexii{request}{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 by the
user and written in Python. A handler written in Python is not any
different from 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 request object. (Throughout this manual,
the 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 has not handled this
phase of the request to completion and Apache needs to look for
another handler in subsequent modules.
\item
\constant{apache.\emph{HTTP_ERROR}}, meaning an HTTP error occurred.
\var{HTTP_ERROR} can be any of the following:
\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{req.write()}
method.
Client data, such as POST requests, can be read by using the
\method{req.read()} function.
\begin{notice}
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.
\end{notice}
An example of a minimalistic handler might be:
\begin{verbatim}
from mod_python import apache
def requesthandler(req):
req.content_type = "text/plain"
req.write("Hello World!")
return apache.OK
\end{verbatim}
\section{Overview of a Filter Handler\label{pyapi-filter}}
\indexii{filter}{handler}
A \dfn{filter handler} is a function that can alter the input or the
output of the server. There are two kinds of filters - \dfn{input} and
\dfn{output} that apply to input from the client and output to the
client respectively.
At this time mod_python supports only request-level filters, meaning
that only the body of HTTP request or response can be filtered. Apache
provides support for connection-level filters, which will be supported
in the future.
A filter handler receives a \emph{filter} object as its argument. The
request object is available as well via \code{filter.req}, but all
writing and reading should be done via the filter's object read and
write methods.
Filters need to be closed when a read operation returns None
(indicating End-Of-Stream).
The return value of a filter is ignored. Filters cannot decline
processing like handlers, but the same effect can be achieved
by using the \method{filter.pass_on()} method.
Filters must first be registered using \code{PythonInputFilter} or
\code{PythonOutputFilter}, then added using the Apache
\code{Add/SetInputFilter} or \code{Add/SetOutputFilter} directives.
Here is an example of how to specify an output filter, it tells the
server that all .py files should processed by CAPITALIZE filter:
\begin{verbatim}
PythonOutputFilter capitalize CAPITALIZE
AddOutputFilter CAPITALIZE .py
\end{verbatim}
And here is what the code for the \file{capitalize.py} might look
like:
\begin{verbatim}
from mod_python import apache
def outputfilter(filter):
s = filter.read()
while s:
filter.write(s.upper())
s = filter.read()
if s is None:
filter.close()
\end{verbatim}
When writing filters, keep in mind that a filter will be called any
time anything upstream requests an IO operation, and the filter has no
control over the amount of data passed through it and no notion of
where in the request processing it is called. For example, within a
single request, a filter may be called once or five times, and there
is no way for the filter to know beforehand that the request is over
and which of calls is last or first for this request, thought
encounter of an EOS (None returned from a read operation) is a fairly
strong indication of an end of a request.
Also note that filters may end up being called recursively in
subrequests. To avoid the data being altered more than once, always
make sure you are not in a subrequest by examining the \code{req.main}
value.
For more information on filters, see
\citetitle[http://httpd.apache.org/docs-2.0/developer/filters.html]{http://httpd.apache.org/docs-2.0/developer/filters.html}.
\section{Overview of a Connection Handler\label{pyapi-conn}}
\indexii{connection}{handler}
A \dfn{connection handler} handles the connection, starting almost
immediately from the point the TCP connection to the server was
made.
Unlike HTTP handlers, connection handlers receive a \emph{connection}
object as an argument.
Connection handlers can be used to implement protocols. Here is an
example of a simple echo server:
Apache configuration:
\begin{verbatim}
PythonConnectionHandler echo
\end{verbatim}
Contents of \filenq{echo.py} file:
\begin{verbatim}
from mod_python import apache
def connectionhandler(conn):
while 1:
conn.write(conn.readline())
return apache.OK
\end{verbatim}
\section{\module{apache} -- Access to Apache Internals.}
\declaremodule[apache]{extension}{apache}
\modulesynopsis{Access to Apache Internals}
\moduleauthor{Gregory Trubetskoy}{[email protected]}
The Python 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. (The request object also provides an
interface to Apache internals, it is covered in its own section of
this manual.)
\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 functions and
objects. For a more in-depth look at Apache internals, see the
\citetitle[http://httpd.apache.org/dev/]{Apache Developer page}
\subsection{Functions\label{pyapi-apmeth}}
\begin{funcdesc}{log_error}{message\optional{, level, server}}
An interface to the Apache \code{ap_log_error()}
function. \var{message} is a string with the error message,
\var{level} is one of the following flags 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{req.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. When \var{server} is not specified,
the setting of LogLevel does not apply, the LogLevel is dictated by
an httpd compile-time default, usually \code{warn}.
If you have a reference to a request object available, consider using
\method{req.log_error} instead, it will prepend request-specific
information such as the source IP of the request to the log entry.
\end{funcdesc}
\begin{funcdesc}{import_module}{module_name\optional{, autoreload=1, log=0, path=None}}
This function can be used to import modules taking advantage of
mod_python's internal mechanism which reloads modules automatically
if they have changed since last import.
\var{module_name} is a string containing the module name (it can
contain dots, e.g. \code{mypackage.mymodule}); \var{autoreload}
indicates whether the module should be reloaded if it has changed since
last import; when \var{log} is true, a message will be written to
the logs when a module is reloaded; \var{path} allows restricting
modules to specific paths.
Example:
\begin{verbatim}
from mod_python import apache
mymodule = apache.import_module('mymodule', log=1)
\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{allow_methods}{\optional{*args}}
A convenience function to set values in \member{req.allowed}.
\member{req.allowed} is a bitmask that is used to construct the
\samp{Allow:} header. It should be set before returning a
\code{HTTP_NOT_IMPLEMENTED} error.
Arguments can be one or more of the following:
\begin{verbatim}
M_GET
M_PUT
M_POST
M_DELETE
M_CONNECT
M_OPTIONS
M_TRACE
M_PATCH
M_PROPFIND
M_PROPPATCH
M_MKCOL
M_COPY
M_MOVE
M_LOCK
M_UNLOCK
M_VERSION_CONTROL
M_CHECKOUT
M_UNCHECKOUT
M_CHECKIN
M_UPDATE
M_LABEL
M_REPORT
M_MKWORKSPACE
M_MKACTIVITY
M_BASELINE_CONTROL
M_MERGE
M_INVALID
\end{verbatim}
\end{funcdesc}
\begin{funcdesc}{exists_config_define}{name}
This function returns True if the Apache server was launched
with the definition with the given \var{name}. This means
that you can test whether Apache was launched with the \code{-DFOOBAR}
parameter by calling \code{apache.exists_config_define('FOOBAR')}.
\end{funcdesc}
\begin{methoddesc}[server]{register_cleanup}{handler\optional{, data}}
Registers a cleanup. Equivalent to \function{req.register_cleanup()}
or \function{req.server.register_cleanup()}, except that a server or request
object is not required.
\end{methoddesc}
\begin{funcdesc}{config_tree}{}
Returns the server-level configuration tree. This tree does not
include directives from .htaccess files. This is a \emph{copy} of
the tree, modifying it has no effect on the actual configuration.
\end{funcdesc}
\begin{funcdesc}{server_root}{}
Returns the value of ServerRoot.
\end{funcdesc}
\begin{funcdesc}{make_table}{}
This function is obsolete and is an alias to \class{table} (see below).
\end{funcdesc}
\begin{funcdesc}{mpm_query}{code}
Allows querying of the MPM for various parameters such as numbers of
processes and threads. The return value is one of three constants:
\begin{verbatim}
AP_MPMQ_NOT_SUPPORTED = 0 # This value specifies whether
# an MPM is capable of
# threading or forking.
AP_MPMQ_STATIC = 1 # This value specifies whether
# an MPM is using a static # of
# threads or daemons.
AP_MPMQ_DYNAMIC = 2 # This value specifies whether
# an MPM is using a dynamic # of
# threads or daemons.
\end{verbatim}
The \var{code} argument must be one of the following:
\begin{verbatim}
AP_MPMQ_MAX_DAEMON_USED = 1 # Max # of daemons used so far
AP_MPMQ_IS_THREADED = 2 # MPM can do threading
AP_MPMQ_IS_FORKED = 3 # MPM can do forking
AP_MPMQ_HARD_LIMIT_DAEMONS = 4 # The compiled max # daemons
AP_MPMQ_HARD_LIMIT_THREADS = 5 # The compiled max # threads
AP_MPMQ_MAX_THREADS = 6 # # of threads/child by config
AP_MPMQ_MIN_SPARE_DAEMONS = 7 # Min # of spare daemons
AP_MPMQ_MIN_SPARE_THREADS = 8 # Min # of spare threads
AP_MPMQ_MAX_SPARE_DAEMONS = 9 # Max # of spare daemons
AP_MPMQ_MAX_SPARE_THREADS = 10 # Max # of spare threads
AP_MPMQ_MAX_REQUESTS_DAEMON= 11 # Max # of requests per daemon
AP_MPMQ_MAX_DAEMONS = 12 # Max # of daemons by config
\end{verbatim}
Example:
\begin{verbatim}
if apache.mpm_query(apache.AP_MPMQ_IS_THREADED):
# do something
else:
# do something else
\end{verbatim}
\end{funcdesc}
\subsection{Table Object (mp_table)\obindex{table}\label{pyapi-mptable}}
\index{table}
\begin{classdesc}{table}{\optional{mapping-or-sequence}}
Returns a new empty object of type \code{mp_table}. See Section
\ref{pyapi-mptable} for description of the table object. The
\var{mapping-or-sequence} will be used to provide initial values for
the table.
The table object is a wrapper around the Apache APR table. The table
object behaves very much like a dictionary (including the Python 2.2
features such as support of the \code{in} operator, etc.), with the
following differences:
\begin{itemize}
\item
Both keys and values must be strings.
\item
Key lookups are case-insensitive.
\item
Duplicate keys are allowed (see \method{add()} below). When there is
more than one value for a key, a subscript operation returns a list.
\end{itemize}
Much of the information that Apache uses is stored in tables. For
example, \member{req.headers_in} and \member{req.headers_out}.
All the tables that mod_python provides inside the 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}
\versionadded{3.0}
\end{classdesc}
\subsection{Request Object\index{request}\label{pyapi-mprequest}}
The request object is a Python mapping to the Apache
\code{request_rec} structure. When a handler is invoked, it is always
passed a single argument - the request object.
You can dynamically assign attributes to it as a way to communicate
between handlers.
\subsubsection{Request Methods\label{pyapi-mprequest-meth}}
\begin{methoddesc}[request]{add_common_vars}{}
Calls the Apache \cfunction{ap_add_common_vars()} function. After a
call to this method, \member{req.subprocess_env} will contain a
lot of CGI information.
\end{methoddesc}
\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 request (but not filter or
connection) 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. If there is a \code{PythonPath} directive in effect, then
\code{sys.path} will be set exactly according to it (no directories
added, the \var{dir} argument is ignored).
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}
\begin{notice}
If you pass this function an invalid handler, an exception will be
generated at the time an attempt is made to find the handler.
\end{notice}
\end{methoddesc}
\begin{methoddesc}[request]{allow_methods}{methods\optional{, reset}}
Adds methods to the \member{req.allowed_methods} list. This list
will be passed in \code{Allowed:} header if
\constant{HTTP_METHOD_NOT_ALLOWED} or \constant{HTTP_NOT_IMPLEMENTED}
is returned to the client. Note that Apache doesn't do anything to
restrict the methods, this list is only used to construct the
header. The actual method-restricting logic has to be provided in the
handler code.
\var{methods} is a sequence of strings. If \var{reset} is 1, then
the list of methods is first cleared.
\end{methoddesc}
\begin{methoddesc}[request]{document_root}{}
Returns DocumentRoot setting.
\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 mod_python
configuration in effect for this request except for
\code{Python*Handler} and \code{PythonOption} (The latter can be
obtained via \method{req.get_options()}. The table has directives as
keys, and their values, if any, as values.
\end{methoddesc}
\begin{methoddesc}[request]{get_remote_host}{\optional{type, str_is_ip}}
This method is used to determine remote client's DNS name or IP
number. 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 \var{type} argument can specify the following:
\begin{itemize}
\item
\code{apache.REMOTE_HOST} Look up the DNS name. Return None 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}
If \var{str_is_ip} is \code{None} or unspecified, then the return
value is a string representing the DNS name or IP address.
If the optional \var{str_is_ip} argument is not \code{None}, then the
return value is an \code{(address, str_is_ip)} tuple, where \var{str_is_ip}
is non-zero if \code{address} is an IP address string.
On failure, \code{None} is returned.
\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]{internal_redirect}{new_uri}
Internally redirects the request to the \var{new_uri}. \var{new_uri}
must be a string.
The httpd server handles internal redirection by creating a new
request object and processing all request phases. Within an internal
redirect, \code{req.prev} will contain a reference to a request
object from which it was redirected.
\end{methoddesc}
\begin{methoddesc}[request]{is_https}{}
Returns non-zero if the connection is using SSL/TLS. Will always return
zero if the mod_ssl Apache module is not loaded.
You can use this method during any request phase, unlike looking for
the \code{HTTPS} variable in the \code{subprocess_env} member dictionary.
This makes it possible to write an authentication or access handler
that makes decisions based upon whether SSL is being used.
Note that this method will not determine the quality of the
encryption being used. For that you should call the \code{ssl_var_lookup}
method to get one of the \code{SSL_CIPHER*} variables.
\end{methoddesc}
\begin{methoddesc}{log_error}{message\optional{, level}}
An interface to the Apache \code{ap_log_rerror}
function. \var{message} is a string with the error message,
\var{level} is one of the following flags constants:
\begin{verbatim}
APLOG_EMERG
APLOG_ALERT
APLOG_CRIT
APLOG_ERR
APLOG_WARNING
APLOG_NOTICE
APLOG_INFO
APLOG_DEBUG
APLOG_NOERRNO
\end{verbatim}
If you need to write to log and do not have a reference to a request object,
use the \function{apache.log_error} function.
\end{methoddesc}
\begin{methoddesc}[request]{meets_conditions}{}
Calls the Apache \cfunction{ap_meets_conditions()} function which
returns a status code. If \var{status} is \constant{apache.OK}, generate
the content of the response normally. If not, simply return \var{status}.
Note that \member{req.headers_out} should be set prior to calling this
function. The same goes for \member{req.status} if the status differs
from \constant{apache.OK}.
Example:
\begin{verbatim}
...
r.headers_out['ETag'] = "1130794f-3774-4584-a4ea-0ab19e684268"
r.headers_out['Last-Modified'] = 'Wed, 23 Feb 2005 00:00:00 GMT'
r.headers_out['Expires'] = 'Mon, 18 Apr 2005 17:30:00 GMT'
status = r.meets_conditions()
if status != apache.OK:
return status
... do expensive generation of the response content ...
\end{verbatim}
\end{methoddesc}
\begin{methoddesc}[request]{requires}{}
Returns a tuple of strings of arguments to \code{require} directive.
For example, with the following apache configuration:
\begin{verbatim}
AuthType Basic
require user joe
require valid-user
\end{verbatim}
\method{requires()} would return \code{('user joe', 'valid-user')}.
\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
omitted, 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. Absence 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.
\begin{notice}
In accordance with the HTTP specification, most clients will
be terminating lines with \samp{\e r\e n} rather
than simply \samp{\e n}.
\end{notice}
\end{methoddesc}
\begin{methoddesc}[request]{readlines}{\optional{sizehint}}
Reads all or up to \var{sizehint} bytes of lines using
\method{readline} and returns a list of the lines read.
\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}.
It is OK to pass the request object as data, but keep in mind that
when the cleanup is executed, the request processing is already
complete, so doing things like writing to the client is completely
pointless.
If errors are encountered during cleanup processing, they should be in
error log, but otherwise will not affect request processing in any
way, which makes cleanup bugs sometimes hard to spot.
If the server is shut down before the cleanup had a chance to run,
it's possible that it will not be executed.
\end{methoddesc}
\begin{methoddesc}[request]{sendfile}{path\optional{, offset, len}}
Sends \var{len} bytes of file \var{path} directly to the client,
starting at offset \var{offset} using the server's internal
API. \var{offset} defaults to 0, and \var{len} defaults to -1 (send
the entire file).
Returns the number of bytes sent, or raises an IOError exception
on failure.
This function provides the most efficient way to send a file to the
client.
\end{methoddesc}
\begin{methoddesc}[request]{ssl_var_lookup}{var_name}
Looks up the value of the named SSL variable. This method queries
the mod_ssl Apache module directly, and may therefore be used in
early request phases (unlike using the \code{subprocess_env} member.
If the mod_ssl Apache module is not loaded or the variable is not
found then \code{None} is returned.
If you just want to know if a SSL or TLS connection is being used,
you may consider calling the \code{is_https} method instead.
It is unfortunately not possible to get a list of all available
variables with the current mod_ssl implementation, so you must know
the name of the variable you want. Some of the potentially useful
ssl variables are listed below. For a complete list of variables
and a description of their values see the mod_ssl documentation.
\begin{verbatim}
SSL_CIPHER
SSL_CLIENT_CERT
SSL_CLIENT_VERIFY
SSL_PROTOCOL
SSL_SESSION_ID
\end{verbatim}
\begin{notice}
Not all SSL variables are defined or have useful values in every
request phase. Also use caution when relying on these values for
security purposes, as SSL or TLS protocol parameters can often be
renegotiated at any time during a request.
\end{notice}
\end{methoddesc}
\begin{methoddesc}[request]{write}{string\optional{, flush=1}}
Writes \var{string} directly to the client, then flushes the buffer,
unless flush is 0.
\end{methoddesc}
\begin{methoddesc}[request]{flush}{}
Flushes the output buffer.
\end{methoddesc}
\begin{methoddesc}[request]{set_content_length}{len}
Sets the value of \member{req.clength} and the \samp{Content-Length}
header to len. Note that after the headers have been sent out (which
happens just before the first byte of the body is written,
i.e. first call to \member{req.write()}), calling the method is
meaningless.
\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 request object we redirect to.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{prev}
If this is an internal redirect, the 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}
Indicates an HTTP/0.9 ``simple'' request. This means that the
response will contain no headers, only the body. Although this
exists for backwards compatibility with obsolescent browsers, some
people have figred out that setting assbackwards to 1 can be a
useful technique when including part of the response from an
internal redirect to avoid headers being sent.
\end{memberdesc}
\begin{memberdesc}[request]{proxyreq}
A proxy request: one of \constant{apache.PROXYREQ_*} values.
\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 \samp{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]{hostname}
String. Host, as set by full URI or Host: header.
\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. \samp{200 OK}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{status}
Status. One of \constant{apache.HTTP_*} values.
\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 containing the method number.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{allowed}
Integer. A bitvector of the allowed methods. Used to construct the
Allowed: header when responding with
\constant{HTTP_METHOD_NOT_ALLOWED} or
\constant{HTTP_NOT_IMPLEMENTED}. This field is for Apache's internal
use, to set the Allowed: methods use \method{req.allow_methods()}
method, described in section \ref{pyapi-mprequest-meth}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{allowed_xmethods}
Tuple. Allowed extension methods.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{allowed_methods}
Tuple. List of allowed methods. Used in relation with
\constant{METHOD_NOT_ALLOWED}. This member can be modified via \method{req.allow_methods()}
described in section \ref{pyapi-mprequest-meth}.
\emph{(Read-Only})
\end{memberdesc}
\begin{memberdesc}[request]{sent_bodyct}
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]{chunked}
Boolean value indicating when sending chunked transfer-coding.
\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.