flask_restful_dbbase.resources package

Submodules

flask_restful_dbbase.resources.collection_model_resource module

” This module implements a starting point for collection model resources.

class flask_restful_dbbase.resources.collection_model_resource.CollectionModelResource[source]

Bases: DBBaseResource

CollectionModelResource Class

This model class implements the base class.

This class supports only gets to return collections of records.

Like the ModelResource class there is a provision for a process_get_input function.

The usual filtering is available for gathering records if a variable is a specific value. Most of the time, this will be all that is necessary.

However, there is a means to select records by a comparison operator.

Use a format as follows:

query_string: {

var1: [operator, comparison_value]

}

The list of operators for single comparison value is:

[“eq”, “ne”, “gt”, “ge”, “lt”, “le”]

In addition, if comparison is made such as selecting where var1 > var2, use {var1: [“gt”, var:var2]} to signal this is another variable.

To gather records that are found in a list use var1[]: [val1, val2, …].

Or, for more flexibility use:

query_string: {

var1: [operator, [val1, val2, …]]

}

The supported list of operators are

[“like”, “ilike”, “notlike”, “notilike”]

To control record set sizes, a variable page_config is a dict of page or record variables.

Bear in mind tha all variables entering can be either camel or snake based.

Page_config variables:

“orderBy”: [“id”, “statusId”],

Can be a single value or a list To sort in descending order use the format -var1

“pageSize”: “50”,

The maximum page size can be limited by the class variable max_page_size

“offset”: 30, The number of records to skip

“limit”: “100”,

limits the size of the record set

“serialFields”: [“id”, “statusId”],

can specify specific columns to be returned fallback: serial fields can be specified by resource or dbbase model

“debug”: “False”,

covered below

if debug is true, the recordset is not returned. Instead, data returned consists of variables used, the default variable amounts, and the sqlalchemy query that would be executed.

“class_defaults”: {

“model_name”: self.model_name, “process_get_input”: get_input_doc, “max_page_size”: self.max_page_size, “order_by”: None, “op_codes”: self.OP_CODES1 + self.OP_CODES2,

}, “original_data”: orig_data, “converted_data”: query_data, “page_configs”: configs, “query”: str(query)

process_get_input = None
max_page_size = None
order_by = None
OP_CODES1 = ['eq', 'ne', 'gt', 'ge', 'lt', 'le']
OP_CODES2 = ['like', 'ilike', 'notlike', 'notilike']
model_name = None

The string version of the Model class name. This is set upon initialization.

get()[source]
methods = {'GET'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

flask_restful_dbbase.resources.dbbase_resource module

” This module implements a starting point for model resources.

class flask_restful_dbbase.resources.dbbase_resource.DBBaseResource[source]

Bases: Resource

DBBaseResource Class

This model class implements the base class.

model_class: a dbbase.Model url_prefix: the portion of the path leading up to the resource, for example: /api/v2

url_name: the url_name defaults to a lower case version of the the model_class name if left as None, but can have an explicit name if necessary.

serial_fields: if left as None, it uses the serial list from the model class. Left as None, it will default to the underlying model.

serial_field_relations: can customize how relationship variables are presented in output.

before_commit/after_commit: These variables are designed to extend the capabilities of the methods be enabling a function or class to modify the data just prior to commit, or after. By using these, it is possible to send data to message queues, adjust the data, or otherwise change the data.

There are expectations of about the functions/classes.

Format for a before/after function:

def myfunc(resource_self, item, status_code):

Parameters:
  • resource_self – (obj) : This is the self of the resource. This provides access to the resource itself.

  • item – (obj) : This is the SQLAlchemy object.

  • status_code (int) – If due to the processing that status_code should change, you can change it here. Otherwise, simply return it.

Returns:

item – (obj) : The modified record status_code (int) : The possibly altered response status_code

Example of a Class:

A class can be used to hold additional data. This example shows how a resource can receive a POSTed object, but return the job created as a result instead.

A class requires that a run function be implemented with the input variables as shown below.

class JobCreator(object):
def __init__(self, class_name):

self.Job = class_name

def run(self, resource_self, item, status_code):

# obj_self gives access resource characteristics # but not used in this case data = item.to_dict(to_camel_case=False) job = self.Job() job = self.Job(

owner_id=data[‘owner_id’], model_id=data[‘id’], job_type_id=0, status_id=0

).save() if resource_self.serial_fields is None:

resource_self.serial_fields = {}

resource_self.serial_fields[‘post’] = self.Job.get_serial_fields()

# job submitted here ->

status_code = 202 return job, status_code

meta_doc: This set of attributes is designed to supplement meta information automatically generated. It uses the MetaDoc class found in utils.

model_class = None
url_prefix = '/'
url_name = None
use_date_conversions = False

use_date_conversions can be used if the database, such as SQlite3 does not support the acceptance of string-based dates. Since it takes processing time and adherence to a format, it is an optional feature.

serial_fields = None
serial_field_relations = None
before_commit = {}
after_commit = {}
default_sort = None
requires_parameter = False
fields = None
meta_doc = None
model_name = None

The string version of the Model class name. This is set upon initialization.

classmethod get_key_names(formatted=False)[source]

This function returns column names marked as primary_key.

