The Request class (cubicweb.web.request)

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, as you’ll access to almost every resources through it.

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
  • User and identification:
    • user, instance of cubicweb.entities.authobjs.CWUser corresponding to the authenticated user
  • Session data handling
    • session.data is the dictionary of the session data; it can be manipulated like an ordinary Python dictionary
  • 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 (a 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
    • status_out: control the HTTP status of the response
  • 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
    • execute(*args, **kwargs), executes an RQL query and return the result set
    • 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.repoapi.Connection and cubicweb.web.ConnectionCubicWebRequestBase.

class cubicweb.req.RequestSessionBase(vreg)[source]

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(secure=None)[source]

return the root url of the instance

build_url(*args, **kwargs)[source]

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.

if __secure__ argument is True, the request will try to build a https url.

raises ValueError if None is found in arguments

build_url_params(**kwargs)[source]

return encoded params to incorporate them in a URL

build_url_path(method, kwargs)[source]

return the “path” part of an URL

create_entity(etype, **kwargs)[source]

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)
eid_rset(eid, etype=None)[source]

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()[source]

return a guaranteed empty result

ensure_ro_rql(rql)[source]

raise an exception if the given rql is not a select query

entity_from_eid(eid, etype=None)[source]

return an entity instance for the given eid. No query is done

etype_rset(etype, size=1)[source]

return a fake result set for a particular entity type

find(etype, **kwargs)[source]

find entities of the given type and attribute values.

Returns:A ResultSet
>>> users = find('CWGroup', name=u"users").one()
>>> groups = find('CWGroup').entities()
format_date(date, date_format=None, time=False)[source]

return a string for a date time according to instance’s configuration

format_float(num)[source]

return a string for floating point number according to instance’s configuration

format_time(time)[source]

return a string for a time according to instance’s configuration

get_cache(cachename)[source]

cachename should be dotted names as in :

  • cubicweb.mycache
  • cubes.blog.mycache
  • etc.
parse_datetime(value, etype='Datetime')[source]

get a datetime or time from a string (according to etype) Datetime formatted as Date are accepted

printable_value(attrtype, value, props=None, displaytime=True, formatters={'Interval': <function print_timedelta at 0x7fde5dd82758>, 'Decimal': <function print_float at 0x7fde5dd82848>, 'TZTime': <function print_tztime at 0x7fde5dd825f0>, 'Bytes': <function print_bytes at 0x7fde5dd82398>, 'TZDatetime': <function print_tzdatetime at 0x7fde5dd826e0>, 'BigInt': <function print_int at 0x7fde5dd82488>, 'Time': <function print_time at 0x7fde5dd82578>, 'String': <function print_string at 0x7fde5dd82410>, 'Int': <function print_int at 0x7fde5dd82488>, 'Float': <function print_float at 0x7fde5dd82848>, 'Datetime': <function print_datetime at 0x7fde5dd82668>, 'Boolean': <function print_boolean at 0x7fde5dd827d0>, 'Date': <function print_date at 0x7fde5dd82500>})[source]

return a displayablye value (i.e. unicode string)

property_value(key)[source]

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)[source]

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.

set_language(lang)[source]

install i18n configuration for lang translation.

Raises KeyError if translation doesn’t exist.

url_parse_qsl(querystring)[source]

return a list of (key, val) found in the url quoted query string

url_quote(value, safe='')[source]

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)[source]

returns a unicode unquoted string

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

user_data(*args, **kwargs)

returns a dictionary with this user’s information.

The keys are :

login
The user login
name
The user name, returned by user.name()
email
The user principal email
view(_RequestSessionBase__vid, rset=None, _RequestSessionBase__fallback_oid=None, _RequestSessionBase__registry='views', initargs=None, w=None, **kwargs)[source]

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 dictionary 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.repoapi.Connection(session)[source]

Repository Connection

Holds all connection related data

Database connection resources:

hooks_in_progress, boolean flag telling if the executing query is coming from a repoapi connection or is a query from within the repository (e.g. started by hooks)

cnxset, the connections set to use to execute queries on sources. If the transaction is read only, the connection set may be freed between actual queries. This allows multiple connections with a reasonably low connection set pool size. Control mechanism is detailed below.

set_cnxset(*args, **kwargs)
free_cnxset(*args, **kwargs)

mode, string telling the connections set handling mode, may be one of ‘read’ (connections set may be freed), ‘write’ (some write was done in the connections set, it can’t be freed before end of the transaction), ‘transaction’ (we want to keep the connections set during all the transaction, with or without writing)

Shared data:

data is a dictionary bound to the underlying session, who will be present for the life time of the session. This may be useful for web clients that rely on the server for managing bits of session-scoped data.

transaction_data is a dictionary cleared at the end of the transaction. Hooks and operations may put arbitrary data in there.

Internal state:

pending_operations, ordered list of operations to be processed on commit/rollback

commit_state, describing the transaction commit state, may be one of None (not yet committing), ‘precommit’ (calling precommit event on operations), ‘postcommit’ (calling postcommit event on operations), ‘uncommitable’ (some ValidationError or Unauthorized error has been raised during the transaction and so it must be rolled back).

Hooks controls:

hooks_mode, may be either HOOKS_ALLOW_ALL or HOOKS_DENY_ALL.

enabled_hook_cats, when hooks_mode is HOOKS_DENY_ALL, this set contains hooks categories that are enabled.

