Created
November 14, 2016 21:00
-
-
Save whalesalad/b30b890634b1c2581fb6c6deb26b31e1 to your computer and use it in GitHub Desktop.
Some of my favorite little utility methods useful with Flask api development.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| import datetime | |
| from functools import wraps | |
| from flask import request, jsonify | |
| class ISO8601Encoder(json.JSONEncoder): | |
| def default(self, obj): | |
| if isinstance(obj, datetime.datetime): | |
| return obj.date().isoformat() | |
| if isinstance(obj, datetime.date): | |
| return obj.isoformat() | |
| return super(ISO8601Encoder, self).default(obj) | |
| def jsonify_exception(e): | |
| return jsonify({ | |
| 'error': e.__class__.__name__, | |
| 'message': e.message or e.__class__.__doc__ | |
| }) | |
| def parameters_from_request(): | |
| return request.json if request.method == 'POST' else request.args | |
| def require_params(*required_parameters): | |
| def outer(func): | |
| @wraps(func) | |
| def decorated(*args, **kwargs): | |
| parameters = set(parameters_from_request().keys()) | |
| missing = set(required_parameters) - parameters | |
| if missing: | |
| return jsonify({ 'error': 'missing-keys', 'message': 'Missing required parameters: %s' % ', '.join(missing) }), 400 | |
| return func(*args, **kwargs) | |
| return decorated | |
| return outer | |
| def validate_contract(contract, data): | |
| """ | |
| Given a contract of key:fn pairs, run the data through each transformation | |
| """ | |
| response = {} | |
| for key,value in data.items(): | |
| response[key] = contract.get(key, lambda x: x)(value) | |
| return response | |
| def transform_params(**contract): | |
| """ | |
| Abstract the GET (query params) or POST (json body) + parsing parameters so that | |
| the underlying view can simply deal with `params` being the pure/pythonified request input | |
| """ | |
| def outer(func): | |
| @wraps(func) | |
| def decorated(*args, **kwargs): | |
| kwargs['params'] = validate_contract(contract, parameters_from_request()) | |
| return func(*args, **kwargs) | |
| return decorated | |
| return outer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment