The Request class (cubicweb.web) — CubicWeb 3.10.1

### Navigation

- index
- modules |
- next |
- previous |
- CubicWeb 3.10.1 »
- Web side development »

# The Request class (cubicweb.web)

## Overview

A request instance is created when an HTTP request is sent to the web server. It contains informations such as form parameters, authenticated user, etc. It is a very prevalent object and is used throughout all of the framework and applications.

A request represents a user query, either through HTTP or not (we also talk about RQL queries on the server side for example).

Here is a non-exhaustive list of attributes and methods available on request objects (grouped by category):

- Browser control:
  - ie_browser: tells if the browser belong to the Internet Explorer family
  - xhtml_browser: tells if the browser is able to properly handle XHTML (at the HTTP content_type level)
- User and identification:
  - user, instance of cubicweb.common.utils.User corresponding to the authenticated user
- Session data handling
  - session_data(), returns a dictionary containing all the session data
  - get_session_data(key, default=None), returns a value associated to the given key or the value default if the key is not defined
  - set_session_data(key, value), assign a value to a key
  - del_session_data(key), suppress the value associated to a key
- Edition (utilities for edition control):
  - cancel_edition: resets error url and cleans up pending operations
  - create_entity: utility to create an entity (from an etype, attributes and relation values)
  - datadir_url: returns the url to the merged external resources (CubicWeb‘s web/data directory plus all data directories of used cubes)
  - edited_eids: returns the list of eids of entities that are edited under the current http request
  - eid_rset(eid): utility which returns a result set from an eid
  - entity_from_eid(eid): returns an entity instance from the given eid
  - encoding: returns the encoding of the current HTTP request
  - ensure_ro_rql(rql): ensure some rql query is a data request
  - etype_rset
  - form, dictionary containing the values of a web form
  - encoding, character encoding to use in the response
  - next_tabindex(): returns a monotonically growing integer used to build the html tab index of forms
- HTTP
  - authmode: returns a string describing the authentication mode (http, cookie, ...)
  - lang: returns the user agents/browser’s language as carried by the http request
  - demote_to_html(): in the context of an XHTML compliant browser, this will force emission of the response as an HTML document (using the http content negociation)
- Cookies handling

> - get_cookie(), returns a dictionary containing the value of the header HTTP ‘Cookie’
> - set_cookie(cookie, key, maxage=300), adds a header HTTP Set-Cookie, with a minimal 5 minutes length of duration by default (maxage = None returns a session cookie which will expire when the user closes the browser window)
> - remove_cookie(cookie, key), forces a value to expire

- URL handling
  - build_url(__vid, *args, **kwargs): return an absolute URL using params dictionary key/values as URL parameters. Values are automatically URL quoted, and the publishing method to use may be specified or will be guessed.
  - build_url_params(**kwargs): returns a properly prepared (quoted, separators, ...) string from the given parameters
  - url(), returns the full URL of the HTTP request
  - base_url(), returns the root URL of the web application
  - relative_path(), returns the relative path of the request
- Web resource (.css, .js files, etc.) handling:
  - add_css(cssfiles): adds the given list of css resources to the current html headers
  - add_js(jsfiles): adds the given list of javascript resources to the current html headers
  - add_onload(jscode): inject the given jscode fragment (an unicode string) into the current html headers, wrapped inside a document.ready(...) or another ajax-friendly one-time trigger event
  - add_header(header, values): adds the header/value pair to the current html headers
- And more...
  - set_content_type(content_type, filename=None), adds the header HTTP ‘Content-Type’
  - get_header(header), returns the value associated to an arbitrary header of the HTTP request
  - set_header(header, value), adds an arbitrary header in the response
  - cursor() returns a RQL cursor on the session
  - execute(*args, **kwargs), shortcut to `.cursor().execute()`
  - property_value(key), properties management (CWProperty)
  - dictionary data to store data to share informations between components while a request is executed

Please note that this class is abstract and that a concrete implementation will be provided by the frontend web used (in particular twisted as of today). For the views or others that are executed on the server side, most of the interface of Request is defined in the session associated to the client.