disabled_hook_cats, when hooks_mode is HOOKS_ALLOW_ALL, this set contains hooks categories that are disabled.

Security level Management:

read_security and write_security, boolean flags telling if read/write security is currently activated.
add_operation(cnx, *args, **kwargs)[source]

add an operation to be executed at the end of the transaction

add_relation(cnx, *args, **kwargs)[source]

provide direct access to the repository method to add a relation.

This is equivalent to the following rql query:

SET X rtype Y WHERE X eid fromeid, T eid toeid

without read security check but also all the burden of rql execution. You may use this in hooks when you know both eids of the relation you want to add.

add_relations(cnx, *args, **kwargs)[source]

set many relation using a shortcut similar to the one in add_relation

relations is a list of 2-uples, the first element of each 2-uple is the rtype, and the second is a list of (fromeid, toeid) tuples

added_in_transaction(cnx, *args, **kwargs)[source]

return True if the entity of the given eid is being created in the current transaction

cached_entities(cnx, *args, **kwargs)[source]

return the whole entity cache

clear()[source]

reset internal data

commit(cnx, *args, **kwargs)[source]

commit the current session’s transaction

commit_state = None

(None, ‘precommit’, ‘postcommit’, ‘uncommitable’)

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)

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)

delete_relation(cnx, *args, **kwargs)[source]

provide direct access to the repository method to delete a relation.

This is equivalent to the following rql query:

DELETE X rtype Y WHERE X eid fromeid, T eid toeid

without read security check but also all the burden of rql execution. You may use this in hooks when you know both eids of the relation you want to delete.

deleted_in_transaction(cnx, *args, **kwargs)[source]

return True if the entity of the given eid is being deleted in the current transaction

disable_hook_categories(cnx, *args, **kwargs)[source]

disable the given hook categories:

  • on HOOKS_DENY_ALL mode, ensure those categories are not enabled
  • on HOOKS_ALLOW_ALL mode, ensure those categories are disabled
drop_entity_cache(cnx, *args, **kwargs)[source]

drop entity from the cache

If eid is None, the whole cache is dropped

enable_hook_categories(cnx, *args, **kwargs)[source]

enable the given hook categories:

  • on HOOKS_DENY_ALL mode, ensure those categories are enabled
  • on HOOKS_ALLOW_ALL mode, ensure those categories are not disabled
entity_cache(cnx, *args, **kwargs)[source]

get cache entity for eid

entity_type(cnx, *args, **kwargs)[source]

Return entity type for the entity with id eid.

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)

exception(msg, *args, **kwargs)

Convenience method for logging an ERROR with exception information.

execute(cnx, *args, **kwargs)[source]

db-api like method directly linked to the querier execute method.

See cubicweb.dbapi.Cursor.execute() documentation.

get_option_value(cnx, *args, **kwargs)[source]

Return the value for option in the configuration.

get_schema(cnx, *args, **kwargs)[source]

Return the schema currently used by the repository.

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)

is_hook_activated(cnx, *args, **kwargs)[source]

return a boolean telling if the given hook class is currently activated or not

is_hook_category_activated(cnx, *args, **kwargs)[source]

return a boolean telling if the given category is currently activated or not

pending_operations = None

ordered list of operations to be processed on commit/rollback

repo = None

server.Repository object

rollback(cnx, *args, **kwargs)[source]

rollback the current transaction

running_hooks_ops(*args, **kwds)[source]

this context manager should be called whenever hooks or operations are about to be run (but after hook selection)

It will help the undo logic record pertinent metadata or some hooks to run (or not) depending on who/what issued the query.

set_entity_cache(entity)[source]

Add entity to the connection entity cache

system_sql(cnx, *args, **kwargs)[source]

return a sql cursor on the system database

transaction_actions(cnx, *args, **kwargs)[source]

Return an ordered list of actions effectued during that transaction.

If public is true, return only ‘public’ actions, i.e. not ones triggered under the cover by hooks, else return all actions.

raise NoSuchTransaction if the transaction is not found or if the user is not allowed (eg not in managers group).

transaction_data = None

dict containing arbitrary data cleared at the end of the transaction

transaction_info(cnx, *args, **kwargs)[source]

Return transaction object for the given uid.

raise NoSuchTransaction if not found or if session’s user is not allowed (eg not in managers group and the transaction doesn’t belong to him).

undo_transaction(cnx, *args, **kwargs)[source]

Undo the given transaction. Return potential restoration errors.

raise NoSuchTransaction if not found or if user is not allowed (eg not in managers group).

undoable_transactions(cnx, *args, **kwargs)[source]

Return a list of undoable transaction objects by the connection’s user, ordered by descendant transaction time.

Managers may filter according to user (eid) who has done the transaction using the ueid argument. Others will only see their own transactions.

Additional filtering capabilities is provided by using the following named arguments:

  • etype to get only transactions creating/updating/deleting entities of the given type
  • eid to get only transactions applied to entity of the given eid
  • action to get only transactions doing the given action (action in ‘C’, ‘U’, ‘D’, ‘A’, ‘R’). If etype, action can only be ‘C’, ‘U’ or ‘D’.
  • public: when additional filtering is provided, they are by default only searched in ‘public’ actions, unless a public argument is given and set to false.
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.ConnectionCubicWebRequestBase(vreg, https=False, form=None, headers={})[source]