Parameters:

formatted – (bool) : will return in form [<int:id>]

Returns:

key_names (list) – a list of keys is returned

classmethod get_obj_params()[source]

This is a convenience function for getting documentation parameters from the model class.

Returns:

(dict) – The object properties of the model class

static format_key(key, key_type)[source]

This function returns the portion of the URL that embodies the key.

Parameters:
  • key – (str) : The name of the key field.

  • key_type – (str) : Either ‘integer’ or something else.

Returns:

formatted key – (str) : such as <int:id>

classmethod get_urls()[source]
This function returns something similar to

[ {url_prefix}/{this_url}, {url_prefix}/{this_url}/<int:id> ]

classmethod get_meta(method=None)[source]

This function returns the settings for the resource.

Parameters:

method – (str : None) : choices are get/post/put/patch/delete.

Returns:

meta_data (dict) – A dict with the resource characteristics. If a method is preferred, the focus will be narrowed to that method.

The intent of this function is to show relevant information for someone interacting with an API.

classmethod is_collection()[source]

This function returns True if identified as a collection resource.

classmethod create_url()[source]

Url can come from: * url_name resource variable

but if None * snake_case version of class name

NOTE: figure out flag for use table/classname

screen_data(data, obj_params, skip_missing_data=False)[source]

Assumes data is deserialized

This function screens data from a few parameters, missing data, unneeded fields in data, excessive string lengths, improper numbers.

Note that this function does not exhaustively determine the problem. It ends on first failure.

Parameters:
  • data – (dict) : incoming data

  • obj_params – (dict) : table parameters

  • skip_missing_data – (bool) : Flag to check for all for record

Returns:

status – (bool) : True, Successful screening msg : (None : dict) : description of the problem

Each test for bad data outputs a status of True, None for each successful test. Unsuccessful tests add the problem to an error list to be returned at the end. That way, there is a relatively complete list of the problems encountered.

flask_restful_dbbase.resources.meta_resource module

This module implements resource with a purpose of documenting a model resource.

Assumes a get method.

class flask_restful_dbbase.resources.meta_resource.MetaResource[source]

Bases: Resource

This class enables documentation for a model resource.

Class variables:

resource_class: This is the model resource that you wish to documnent.

url_prefix: Like with the ModelResource class, this prefix can be used to create a url for the documentation.

url_name: This is the final part of a url for creating a url. It defaults to a name of ‘meta’.

Both the url_prefix and url_name come into play only upon initial configuration.

resource_class = None

This is the resource class to be documented

url_prefix = 'meta'

This is the default prefix to be used for the URL.

methods = {'GET'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

url_name = None

This name can be used to make the default URL for the meta resource.

get()[source]

This function is the request.GET method for the meta resource URL.

Parameters:
  • method – (str) : can specify only a specific method of the resource

  • documented (to be) –

  • put. (such as get or) –

  • filter – (str) : the details of the table

Returns:

meta – (json) : The documentation

classmethod get_urls()[source]

This function returns a default url for the resource. To keep consistency with the get_urls functions in other resources, it returns the url in a list, even though there would never be more than one.

The approach enables a code consistent approach when using the api.add_resource function.

Example:

api.add_resource(BookResource, *BookResource.get_urls()) api.add_resource(BookCollection, *BookCollection.get_urls()) api.add_resource(BookMetaResource, *BookMetaResource.get_urls()) api.add_resource(BookMetaCollection, *BookMetaCollection.get_urls())

Default URLS: /books /books/<int:id> /meta/books/single /meta/books/collection

Bear in mind that the get_urls function is only for convenience when adding the resource the api.

flask_restful_dbbase.resources.model_resource module

” This module implements a starting point for model resources.

class flask_restful_dbbase.resources.model_resource.ModelResource[source]

Bases: DBBaseResource

ModelResource Class

This model class implements the base class.

Class variables:

model_class: a dbbase.Model

url_prefix: the portion of the path leading up to the resource

For example: /api/v2

url_name: the url_name defaults to a lower case version of the

the model_class name if left as None, but can have an explicit name if necessary.

serial_fields: if left as None, it uses the serial list from

the model class. However, it can be a list of field names or

before_commit: A dict with method keys for placing a function

to run just before committing an item to the database. It can also divert the method to end the HTTP method early and return something entirely different than the item being applied.

after_commit: A dict with method keys for placing a function

to run just afteer committing an item to the database. It can also divert the method to end the HTTP method early and return something entirely different than the item being applied.

process_get_input = None
process_post_input = None
process_put_input = None
process_patch_input = None
process_delete_input = None
get(**kwargs)[source]

This function is the HTTP GET method for a resource handling a single item.

post()[source]

This function is the HTTP POST method for a resource handling a single item.

put(**kwargs)[source]

This function is the HTTP PUT method for a resource handling a single item.

patch(**kwargs)[source]

This function is the HTTP PATCH method for a resource handling a single item.

delete(**kwargs)[source]

This function is the HTTP DELETE method for a resource handling a single item.

methods = {'DELETE', 'GET', 'PATCH', 'POST', 'PUT'}

The methods this view is registered for. Uses the same default (["GET", "HEAD", "OPTIONS"]) as route and add_url_rule by default.

Module contents