| 2370 | |
| 2371 | |
| 2372 | class JSONPlugin(object): |
| 2373 | name = 'json' |
| 2374 | api = 2 |
| 2375 | |
| 2376 | def __init__(self, json_dumps=json_dumps): |
| 2377 | self.json_dumps = json_dumps |
| 2378 | |
| 2379 | def setup(self, app): |
| 2380 | app.config._define('json.enable', default=True, validate=bool, |
| 2381 | help="Enable or disable automatic dict->json filter.") |
| 2382 | app.config._define('json.ascii', default=False, validate=bool, |
| 2383 | help="Use only 7-bit ASCII characters in output.") |
| 2384 | app.config._define('json.indent', default=True, validate=bool, |
| 2385 | help="Add whitespace to make json more readable.") |
| 2386 | app.config._define('json.dump_func', default=None, |
| 2387 | help="If defined, use this function to transform" |
| 2388 | " dict into json. The other options no longer" |
| 2389 | " apply.") |
| 2390 | |
| 2391 | def apply(self, callback, route): |
| 2392 | dumps = self.json_dumps |
| 2393 | if not self.json_dumps: return callback |
| 2394 | |
| 2395 | @functools.wraps(callback) |
| 2396 | def wrapper(*a, **ka): |
| 2397 | try: |
| 2398 | rv = callback(*a, **ka) |
| 2399 | except HTTPResponse as resp: |
| 2400 | rv = resp |
| 2401 | |
| 2402 | if isinstance(rv, dict): |
| 2403 | #Attempt to serialize, raises exception on failure |
| 2404 | json_response = dumps(rv) |
| 2405 | #Set content type only if serialization successful |
| 2406 | response.content_type = 'application/json' |
| 2407 | return json_response |
| 2408 | elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict): |
| 2409 | rv.body = dumps(rv.body) |
| 2410 | rv.content_type = 'application/json' |
| 2411 | return rv |
| 2412 | |
| 2413 | return wrapper |
| 2414 | |
| 2415 | |
| 2416 | class TemplatePlugin(object): |
no outgoing calls
no test coverage detected
searching dependent graphs…