Warning
Starting from CubicWeb version 4.0 all code related to generating html views has been moved to the Cube cubicweb_web.
If you want to migrate a project from 3.38 to 4.* while still using all the
html views you need to both install the cubicweb_web cube AND add it to
your dependencies and run add_cube('web')
.
cubicweb_web can be installed from pypi this way:
pip install cubicweb_web
We donât plan to maintain the features in cubicweb_web in the long run; we are moving to a full javascript frontend using both cubicweb_api (which exposes a HTTP API) and @cubicweb/client as a frontend javascript toolkit.
In the long run cubicweb_api will be merged inside of CubicWeb.
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
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. 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(*args, **kwargs)#
- class cubicweb.repoapi.Connection(repo, user)[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.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/rollbackcommit_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â (someValidationError
orUnauthorized
error has been raised during the transaction and so it must be rolled back).Hooks controls:
- deny_all_hooks_but(*categories)[source]#
Context manager to disable all hooks but those in the given categories.
- allow_all_hooks_but(*categories)[source]#
Context manager to enable all hooks but those in the given categories.
Security level Management:
read_security
andwrite_security
, boolean flags telling if read/write security is currently activated.- add_operation(operation, index=None)[source]#
add an operation to be executed at the end of the transaction
- add_relation(fromeid, rtype, toeid)[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(relations)[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(eid)[source]#
return True if the entity of the given eid is being created in the current transaction
- allow_all_hooks_but(*categories)[source]#
Context manager to enable all hooks but those in the given categories.
- commit_state#
(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=True)
- 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=True)
- delete_relation(fromeid, rtype, toeid)[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(eid)[source]#
return True if the entity of the given eid is being deleted in the current transaction
- deny_all_hooks_but(*categories)[source]#
Context manager to disable all hooks but those in the given categories.
- 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=True)
- exception(msg, *args, exc_info=True, **kwargs)#
Convenience method for logging an ERROR with exception information.
- execute(rql, kwargs=None, build_descr=True)[source]#
db-api like method directly linked to the querier execute method.
See
cubicweb.dbapi.Cursor.execute()
documentation.
- 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=True)
- is_hook_activated(hook)[source]#
return a boolean telling if the given hook class is currently activated or not
- is_hook_category_activated(category)[source]#
return a boolean telling if the given category is currently activated or not
- pending_operations#
ordered list of operations to be processed on commit/rollback
- repo#
server.Repository object
- running_hooks_ops()[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.
- system_sql(sql, args=None, rollback_on_failure=True, rql_query_tracing_token=None)[source]#
return a sql cursor on the system database
- transaction_actions(txuuid, public=True)[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#
dict containing arbitrary data cleared at the end of the transaction
- transaction_info(txuuid)[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(txuuid)[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(ueid=None, **actionfilters)[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=True)
- class cubicweb_web.request.ConnectionCubicWebRequestBase(*args, **kwargs)#
- Vreg
Vregistry,
- Form
Forms value
- Headers
dict, request header