pyfarm.master.utility module


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]


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 call flask.abort() with UNSUPPORTED_MEDIA_TYPE

  • flask_request – The flask request object which we should check the mimetype attribute on.
  • mimetypes (list, tuple, set) – The mimetypes which flask_request can be.
pyfarm.master.utility.dumps(obj, **kwargs)[source]

Wrapper for json.dumps() that ensures JSONEncoder is 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.mimetype is application/json it will return a json response. This function is typically used within a functools.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")
  • 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 httplib or http.client modules depending on your Python version.
  • default (callable) – This will be the default error message if g.error does not contain anything. default may 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
pyfarm.master.utility.get_g(attribute, instance_types, unset=<object object>)[source]

Returns data from flask.g after 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.

  • attribute (str) – The name of the attribute on the flask.g object
  • instance_types (tuple) – A tuple of classes which the data we’re looking for should be a part of
pyfarm.master.utility.get_request_argument(argument, default=None, required=False, types=None)[source]

This is a function similar to Flask’s request.args.get except it does type validation and it has the concept of required url arguments.

  • argument (str) – The name of the url argument we’re trying to retrieve
  • default – The value to return if argument is not present in the url and argument is not a required parameter.
  • required (bool) – If True and the url argument provided by argument is not provided respond to the request with BAD_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:
            return type_callable(value)
        except Exception:

Returns True if we’re inside a request, False if not.


Returns True if value is a UUID object 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 to json.dumps(), we cannot use it if the output data contains custom types.


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. Unlike validate_with_model() this decorator is meant to handle data which may not be structured for a model.

  • mimetype (tuple) – A tuple of mimetypes that are allowed to be handled by the decorated function.
  • json_types (tuple) – The root type or types which the object on g.json should be an instance of.
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
  • 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 PUT requests 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