unrest.rest
Rest
Rest(self,
unrest,
Model,
methods=['GET'],
name=None,
only=None,
exclude=None,
query=None,
properties=None,
relationships=None,
allow_batch=False,
auth=None,
read_auth=None,
write_auth=None,
validators=None,
validation_error_code=500,
primary_keys=None,
defaults=None,
fixed=None,
idiom=UnRestIdiom,
SerializeClass=Serialize,
DeserializeClass=Deserialize)
This is the entry point for generating a REST endpoint for a specific model
The final uri if the path is '/api' and version 'v2' would be:
/api/v2/model
and /api/v2/model/pk1/pk2
and if model is not in the
public schema /api/v2/schema/model
and /api/v2/schema/model/pk1/pk2
.
Usage:
rest = UnRest(app)
def name_validator(field):
if len(field.value) > 12:
raise field.ValidationError(
'Name is too long (max 12 characters).')
return field.value
rest(Person, only=['name', 'sex', 'age'], methods=rest.all,
query=lambda q: q.filter(Person.age > 16),
validators={'name': name_validator})
Arguments
- unrest: The unrest instance given automatically on UnRest call.
- Model: The sqlalchemy orm model class.
- methods: The allowed method list on this endpoint. Possible values are GET, PUT, POST, DELETE, PATCH and rest.all
- name: If specified replaces the model name in url.
- only: If specified restricts the json fields to this list.
- exclude: If specified removes the json fields in this list.
- query: A function that takes the Model query and returns your specific query. Can be useful to filter data for all the methods.
- properties: A list of additional properties to retrieve on the model.
- relationships: A mapping of relationships and rest endpoints to fetch with the model.
- allow_batch: Allow batch operations (PUT, DELETE and PATCH) without primary key.
- auth: A decorator that will always be called.
- read_auth: A decorator that will be called on GET.
- write_auth: A decorator that will be called on PUT, POST, DELETE and PATCH.
- validators: A mapping of field names and validation functions.
A validator function takes a
Validatable
object as parameter and must return the final value for the field or raise arest.ValidationError(reason)
(whererest = Unrest()
) - validation_error_code: The http return code when the validation fails. Defaults to 500
- primary_keys: A list of column names to use as primary_keys (use real db primary keys by default)
- defaults: A mapping of column -> values which sets the default value of the columns when the column is not present in the payload. Can be a callable, in this case it will be called at runtime with the payload as argument.
- fixed: A mapping of column -> values which replaces the values present or not in the payload. Can be a callable, in this case it will be called at runtime with the payload as argument.
- SerializeClass: An alternative
Serialize
class. - DeserializeClass: An alternative
Deserialize
class.
columns
Gets all columns of this model column_property
included.
mapper
Get the SQLAlchemy mapper of this Model.
name_parts
Returns a tuple containing optionally the schema of this table and its name.
path
Gets the root path of this endpoint.
primary_keys
This model primary keys names.
query
Gets the current query associated to this Model.
session
Shortcut property to the UnRest
session.
table
This Model table name.
undefered_query
Gets the query with all attributes undefered.
get
Rest.get(payload, **pks)
The GET method
- With no arguments: Returns all query elements. (/api/model/)
- With primary keys: Returns the element in query with the primary keys. (/api/model/pk)
Arguments
- payload: The request content ignored for GET.
- pks: The primary keys in url if any.
put
Rest.put(payload, **pks)
The PUT method
- With no arguments: If allow_batch set to true replace all the query elements with the ones in the request payload.
- With primary keys: Create or replace the element associated with the primary keys from the one in the request payload.
Arguments
- payload: The request content containing new elements.
- pks: The primary keys in url if any.
post
Rest.post(payload, **pks)
The POST method
- With no arguments: Add element from request payload.
- With primary keys: Correspond to new collection creation. Unused.
Arguments
- payload: The request content containing the new element.
- pks: The primary keys in url if any.
delete
Rest.delete(payload, **pks)
The DELETE method
- With no arguments: If allow_batch set to true delete all query elements.
- With primary keys: Delete the element associated with the primary keys.
Arguments
- payload: The request content ignored in DELETE.
- pks: The primary keys of the element to delete.
patch
Rest.patch(payload, **pks)
The PATCH method
- With no arguments: If allow_batch set to true patch existing elements with element attributes specified in the request payload.
- With primary keys: Patch only one
Arguments
- payload: The request content containing a list of attributes to be patched.
- pks: The primary keys of the element to patch.
options
Rest.options(payload, **pks)
The OPTIONS method
Returns a description of this rest endpoint.
declare
Rest.declare(method, manual_commit=False)
A decorator to register an alternative method. The original is still callable with rest.{method}
fruit = rest(Fruit)
@fruit.declare('GET')
def get(payload, fruit_id=None):
rv = fruit.get(payload, fruit_id=fruit_id)
return {
'occurences': rv['occurences'],
'objects': [
{'id': obj['fruit_id']} for obj in rv['objects']
]
}
Arguments
- method: The method to override ('GET' for exemple)
- manual_commit: Set this to True to prevent auto commit after route call
sub
Rest.sub(query_factory, **kwargs)
This methods return a copy of the current rest endpoint and takes a
query_factory
argument to alter the current query.
Arguments
- query_factory: A function that takes the original query in parameter and returns a new query.
- **kwargs: Can be used to override Rest constructor arguments (query is not supported)
Returns
A Rest
endpoint copied from this one
parameters_to_pks
Rest.parameters_to_pks(parameters)
Transform query parameters into primary keys mapping with deserialized values.
deserialize
Rest.deserialize(payload, item, blank_missing=True)
Deserialize the payload item in the provided item.
Arguments
- payload: The payload containing the item object
- item: An instance of the model to put values in
- blank_missing: Set non-provided by payload item attributes at None
deserialize_all
Rest.deserialize_all(payload)
Deserialize all the payload items.
Arguments
- payload: The payload containing the item list
serialize
Rest.serialize(item)
Serialize an item
with the given SerializeClass
serialize_all
Rest.serialize_all(items)
Serialize all items and return a mapping containing:
Returns
A dict containing
:
- objects: The serialized objects
- primary_keys: The list of primary keys defined for this rest endpoint
- occurences: The number of total occurences (without limit)
- offset if there's a query offset
- limit if there's a query limit
set_defaults
Rest.set_defaults(payload, columns)
Sets in payload item all the fixed and defaults values
Validatable
Rest.Validatable(value, name, item, ValidationError)
A validatable class that is used as validators argument.
Arguments
- value: The current field value
- name: The current field name
- item: The current item
- ValidationError: The
ValidationError
Exception to raise on validation error.
validate
Rest.validate(item, errors=None)
Validates all validators columns against validators.
Raise RestError if validation errors.
validate_all
Rest.validate_all(items)
Calls validate on all the items
and raise an error if any does not
validate.
Arguments
- items: A list of item to validate
Raises
A RestError
on validation error
raise_error
Rest.raise_error(status, message, extra=None)
Shortcut function to raise_error
.
route
Rest.route(method, request)
This is the entry point for any route method ( get
, post
, put
,
delete, patch
, options
), it takes the Request
and
returns the Response
.
Exhaustively it
- converts request parameters into primary keys values
- calls the current idiom request_to_payload
- checks auth with read_auth
, write_auth
and auth
if defined
- calls the route associated with the HTTP method
, either by default
or overidden with declare
, with the previously obtained payload
- commits the session if manual_commit
is False
and method is
amongst modification ones
- and finally calls data_to_response
with the
return value of the wrapped function to return
the Response
Arguments
- method: The HTTP method which is curried in a partial
- request: The current
Request
Returns
The Response
of this request
wrap_auth_route
Rest.wrap_auth_route(method, route)
This takes a route and apply auth wrappers around it.
inner_route
Rest.inner_route(request, payload, **pks)
This is the inner route wrapped by the auth wrappers. It takes the request and the deserialized payload/primary keys.
Arguments
- request: The current
Request
- payload: The deserialized payload of this request
- **pks: The deserialized primary keys if any
Returns
The Response
of this request
register_method
Rest.register_method(method)
Tells the framework to register the route
function or an overidden one
associated with the http method
.
Arguments
- method: The http method to register the route with
has
Rest.has(pks)
Returns whether the pks dict has values in it.
get_from_pk
Rest.get_from_pk(query, **pks)
Get the item from query
that has **pks
or None if not found.
get_all_from_pks
Rest.get_all_from_pks(query, items_pks)
Get all items from query
correponding to the primary keys items_pks
in one query.
query_request
Rest.query_request(*args, **kwds)
Context manager that sets the _query_alterer
to the idiom alter_query
and restore it to identity at exit.