Package cherrypy :: Module _cprequest :: Class Request
[hide private]
[frames] | no frames]

Class Request

source code

object --+
         |
        Request

An HTTP request.
    
    This object represents the metadata of an HTTP request message;
    that is, it contains attributes which describe the environment
    in which the request URL, headers, and body were sent (if you
    want tools to interpret the headers and body, those are elsewhere,
    mostly in Tools). This 'metadata' consists of socket data,
    transport characteristics, and the Request-Line. This object
    also contains data regarding the configuration in effect for
    the given URL, and the execution plan for generating a response.
    

app [= None]:
    The cherrypy.Application object which is handling this request.

base [= '']:
    The (scheme://host) portion of the requested URL.

body [= None]:
    
    If the request Content-Type is 'application/x-www-form-urlencoded'
    or multipart, this will be None. Otherwise, this will contain the
    request entity body as a string; this value is set between the
    'before_request_body' and 'before_handler' hooks (assuming that
    process_request_body is True).

body_params [= None]:
    
    If the request Content-Type is 'application/x-www-form-urlencoded' or
    multipart, this will be a dict of the params pulled from the entity
    body; that is, it will be the portion of request.params that come
    from the message body (sometimes called "POST params", although they
    can be sent with various HTTP method verbs). This value is set between
    the 'before_request_body' and 'before_handler' hooks (assuming that
    process_request_body is True).

closed [= False]:
    
    True once the close method has been called, False otherwise.

config [= None]:
    
    A flat dict of all configuration entries which apply to the
    current request. These entries are collected from global config,
    application config (based on request.path_info), and from handler
    config (exactly how is governed by the request.dispatch object in
    effect for this request; by default, handler config can be attached
    anywhere in the tree between request.app.root and the final handler,
    and inherits downward).

cookie [= <SimpleCookie: >]:
    See help(Cookie).

dispatch [= <cherrypy._cpdispatch.Dispatcher object at 0x8626f8c>]:
    
    The object which looks up the 'page handler' callable and collects
    config for the current request based on the path_info, other
    request attributes, and the application architecture. The core
    calls the dispatcher as early as possible, passing it a 'path_info'
    argument.
    
    The default dispatcher discovers the page handler by matching path_info
    to a hierarchical arrangement of objects, starting at request.app.root.
    See help(cherrypy.dispatch) for more information.

error_page [= {}]:
    
    A dict of {error code: response filename or callable} pairs.
    
    The error code must be an int representing a given HTTP error code,
    or the string 'default', which will be used if no matching entry
    is found for a given numeric code.
    
    If a filename is provided, the file should contain a Python string-
    formatting template, and can expect by default to receive format
    values with the mapping keys %(status)s, %(message)s, %(traceback)s,
    and %(version)s. The set of format mappings can be extended by
    overriding HTTPError.set_response.
    
    If a callable is provided, it will be called by default with keyword
    arguments 'status', 'message', 'traceback', and 'version', as for a
    string-formatting template. The callable must return a string which
    will be set to response.body. It may also override headers or perform
    any other processing.
    
    If no entry is given for an error code, and no 'default' entry exists,
    a default template will be used.
    

error_response [= <bound method HTTPError.set_response of HTTPError(500, None)>]:
    
    The no-arg callable which will handle unexpected, untrapped errors
    during request processing. This is not used for expected exceptions
    (like NotFound, HTTPError, or HTTPRedirect) which are raised in
    response to expected conditions (those should be customized either
    via request.error_page or by overriding HTTPError.set_response).
    By default, error_response uses HTTPError(500) to return a generic
    error response to the user-agent.

handler [= None]:
    
    The function, method, or other callable which CherryPy will call to
    produce the response. The discovery of the handler and the arguments
    it will receive are determined by the request.dispatch object.
    By default, the handler is discovered by walking a tree of objects
    starting at request.app.root, and is then passed all HTTP params
    (from the query string and POST body) as keyword arguments.

header_list [= []]:
    
    A list of the HTTP request headers as (name, value) tuples.
    In general, you should use request.headers (a dict) instead.

headers [= {}]:
    
    A dict-like object containing the request headers. Keys are header
    names (in Title-Case format); however, you may get and set them in
    a case-insensitive manner. That is, headers['Content-Type'] and
    headers['content-type'] refer to the same value. Values are header
    values (decoded according to RFC 2047 if necessary). See also:
    http.HeaderMap, http.HeaderElement.

hooks [= cherrypy._cprequest.HookMap(points=['before_error_response', 'on_end_resource', 'on_end_request', 'before_finalize', 'before_handler', 'after_error_response', 'on_start_resource', 'before_request_body'])]:
    
    A HookMap (dict-like object) of the form: {hookpoint: [hook, ...]}.
    Each key is a str naming the hook point, and each value is a list
    of hooks which will be called at that hook point during this request.
    The list of hooks is generally populated as early as possible (mostly
    from Tools specified in config), but may be extended at any time.
    See also: _cprequest.Hook, _cprequest.HookMap, and cherrypy.tools.

is_index [= None]:
    
    This will be True if the current request is mapped to an 'index'
    resource handler (also, a 'default' handler if path_info ends with
    a slash). The value may be used to automatically redirect the
    user-agent to a 'more canonical' URL which either adds or removes
    the trailing slash. See cherrypy.tools.trailing_slash.

local [= http.Host('127.0.0.1', 80, '127.0.0.1')]:
    An http.Host(ip, port, hostname) object for the server socket.

login [= None]:
    
    When authentication is used during the request processing this is
    set to 'False' if it failed and to the 'username' value if it succeeded.
    The default 'None' implies that no authentication happened.

method [= 'GET']:
    
    Indicates the HTTP method to be performed on the resource identified
    by the Request-URI. Common methods include GET, HEAD, POST, PUT, and
    DELETE. CherryPy allows any extension method; however, various HTTP
    servers and gateways may restrict the set of allowable methods.
    CherryPy applications SHOULD restrict the set (on a per-URI basis).

methods_with_bodies [= ('POST', 'PUT')]:
    
    A sequence of HTTP methods for which CherryPy will automatically
    attempt to read a body from the rfile.

params [= {}]:
    
    A dict which combines query string (GET) and request entity (POST)
    variables. This is populated in two stages: GET params are added
    before the 'on_start_resource' hook, and POST params are added
    between the 'before_request_body' and 'before_handler' hooks.

path_info [= '/']:
    
    The 'relative path' portion of the Request-URI. This is relative
    to the script_name ('mount point') of the application which is
    handling this request.

prev [= None]:
    
    The previous Request object (if any). This should be None
    unless we are processing an InternalRedirect.

process_request_body [= True]:
    
    If True, the rfile (if any) is automatically read and parsed,
    and the result placed into request.params or request.body.

protocol [= (1, 1)]:
    The HTTP protocol version corresponding to the set
    of features which should be allowed in the response. If BOTH
    the client's request message AND the server's level of HTTP
    compliance is HTTP/1.1, this attribute will be the tuple (1, 1).
    If either is 1.0, this attribute will be the tuple (1, 0).
    Lower HTTP protocol versions are not explicitly supported.

query_string [= '']:
    
    The query component of the Request-URI, a string of information to be
    interpreted by the resource. The query portion of a URI follows the
    path component, and is separated by a '?'. For example, the URI
    'http://www.cherrypy.org/wiki?a=3&b=4' has the query component,
    'a=3&b=4'.

remote [= http.Host('127.0.0.1', 1111, '127.0.0.1')]:
    An http.Host(ip, port, hostname) object for the client socket.

request_line [= '']:
    
    The complete Request-Line received from the client. This is a
    single string consisting of the request method, URI, and protocol
    version (joined by spaces). Any final CRLF is removed.

rfile [= None]:
    
    If the request included an entity (body), it will be available
    as a stream in this attribute. However, the rfile will normally
    be read for you between the 'before_request_body' hook and the
    'before_handler' hook, and the resulting string is placed into
    either request.params or the request.body attribute.
    
    You may disable the automatic consumption of the rfile by setting
    request.process_request_body to False, either in config for the desired
    path, or in an 'on_start_resource' or 'before_request_body' hook.
    
    WARNING: In almost every case, you should not attempt to read from the
    rfile stream after CherryPy's automatic mechanism has read it. If you
    turn off the automatic parsing of rfile, you should read exactly the
    number of bytes specified in request.headers['Content-Length'].
    Ignoring either of these warnings may result in a hung request thread
    or in corruption of the next (pipelined) request.
    

scheme [= 'http']:
    
    The protocol used between client and server. In most cases,
    this will be either 'http' or 'https'.

script_name [= '']:
    
    The 'mount point' of the application which is handling this request.
    
    This attribute MUST NOT end in a slash. If the script_name refers to
    the root of the URI, it MUST be an empty string (not "/").
    

server_protocol [= 'HTTP/1.1']:
    
    The HTTP version for which the HTTP server is at least
    conditionally compliant.

show_tracebacks [= True]:
    
    If True, unexpected errors encountered during request processing will
    include a traceback in the response body.

stage [= None]:
    
    A string containing the stage reached in the request-handling process.
    This is useful when debugging a live server with hung requests.

throw_errors [= False]:
    
    If True, Request.run will not trap any errors (except HTTPRedirect and
    HTTPError, which are more properly called 'exceptions', not errors).

throws [= (<type 'exceptions.KeyboardInterrupt'>, <type 'exceptions.SystemExit'>, <class 'cherrypy._cperror.InternalRedirect'>)]:
    The sequence of exceptions which Request.run does not trap.

toolmaps [= {}]:
    
    A nested dict of all Toolboxes and Tools in effect for this request,
    of the form: {Toolbox.namespace: {Tool.name: config dict}}.

Nested Classes [hide private]
  __metaclass__
Metaclass for declaring docstrings for class attributes.
Instance Methods [hide private]
 
error_response()
Modify cherrypy.response status, headers, and body to represent self.
source code
 
__init__(self, local_host, remote_host, scheme='http', server_protocol='HTTP/1.1')
Populate a new Request object.
source code
 
close(self)
Run cleanup code.
source code
 
run(self, method, path, query_string, req_protocol, headers, rfile)
Process the Request.
source code
 
respond(self, path_info)
Generate a response for the resource at self.path_info.
source code
 
process_headers(self)
Parse HTTP header data into Python structures.
source code
 
get_resource(self, path)
Call a dispatcher (which sets self.handler and .config).
source code
 
process_body(self)
Convert request.rfile into request.params (or request.body).
source code
 
handle_error(self)
Handle the last unanticipated exception.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Class Variables [hide private]
  prev = None
hash(x)
  prev__doc = ...
  local = http.Host('127.0.0.1', 80, '127.0.0.1')
  local__doc = "An http.Host(ip, port, hostname) object for the ...
  remote = http.Host('127.0.0.1', 1111, '127.0.0.1')
  remote__doc = "An http.Host(ip, port, hostname) object for the...
  scheme = 'http'
  scheme__doc = ...
  server_protocol = 'HTTP/1.1'
  server_protocol__doc = ...
  base = ''
  base__doc = """The (scheme://host) portion of the requested UR...
  request_line = ''
  request_line__doc = ...
  method = 'GET'
  method__doc = ...
  query_string = ''
  query_string__doc = ...
  protocol = (1, 1)
  protocol__doc = """The HTTP protocol version corresponding to ...
  params = {}
  params__doc = ...
  header_list = []
  header_list__doc = ...
  headers = {}
  headers__doc = ...
  cookie = <SimpleCookie: >
  cookie__doc = """See help(Cookie)."""
  rfile = None
hash(x)
  rfile__doc = ...
  process_request_body = True
  process_request_body__doc = ...
  methods_with_bodies = ('POST', 'PUT')
  methods_with_bodies__doc = ...
  body = None
hash(x)
  body__doc = ...
  body_params = None
hash(x)
  body_params__doc = ...
  dispatch = cherrypy.dispatch.Dispatcher()
  dispatch__doc = ...
  script_name = ''
  script_name__doc = ...
  path_info = '/'
  path_info__doc = ...
  login = None
hash(x)
  login__doc = ...
  app = None
hash(x)
  app__doc = """The cherrypy.Application object which is handlin...
  handler = None
hash(x)
  handler__doc = ...
  toolmaps = {}
  toolmaps__doc = ...
  config = None
hash(x)
  config__doc = ...
  is_index = None
hash(x)
  is_index__doc = ...
  hooks = cherrypy._cprequest.HookMap(points=['before_error_resp...
  hooks__doc = ...
  error_response__doc = ...
  error_page = {}
  error_page__doc = ...
  show_tracebacks = True
  show_tracebacks__doc = ...
  throws = (<type 'exceptions.KeyboardInterrupt'>, <type 'except...
  throws__doc = """The sequence of exceptions which Request.run ...
  throw_errors = False
  throw_errors__doc = ...
  closed = False
  closed__doc = ...
  stage = None
hash(x)
  stage__doc = ...
  namespaces = cherrypy._cpconfig.NamespaceSet({'hooks': <functi...
Properties [hide private]

Inherited from object: __class__

Method Details [hide private]

error_response()

source code 

Modify cherrypy.response status, headers, and body to represent self.

CherryPy uses this internally, but you can also use it to create an HTTPError object and set its output without *raising* the exception.

__init__(self, local_host, remote_host, scheme='http', server_protocol='HTTP/1.1')
(Constructor)

source code 

Populate a new Request object.

local_host should be an http.Host object with the server info. remote_host should be an http.Host object with the client info. scheme should be a string, either "http" or "https".

Overrides: object.__init__

close(self)

source code 

Run cleanup code. (Core)

run(self, method, path, query_string, req_protocol, headers, rfile)

source code 
Process the Request. (Core)

method, path, query_string, and req_protocol should be pulled directly
    from the Request-Line (e.g. "GET /path?key=val HTTP/1.0").
path should be %XX-unquoted, but query_string should not be.
headers should be a list of (name, value) tuples.
rfile should be a file-like object containing the HTTP request entity.

When run() is done, the returned object should have 3 attributes:
  status, e.g. "200 OK"
  header_list, a list of (name, value) tuples
  body, an iterable yielding strings

Consumer code (HTTP servers) should then access these response
attributes to build the outbound stream.

respond(self, path_info)

source code 

Generate a response for the resource at self.path_info. (Core)

process_headers(self)

source code 

Parse HTTP header data into Python structures. (Core)

get_resource(self, path)

source code 

Call a dispatcher (which sets self.handler and .config). (Core)

process_body(self)

source code 

Convert request.rfile into request.params (or request.body). (Core)

handle_error(self)

source code 

Handle the last unanticipated exception. (Core)


Class Variable Details [hide private]

prev__doc

Value:
"""
    The previous Request object (if any). This should be None
    unless we are processing an InternalRedirect."""

local__doc

Value:
"An http.Host(ip, port, hostname) object for the server socket."

remote__doc

Value:
"An http.Host(ip, port, hostname) object for the client socket."

scheme__doc

Value:
"""
    The protocol used between client and server. In most cases,
    this will be either 'http' or 'https'."""

server_protocol__doc

Value:
"""
    The HTTP version for which the HTTP server is at least
    conditionally compliant."""

base__doc

Value:
"""The (scheme://host) portion of the requested URL."""

request_line__doc

Value:
"""
    The complete Request-Line received from the client. This is a
    single string consisting of the request method, URI, and protocol
    version (joined by spaces). Any final CRLF is removed."""

method__doc

Value:
"""
    Indicates the HTTP method to be performed on the resource identifi\
ed
    by the Request-URI. Common methods include GET, HEAD, POST, PUT, a\
nd
    DELETE. CherryPy allows any extension method; however, various HTT\
P
    servers and gateways may restrict the set of allowable methods.
...

query_string__doc

Value:
"""
    The query component of the Request-URI, a string of information to\
 be
    interpreted by the resource. The query portion of a URI follows th\
e
    path component, and is separated by a '?'. For example, the URI
    'http://www.cherrypy.org/wiki?a=3&b=4' has the query component,
    'a=3&b=4'."""

protocol__doc

Value:
"""The HTTP protocol version corresponding to the set
        of features which should be allowed in the response. If BOTH
        the client's request message AND the server's level of HTTP
        compliance is HTTP/1.1, this attribute will be the tuple (1, 1\
).
        If either is 1.0, this attribute will be the tuple (1, 0).
        Lower HTTP protocol versions are not explicitly supported."""

params__doc

Value:
"""
    A dict which combines query string (GET) and request entity (POST)
    variables. This is populated in two stages: GET params are added
    before the 'on_start_resource' hook, and POST params are added
    between the 'before_request_body' and 'before_handler' hooks."""

header_list__doc

Value:
"""
    A list of the HTTP request headers as (name, value) tuples.
    In general, you should use request.headers (a dict) instead."""

headers__doc

Value:
"""
    A dict-like object containing the request headers. Keys are header
    names (in Title-Case format); however, you may get and set them in
    a case-insensitive manner. That is, headers['Content-Type'] and
    headers['content-type'] refer to the same value. Values are header
    values (decoded according to RFC 2047 if necessary). See also:
    http.HeaderMap, http.HeaderElement."""

rfile__doc

Value:
"""
    If the request included an entity (body), it will be available
    as a stream in this attribute. However, the rfile will normally
    be read for you between the 'before_request_body' hook and the
    'before_handler' hook, and the resulting string is placed into
    either request.params or the request.body attribute.
    
    You may disable the automatic consumption of the rfile by setting
...

process_request_body__doc

Value:
"""
    If True, the rfile (if any) is automatically read and parsed,
    and the result placed into request.params or request.body."""

methods_with_bodies__doc

Value:
"""
    A sequence of HTTP methods for which CherryPy will automatically
    attempt to read a body from the rfile."""

body__doc

Value:
"""
    If the request Content-Type is 'application/x-www-form-urlencoded'
    or multipart, this will be None. Otherwise, this will contain the
    request entity body as a string; this value is set between the
    'before_request_body' and 'before_handler' hooks (assuming that
    process_request_body is True)."""

body_params__doc

Value:
"""
    If the request Content-Type is 'application/x-www-form-urlencoded'\
 or
    multipart, this will be a dict of the params pulled from the entit\
y
    body; that is, it will be the portion of request.params that come
    from the message body (sometimes called "POST params", although th\
ey
...

dispatch__doc

Value:
"""
    The object which looks up the 'page handler' callable and collects
    config for the current request based on the path_info, other
    request attributes, and the application architecture. The core
    calls the dispatcher as early as possible, passing it a 'path_info\
'
    argument.
    
...

script_name__doc

Value:
"""
    The 'mount point' of the application which is handling this reques\
t.
    
    This attribute MUST NOT end in a slash. If the script_name refers \
to
    the root of the URI, it MUST be an empty string (not "/").
    """

path_info__doc

Value:
"""
    The 'relative path' portion of the Request-URI. This is relative
    to the script_name ('mount point') of the application which is
    handling this request."""

login__doc

Value:
"""
    When authentication is used during the request processing this is
    set to 'False' if it failed and to the 'username' value if it succ\
eeded.
    The default 'None' implies that no authentication happened."""

app__doc

Value:
"""The cherrypy.Application object which is handling this request."""

handler__doc

Value:
"""
    The function, method, or other callable which CherryPy will call t\
o
    produce the response. The discovery of the handler and the argumen\
ts
    it will receive are determined by the request.dispatch object.
    By default, the handler is discovered by walking a tree of objects
    starting at request.app.root, and is then passed all HTTP params
...

toolmaps__doc

Value:
"""
    A nested dict of all Toolboxes and Tools in effect for this reques\
t,
    of the form: {Toolbox.namespace: {Tool.name: config dict}}."""

config__doc

Value:
"""
    A flat dict of all configuration entries which apply to the
    current request. These entries are collected from global config,
    application config (based on request.path_info), and from handler
    config (exactly how is governed by the request.dispatch object in
    effect for this request; by default, handler config can be attache\
d
    anywhere in the tree between request.app.root and the final handle\
...

is_index__doc

Value:
"""
    This will be True if the current request is mapped to an 'index'
    resource handler (also, a 'default' handler if path_info ends with
    a slash). The value may be used to automatically redirect the
    user-agent to a 'more canonical' URL which either adds or removes
    the trailing slash. See cherrypy.tools.trailing_slash."""

hooks

Value:
cherrypy._cprequest.HookMap(points=['before_error_response', 'on_end_r\
esource', 'on_end_request', 'before_finalize', 'before_handler', 'afte\
r_error_response', 'on_start_resource', 'before_request_body'])

hooks__doc

Value:
"""
    A HookMap (dict-like object) of the form: {hookpoint: [hook, ...]}\
.
    Each key is a str naming the hook point, and each value is a list
    of hooks which will be called at that hook point during this reque\
st.
    The list of hooks is generally populated as early as possible (mos\
tly
...

error_response__doc

Value:
"""
    The no-arg callable which will handle unexpected, untrapped errors
    during request processing. This is not used for expected exception\
s
    (like NotFound, HTTPError, or HTTPRedirect) which are raised in
    response to expected conditions (those should be customized either
    via request.error_page or by overriding HTTPError.set_response).
    By default, error_response uses HTTPError(500) to return a generic
...

error_page__doc

Value:
"""
    A dict of {error code: response filename or callable} pairs.
    
    The error code must be an int representing a given HTTP error code\
,
    or the string 'default', which will be used if no matching entry
    is found for a given numeric code.
    
...

show_tracebacks__doc

Value:
"""
    If True, unexpected errors encountered during request processing w\
ill
    include a traceback in the response body."""

throws

Value:
(<type 'exceptions.KeyboardInterrupt'>,
 <type 'exceptions.SystemExit'>,
 <class 'cherrypy._cperror.InternalRedirect'>)

throws__doc

Value:
"""The sequence of exceptions which Request.run does not trap."""

throw_errors__doc

Value:
"""
    If True, Request.run will not trap any errors (except HTTPRedirect\
 and
    HTTPError, which are more properly called 'exceptions', not errors\
)."""

closed__doc

Value:
"""
    True once the close method has been called, False otherwise."""

stage__doc

Value:
"""
    A string containing the stage reached in the request-handling proc\
ess.
    This is useful when debugging a live server with hung requests."""

namespaces

Value:
cherrypy._cpconfig.NamespaceSet({'hooks': <function hooks_namespace at\
 0x8620e2c>, 'error_page': <function error_page_namespace at 0x862856c\
>, 'request': <function request_namespace at 0x86284fc>, 'response': <\
function response_namespace at 0x8628534>, 'tools': <cherrypy._cptools\
.Toolbox object at 0x85e9eac>})