## API

The elements we gave in overview for above are built in three layers, from `cubicweb.req.RequestSessionBase`, `cubicweb.dbapi.DBAPIRequest` and `cubicweb.web.CubicWebRequestBase`.

class `cubicweb.req.` `RequestSessionBase`(vreg)

  base class containing stuff shared by server session and web request

  request/session is the main resources accessor, mainly through it’s vreg attribute:

  Attribute vreg: | the instance’s registry
  Attribute vreg.schema:
  | the instance’s schema
  Attribute vreg.config:
  | the instance’s configuration

  `base_url`()
    return the root url of the instance
  `build_url`(*args, **kwargs)

    return an absolute URL using params dictionary key/values as URL parameters. Values are automatically URL quoted, and the publishing method to use may be specified or will be guessed.

    raises `ValueError` if None is found in arguments

  `build_url_params`(**kwargs)
    return encoded params to incorporate them in an URL
  `create_entity`(etype, **kwargs)

    add a new entity of the given type

    Example (in a shell session):

        >>> c = create_entity('Company', name=u'Logilab')
        >>> create_entity('Person', firstname=u'John', surname=u'Doe',
        ...               works_for=c)

  `describe`(eid)
    return a tuple (type, sourceuri, extid) for the entity with id <eid>
  `eid_rset`(eid, etype=None)
    return a result set for the given eid without doing actual query (we have the eid, we can suppose it exists and user has access to the entity)
  `empty_rset`()
    return a guaranteed empty result
  `ensure_ro_rql`(rql)
    raise an exception if the given rql is not a select query
  `entity_from_eid`(eid, etype=None)
    return an entity instance for the given eid. No query is done
  `etype_rset`(etype, size=1)
    return a fake result set for a particular entity type
  `format_date`(date, date_format=None, time=False)
    return a string for a date time according to instance’s configuration
  `format_float`(num)
    return a string for floating point number according to instance’s configuration
  `format_time`(time)
    return a string for a time according to instance’s configuration
  `get_cache`(cachename)

    cachename should be dotted names as in :

    - cubicweb.mycache
    - cubes.blog.mycache
    - etc.
  `is_internal_session`()
    overrided on the server-side
  `parse_datetime`(value, etype='Datetime')
    get a datetime or time from a string (according to etype) Datetime formatted as Date are accepted
  `property_value`(key)
    return value of the property with the given key, giving priority to user specific value if any, else using site value
  `rebuild_url`(url, **newparams)

    return the given url with newparams inserted. If any new params is already specified in the url, it’s overriden by the new value

    newparams may only be mono-valued.

  `url_parse_qsl`(querystring)
    return a list of (key, val) found in the url quoted query string
  `url_quote`(value, safe='')
    urllib.quote is not unicode safe, use this method to do the necessary encoding / decoding. Also it’s designed to quote each part of a url path and so the ‘/’ character will be encoded as well.
  `url_unquote`(quoted)

    returns a unicode unquoted string

    decoding is based on self.encoding which is the encoding used in url_quote

  `user_data`(*args)
    returns a dictionnary with this user’s information
  `view`(_RequestSessionBase__vid, rset=None, _RequestSessionBase__fallback_oid=None, _RequestSessionBase__registry='views', initargs=None, w=None, **kwargs)

    Select object with the given id (__oid) then render it. If the object isn’t selectable, try to select fallback object if __fallback_oid is specified.

    If specified initargs is expected to be a dictionnary containing arguments that should be given to selection (hence to object’s __init__ as well), but not to render(). Other arbitrary keyword arguments will be given to selection and to render(), and so should be handled by object’s call or cell_call method..

