5.1.1. API Documentation¶
Contains documentation pulled from all modules in Omicron Server
5.1.1.1. api_server¶
Defines the flask app which will run our HTTP application. This also creates a flask-restful API object, which will serve as the router to the objects in
api_views.
api_server.create_token(*args, **kwargs)[source]¶Generate a user’s auth token from the user in Flask’s
Flask.gobject, which acts as an object repository unique to each request. Expects an Authorization header with Basic Auth.Example Request
POST /api/v1/token HTTP/1.1 Host: example.com Content-Type: application/json Authorization: B12kS1l2jS1=Example Response
Content-Type: application/json { "token": "a409a362-d733-11e5-b625-7e14f79230d0", "expiration_date": "2015-01-01T12:00:00" }
Returns: A Flask response object with the token jsonified into ASCII
api_server.hello_world()[source]¶Base URL to confirm that the API actually works. Eventually, this endpoint will serve the OmicronClient. JavaScript UI to users.
Example Response
GET / HTTP/1.1 Content-Type: application/json Hello World!
Returns: Hello, world! Return type: str
5.1.1.2. authentication¶
Contains declarations for HTTP authorization, needed to be put here to avoid a circular import where
api_serverimportsapi_views.users.UserContainer, butapi_views.users.UserContanerrequires anauthobject declared inapi_server
auth._verify_user(username, password)[source]¶Check if the username matches the user. If it does, write the user to
Flask.g()and returnTrue, else returnFalse:param str username: The name of the user to validate :param str password: The password to validate :return:Trueif the user authenticated andFalseif not
auth.verify_password(username_or_token, password=None)[source]¶Callback function for
flask.ext.httpauth.HTTPBasicAuth.verify_password(), used to verify both username and password authentication, as well as authentication tokens.In order to authenticate, the user must use base64 encoding, encode a string of the form
username:password, and submit the encoded string in the request’s Authorization. header.Alternatively, the user can encode their token in base64, and submit this in their Authorization. header. In this case, the incoming password will be
None.Warning
Basic Authentication, unless done over SSL. IS NOT A SECURE FORM ** OF AUTHENTICATION**, as ANYONE can intercept an HTTP request, and decode the information in the Authorization header. This will be solved in two ways
Any production deployment of this API will be done using SSL
- HMAC-SHA256. authentication will be supported, although this is
currently out of scope for the Christmas Release of this API
Parameters:
- username_or_token (str) – The username or token of the user attempting to authenticate into the API
- password (str) – The password or token to be used to authenticate into the API. If no password is supplied, this value will be
None.Returns: True if the password or token is correct, False if otherwise
Rtype bool:
5.1.1.3. config¶
Contains global config parameters for the API
- class
config.Config(conf_dict={'READTHEDOCS_PROJECT': 'omicron-server', 'READTHEDOCS': 'True', 'APPDIR': '/app', 'DEBIAN_FRONTEND': 'noninteractive', 'OLDPWD': '/', 'HOSTNAME': 'version-latest-of-omicronserver-1769447', 'PWD': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/checkouts/latest/docs/source', 'BIN_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/envs/latest/bin', 'READTHEDOCS_VERSION': 'latest', 'PATH': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/envs/latest/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'HOME': '/home/docs'})[source]¶Contains configuration parameters and methods for receiving values from environment variables.
For global configuration, system environment variables have priority, followed by values in this object, then followed by the value in a component’s configuration file.
__init__(conf_dict={'READTHEDOCS_PROJECT': 'omicron-server', 'READTHEDOCS': 'True', 'APPDIR': '/app', 'DEBIAN_FRONTEND': 'noninteractive', 'OLDPWD': '/', 'HOSTNAME': 'version-latest-of-omicronserver-1769447', 'PWD': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/checkouts/latest/docs/source', 'BIN_PATH': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/envs/latest/bin', 'READTHEDOCS_VERSION': 'latest', 'PATH': '/home/docs/checkouts/readthedocs.org/user_builds/omicron-server/envs/latest/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', 'HOME': '/home/docs'})[source]¶Instantiate config parameters from environment variables
Parameters: conf_dict – The dictionary or dictionary-like object from which configuration parameters should be pulled, defaults to os.environ. This is overwritten for testing
__weakref__¶list of weak references to the object (if defined)
5.1.1.4. decorators¶
Contains utilities to decorate endpoints with additional functionality
5.1.1. Decorators¶
A decorator is a function that takes in a function as an argument, and returns a function. In Python, a typical decorator can be used as follows
class UserContainer(Resource): @staticmethod def parse_search_params(params): pass @restful_pagination() def get(self, pag_args): passThe use of the
@symbol is syntactic sugar forparse_search_params = staticmethod(parse_search_params)In order to provide arguments to the decorator, as in the case of
@restful_pagination, another level of indirection is needed.restful_paginationis not a decorator in and of itself, but it returns a decorator that then decorates a particular function.Note
Due to Sphinx Autodoc <http://sphinx-doc.org/ext/autodoc.html>‘s documentation generator, the
__name__and__doc__property of the function to be decorated must be assigned to the__name__and__doc__of the decorator. Seetests.unit.test_decorators.TestRestfulPaginationfor an example of a unit test that tests this behaviour
- class
decorators.PaginationArgs(page, items_per_page, offset)¶
__getnewargs__()¶Return self as a plain tuple. Used by copy and pickle.
__getstate__()¶Exclude the OrderedDict from pickling
- static
__new__(_cls, page, items_per_page, offset)¶Create new instance of PaginationArgs(page, items_per_page, offset)
__repr__()¶Return a nicely formatted representation string
_asdict()¶Return a new OrderedDict which maps field names to their values
- classmethod
_make(iterable, new=<built-in method __new__ of type object at 0x9192c0>, len=<built-in function len>)¶Make a new PaginationArgs object from a sequence or iterable
_replace(_self, **kwds)¶Return a new PaginationArgs object replacing specified fields with new values
items_per_page¶Alias for field number 1
offset¶Alias for field number 2
page¶Alias for field number 0
decorators.restful_pagination(default_items_per_page=1000)[source]¶Wraps a RESTful getter, extracting the arguments
pageanditems_per_pagefrom the URL query parameter. These arguments are then parsed into integers, and returned as a named tuple. consisting of the following variables
page: The number of the page to be displayed
items_per_page: The number of items to be displayed on eachpage
offset: The offset (item number of the first item on thispage)
The PaginationArgs tuple is then injected into the decorated function as a keyword argument (kwarg.), in a similar way to the
@mock.patchdecorator. A usage pattern for this decorator could be@restful_pagination() def paginated_input(pagination_args): with sessionmaker() as session: session.query(Something).limit( pagination_args.limit ).offset( pagination_args.offset ).all()
Parameters: default_items_per_page – The number of items that should be displayed by default. This is to prevent a query with, for example, 300,000 results loading a large amount of data into memory. Returns: A decorator with the default arguments per page configured Return type: function
5.1.1.5. JSON Schema Parser¶
Contains utilities for loading, parsing, and validating inputs against a JSON schema
- exception
json_schema_parser.BadJsonSchemaError[source]¶Thrown if the JSON Schema presented is not a valid draft 3 or draft 4 schema
__weakref__¶list of weak references to the object (if defined)
- exception
json_schema_parser.FileNotFoundError[source]¶Thrown if the parser is unable to find the file
__weakref__¶list of weak references to the object (if defined)
- class
json_schema_parser.JsonSchemaValidator(path)[source]¶Contains utilities for validating JSONSchema from a file
__init__(path)[source]¶Initialize the schema :param path: the path from which the file should be pulled
__weakref__¶list of weak references to the object (if defined)
- static
_read_schema_from_file(path)[source]¶Read the file containing the JSON Schema and return it as a json-loaded dictionary :return:
validate_dict(dict_to_validate)[source]¶Validates a dictionary against
self.json_dict. :param dict dict_to_validate: The dictionary to check againstself.json_dict, representing the base JSON Schema to validate.
Returns: True if the dictionary is allowed by the schema and false if not. The False return also returns a string showing the reason why validation failed.