pyfarm.master.utility module¶
Utility¶
General utility which are not view or tool specific
-
class
pyfarm.master.utility.JSONEncoder(skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]¶ Bases:
json.encoder.JSONEncoder
-
pyfarm.master.utility.assert_mimetypes(flask_request, mimetypes)[source]¶ Warning
This function will produce an unhandled error if you use it outside of a request.
Check to make sure that the request’s mimetype is in
mimetypes. If this is not true then callflask.abort()withUNSUPPORTED_MEDIA_TYPEParameters: - flask_request – The flask request object which we should check the
mimetypeattribute on. - mimetypes (list, tuple, set) – The mimetypes which
flask_requestcan be.
- flask_request – The flask request object which we should check the
-
pyfarm.master.utility.dumps(obj, **kwargs)[source]¶ Wrapper for
json.dumps()that ensuresJSONEncoderis passed in.
-
pyfarm.master.utility.error_handler(e, code=None, default=None, title=None, template=None)[source]¶ Constructor for http errors that respects the current mimetype. By default this function returns html however when
request.mimetypeisapplication/jsonit will return a json response. This function is typically used within afunctools.partial()call:>>> from functools import partial >>> try: ... from httplib import BAD_REQUEST ... except ImportError: ... from http.client import BAD_REQUEST ... >>> from flask import request >>> error_400 = partial( ... error_handler, BAD_REQUEST, ... lambda: "bad request to %s" % request.url, "Bad Request")
Parameters: - e (flask.Response) – The response object which will be passed into
error_handler(), this value is ignored by default. - code (int) – The integer to use in the response. For the most consistent
results you can use the
httpliborhttp.clientmodules depending on your Python version. - default (callable) – This will be the default error message if g.error does not
contain anything.
defaultmay either be a callable function which will produce the string or it may be a string by itself. - title (str) – The HTML title of the request being made. This is not used when dealing with json requests and if not provided at all will default to using the official status code’s string representation.
- template (str) – A alternative template path for HTML responses
- e (flask.Response) – The response object which will be passed into
-
pyfarm.master.utility.get_g(attribute, instance_types, unset=<object object>)[source]¶ Returns data from
flask.gafter checking to make sure the attribute was set and that it has the correct type.This function does not check to see if you’re already inside a request.
Parameters:
-
pyfarm.master.utility.get_request_argument(argument, default=None, required=False, types=None)[source]¶ This is a function similar to Flask’s
request.args.getexcept it does type validation and it has the concept of required url arguments.Parameters: - argument (str) – The name of the url argument we’re trying to retrieve
- default – The value to return if
argumentis not present in the url and argument is not a required parameter. - required (bool) – If True and the url argument provided by
argumentis not provided respond to the request withBAD_REQUEST - types –
A single or list of multiple callable objects which will be used to try and produce a result to return. This would function similarly to this:
value = "5" types = (int, bool) for type_callable in types: try: return type_callable(value) except Exception: continue
-
pyfarm.master.utility.inside_request()[source]¶ Returns True if we’re inside a request, False if not.
-
pyfarm.master.utility.isuuid(value)[source]¶ Returns True if
valueis aUUIDobject or can be converted to one
-
pyfarm.master.utility.jsonify(*args, **kwargs)[source]¶ Drop in replacement for
flask.jsonify()that also handles list objects as well as a few custom objects like Decimal or datetime. Flask does not support lists by default because it’s considered a security risk in most cases but we do need it in certain cases. Since flask’s jsonify does not allow passing arbitrary arguments tojson.dumps(), we cannot use it if the output data contains custom types.
-
pyfarm.master.utility.timedelta_format(value)[source]¶ Formats a timedelta object without the microseconds
-
pyfarm.master.utility.validate_json(validator, json_types=(<class 'dict'>, ))[source]¶ A decorator, similar to
validate_with_model(), but greatly simplified and more flexible. Unlikevalidate_with_model()this decorator is meant to handle data which may not be structured for a model.Parameters:
-
pyfarm.master.utility.validate_with_model(model, type_checks=None, ignore=None, ignore_missing=None, disallow=None)[source]¶ Decorator which will check the contents of the of the json request against a model for:
- missing fields which are required
- values which don’t match their type(s) in the database
- inclusion of fields which do not exist
Parameters: - model – The model object that the decorated endpoint should use for testing the points above.
- type_checks (dict) – A dictionary containing a mapping of column names to special functions used for checking. If there’s a key in the incoming request that needs a more detailed check than “isinstance(g.json[column_name], <Python type(s) from sql>)” then this is the place to add it.
- ignore_missing (list) – A list of fields to completely ignore in the incoming
request. Typically this is used by
PUTrequests or other similar requests where part of the data is in the url. - allow_missing (list) – A list of fields which are allowed to be missing in the request. These fields will still be checked for type however.
- disallow (list) – A list of columns which are never in the request to the decorated function