class `cubicweb.dbapi.` `DBAPIRequest`(vreg, session=None)
  classmethod `critical`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘CRITICAL’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

  classmethod `debug`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘DEBUG’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

  `describe`(eid)
    return a tuple (type, sourceuri, extid) for the entity with id <eid>
  classmethod `error`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘ERROR’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

  classmethod `exception`(msg, *args)
    Convenience method for logging an ERROR with exception information.
  `execute`(*args, **kwargs)
    overriden when session is set. By default raise authentication error so authentication is requested.
  `get_shared_data`(key, default=None, pop=False, txdata=False)
    see `Connection.get_shared_data()`
  `hijack_user`(user)
    return a fake request/session using specified user
  classmethod `info`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘INFO’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

  `session_data`(*args, **kwargs)
    return a dictionnary containing session data
  `set_session`(session, user=None)
    method called by the session handler when the user is authenticated or an anonymous connection is open
  `set_shared_data`(key, value, txdata=False, querydata=None)
    see `Connection.set_shared_data()`
  `source_defs`()
    return the definition of sources used by the repository.
  classmethod `warning`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘WARNING’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

class `cubicweb.web.request.` `CubicWebRequestBase`(vreg, https, form=None)

  abstract HTTP request, should be extended according to the HTTP backend

  `add_css`(cssfiles, media=u'all', localfile=True, ieonly=False, iespec=u'[, if lt IE 8], ')

    specify a CSS file to include in the HTML headers

    Parameters: | cssfiles – a CSS filename or a list of CSS filenames media – the CSS’s media if necessary localfile – if True, the default data dir prefix is added to the CSS filename ieonly – True if this css is specific to IE iespec – conditional expression that will be used around the css inclusion. cf: http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx

  `add_header`(header, value)
    add an output HTTP header
  `add_js`(jsfiles, localfile=True)

    specify a list of JS files to include in the HTML headers :param jsfiles: a JS filename or a list of JS filenames :param localfile: if True, the default data dir prefix is added to the

    > JS filename

  `ajax_replace_url`(nodeid, replacemode='replace', **extraparams)

    builds an ajax url that will replace nodeid’s content

    Parameters: | nodeid – the dom id of the node to replace replacemode – defines how the replacement should be done. Possible values are : - ‘replace’ to replace the node’s content with the generated HTML - ‘swap’ to replace the node itself with the generated HTML - ‘append’ to append the generated HTML to the node’s content

    Arbitrary extra named arguments may be given, they will be included as parameters of the generated url.

  `base_url_path`()
    returns the absolute path of the base url
  `cancel_edition`(errorurl)
    remove pending operations and errorurl‘s specific stored data
  classmethod `critical`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘CRITICAL’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

  classmethod `debug`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘DEBUG’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

  `del_page_data`(key=None)
    remove value associated to key in current page data if key is None, all page data will be cleared
  `demote_to_html`()

    helper method to dynamically set request content type to text/html

    The global doctype and xmldec must also be changed otherwise the browser will display ‘<[‘ at the beginning of the page

  `edited_eids`(withtype=False)
    return a list of edited eids
  classmethod `error`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘ERROR’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.error(“Houston, we have a %s”, “major problem”, exc_info=1)

  classmethod `exception`(msg, *args)
    Convenience method for logging an ERROR with exception information.
  `external_resource`(*args, **kwargs)

    return a path to an external resource, using its identifier

    raise KeyError if the resource is not defined

  `extract_entity_params`(eid, minparams=3)
    extract form parameters relative to the given eid
  `from_controller`(*args)
    return the id (string) of the controller issuing the request
  `get_authorization`(*args)
    Parse and return the Authorization header
  `get_cookie`()
    retrieve request cookies, returns an empty cookie if not found
  `get_header`(header, default=None)
    return the value associated with the given input HTTP header, raise KeyError if the header is not set
  `get_page_data`(key, default=None)
    return value associated to key in current page data
  `header_accept_language`(*args, **kwargs)
    returns an ordered list of preferred languages
  `header_authorization`()
    returns a couple (auth-type, auth-value)
  `header_if_modified_since`()
    If the HTTP header If-modified-since is set, return the equivalent mx date time value (GMT), else return None
  `http_method`()
    returns ‘POST’, ‘GET’, ‘HEAD’, etc.
  classmethod `info`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘INFO’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

  `list_form_param`(param, form=None, pop=False)

    get param from form parameters and return its value as a list, skipping internal markers if any

    - if the parameter isn’t defined, return an empty list
    - if the parameter is a single (unicode) value, return a list containing that value
    - if the parameter is already a list or tuple, just skip internal markers

    if pop is True, the parameter is removed from the form dictionnary

  `match_search_state`(rset)
    when searching an entity to create a relation, return True if entities in the given rset may be used as relation end
  `no_script_form_param`(param, value)

    ensure there is no script in a user form param

    by default return a cleaned string instead of raising a security exception

    this method should be called on every user input (form at least) fields that are at some point inserted in a generated html page to protect against script kiddies

  `parse_accept_header`(header)
    returns an ordered list of preferred languages
  `relative_path`(includeparams=True)

    return the normalized path of the request (ie at least relative to the instance’s root, but some other normalization may be needed so that the returned path may be used to compare to generated urls

    Parameter: | includeparams – boolean indicating if GET form parameters should be kept in the path

  `remove_cookie`(cookie, key)
    remove a cookie by expiring it
  `remove_header`(header)
    remove an output HTTP header
  `remove_pending_operations`()

    shortcut to clear req’s pending_{delete,insert} entries

    This is needed when the edition is completed (whether it’s validated or cancelled)

  `reset_headers`()
    used by AutomaticWebTest to clear html headers between tests on the same resultset
  `selected`(url)
    return True if the url is equivalent to currently accessed url
  `set_content_type`(content_type, filename=None, encoding=None)
    set output content type for this request. An optional filename may be given
  `set_cookie`(cookie, key, maxage=300, expires=None)

    set / update a cookie key

    by default, cookie will be available for the next 5 minutes. Give maxage = None to have a “session” cookie expiring when the client close its browser

  `set_header`(header, value, raw=True)
    set an output HTTP header
  `set_page_data`(key, value)
    set value associated to key in current page data
  `set_search_state`(searchstate)
    set a new search state
  `set_session`(session, user=None)
    method called by the session handler when the user is authenticated or an anonymous connection is open
  `setup_params`(params)

    WARNING: we’re intentionaly leaving INTERNAL_FIELD_VALUE here

    subclasses should overrides to

  `update_breadcrumbs`()
    stores the last visisted page in session data
  `update_search_state`()
    update the current search state
  `url`(includeparams=True)
    return currently accessed url
  `user_callback`(cb, cbargs, *args, **kwargs)

    register the given user callback and return an url to call it ready to be inserted in html.

    You can specify the underlying js function to call using a ‘jsfunc’ named args, to one of `userCallback()`, ‘`userCallbackThenUpdateUI()`, ‘`userCallbackThenReloadPage()` (the default). Take care arguments may vary according to the used function.

  `user_rql_callback`(rqlargs, *args, **kwargs)

    register a user callback to execute some rql query and return an url to call it ready to be inserted in html.

    rqlargs should be a tuple containing argument to give to the execute function.

    For other allowed arguments, see `user_callback()` method

  `validate_cache`()

    raise a DirectResponse exception if a cached page along the way exists and is still usable.

    calls the client-dependant implementation of _validate_cache

  `varmaker`

    the rql varmaker is exposed both as a property and as the set_varmaker function since we’ve two use cases:

    - accessing the req.varmaker property to get a new variable name
    - calling req.set_varmaker() to ensure a varmaker is set for later ajax calls sharing our .pageid
  classmethod `warning`(msg, *args, **kwargs)

    Log ‘msg % args’ with severity ‘WARNING’.

    To pass exception information, use the keyword argument exc_info with a true value, e.g.

    logger.warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

  `xhtml_browser`()

    return True if the browser is considered as xhtml compatible.

    If the instance is configured to always return text/html and not application/xhtml+xml, this method will always return False, even though this is semantically different

### Navigation

- index
- modules |
- next |
- previous |
- CubicWeb 3.10.1 »
- Web side development »