request

The request object is an instance of the ubiquitous web2py class that is called gluon.storage.Storage, which extends the Python dict class. It is basically a dictionary, but the item values can also be accessed as attributes:

  1. request.vars

is the same as:

  1. request['vars']

Unlike a dictionary, if an attribute (or key) does not exist, it does not raise an exception. Instead, it returns None.

It is sometimes useful to create your own Storage objects. You can do so as follows:

  1. from gluon.storage import Storage
  2. my_storage = Storage() # empty storage object
  3. my_other_storage = Storage(dict(a=1, b=2)) # convert dictionary to Storage

request has the following items/attributes, some of which are also an instance of the Storage class:

  • request.cookies: a Cookie.SimpleCookie() object containing the cookies passed with the HTTP request. It acts like a dictionary of cookies. Each cookie is a Morsel object [morsel].
  • request.env: a Storage object containing the environment variables passed to the controller, including HTTP header variables from the HTTP request and standard WSGI parameters. The environment variables are all converted to lower case, and dots are converted to underscores for easier memorization.
  • request.application: the name of the requested application.
  • request.controller: the name of the requested controller.
  • request.function: the name of the requested function.
  • request.extension: the extension of the requested action. It defaults to “html”. If the controller function returns a dictionary and does not specify a view, this is used to determine the extension of the view file that will render the dictionary (parsed from the request.env.path_info).
  • request.folder: the application directory. For example if the application is “welcome”, request.folder is set to the absolute path “/path/to/welcome”. In your programs, you should always use this variable and the os.path.join function to build paths to the files you need to access. Although web2py always uses absolute paths, it is a good rule never to explicitly change the current working folder (whatever that is) since this is not a thread-safe practice.
  • request.now: a datetime.datetime object storing the datetime of the current request.
  • request.utcnow: a datetime.datetime object storing the UTC datetime of the current request.
  • request.args: A list of the URL path components following the controller function name; equivalent to request.env.path_info.split('/')[3:]
  • request.vars: a gluon.storage.Storage object containing all request parameters.
  • request.get_vars: a gluon.storage.Storage object containing only parameters passed into the query string (a request to /a/c/f?var1=1&var2=2 will end in {var1: "1", var2: "2"})
  • request.post_vars: a gluon.storage.Storage object containing only the parameters passed into the body of the request (usually in POST, PUT, DELETE requests).
  • request.client: The ip address of the client as determined by, if present, request.env.http_x_forwarded_for or by request.env.remote_addr otherwise. While this is useful it should not be trusted because the http_x_forwarded_for can be spoofed.
  • request.is_local: True if the client is localhost, False otherwise. Should work behind a proxy if the proxy supports http_x_forwarded_for.
  • request.is_https: True if the request is using the HTTPS protocol, False otherwise.
  • request.body: a read-only file stream that contains the body of the HTTP request. This is automatically parsed to get the request.post_vars and then rewinded. It can be read with request.body.read().
  • request.ajax is True if the function is being called via an Ajax request.
  • request.cid is the id of the component that generated the Ajax request (if any). You can read more about components in Chapter 12.
  • request.requires_https() prevents further code execution if the request is not over HTTPS and redirects the visitor to the current page over HTTPS.
  • request.restful this is a new and very useful decorator that can be used to change the default behavior of web2py actions by separating GET/POST/PUT/DELETE requests. It will be discussed in some detail in Chapter 10.
  • request.user_agent() parses the user_agent field from the client and returns the information in the form of a dictionary. It is useful to detect mobile devices. It uses “gluon/contrib/user_agent_parser.py” created by Ross Peoples. To see what it does, try to embed the following code in a view:

    1. {{=BEAUTIFY(request.user_agent())}}
  • request.global_settings contains web2py system wide settings. They are set automatically and you should not change them. For example request.global_settings.gluon_parent contains the full path to the web2py folder, request.global_settings.is_pypy determines if web2py is running on PyPy.

  • request.wsgi is a hook that allows you to call third party WSGI applications from inside actions

The latter includes:

  • request.wsgi.environ
  • request.wsgi.start_response
  • request.wsgi.middleware

their usage is discussed at the end of this chapter in WSGI section.

As an example, the following call on a typical system:

  1. http://127.0.0.1:8000/examples/default/status/x/y/z?p=1&q=2

results in the following request object:

variablevalue
request.applicationexamples
request.controllerdefault
request.functionstatus
request.extensionhtml
request.viewstatus
request.folderapplications/examples/
request.args[‘x’, ‘y’, ‘z’]
request.vars<Storage {‘p’: 1, ‘q’: 2}>
request.get_vars<Storage {‘p’: 1, ‘q’: 2}>
request.post_vars<Storage {}>
request.is_localFalse
request.is_httpsFalse
request.ajaxFalse
request.cidNone
request.wsgi<hook>
request.env.content_length0
request.env.content_type
request.env.http_accepttext/xml,text/html;
request.env.http_accept_encodinggzip, deflate
request.env.http_accept_languageen
request.env.http_cookiesession_id_examples=127.0.0.1.119725
request.env.http_host127.0.0.1:8000
request.env.http_refererhttp://web2py.com/
request.env.http_user_agentMozilla/5.0
request.env.path_info/examples/simple_examples/status
request.env.query_stringp=1&q=2
request.env.remote_addr127.0.0.1
request.env.request_methodGET
request.env.script_name
request.env.server_name127.0.0.1
request.env.server_port8000
request.env.server_protocolHTTP/1.1
request.env.server_softwareRocket 1.2.6
request.env.web2py_path/Users/mdipierro/web2py
request.env.web2py_versionVersion 2.4.1
request.env.wsgi_errors<open file, mode ‘w’ at >
request.env.wsgi_input
request.env.wsgi_url_schemehttp

Which environment variables are actually defined depends on the web server. Here we are assuming the built-in Rocket wsgi server. The set of variables is not much different when using the Apache web server.

The request.env.http_* variables are parsed from the request HTTP header.

The request.env.web2py_* variables are not parsed from the web server environment, but are created by web2py in case your applications need to know about the web2py location and version, and whether it is running on the Google App Engine (because specific optimizations may be necessary).

Also notice the request.env.wsgi_* variables. They are specific to the wsgi adapter.