[英]How can I return a common JSON object in my flask API?
I'm building an API that returns JSON strings. 我正在构建一个返回JSON字符串的API。 My goal, however, is to have a common wrapper around results that contain various meta data attributes about the returned results, plus the return results.
但是,我的目标是为结果提供一个通用包装,其中包含有关返回结果以及返回结果的各种元数据属性。
My JSON object would look something like this: 我的JSON对象如下所示:
{
'total_results': 1001,
'throttle': 0,
'error_cd': 0,
'message': 'Successful',
'results': [
# Data that is returned; Each end point can return a different "type"
]
}
The goal is to have my end points simply return the data that appears in results
(not even in JSON format). 目的是让我的端点简单地返回
results
中显示的数据(甚至不是JSON格式)。 My question is how can I provide a wrapper around this? 我的问题是我该如何提供包装器?
My initial idea was a decorator of some kind that runs jsonify
, but can a decorator run AFTER a function? 我最初的想法是运行
jsonify
某种装饰器,但是装饰器可以在函数之后运行吗? IE. IE浏览器 Can I run the code in my route and THEN run decorator code?
我可以在路线中运行代码,然后运行装饰器代码吗?
What about just writing a wrapper function? 只编写包装函数呢? I would probably do something like:
我可能会做类似的事情:
@app.route('/api/blah/')
def my_route():
results = calculate_my_results()
return jsonify(format_api_result(results))
def format_api_result(data):
# add in your extra metadata here, return a dictionary
A function seems to me to be the most straightforward and most flexible way to do what you want. 在我看来,功能似乎是最简单,最灵活的操作方式。 It's a little extra code, but so's a decorator.
这是一些额外的代码,但是是一个装饰器。 And while you can certainly do this in a decorator, I don't think it adds much here except complexity.
尽管您当然可以在装饰器中完成此操作,但是我认为除了复杂性之外,它在这里没有增加太多其他功能。
If you do want to go the decorator route, check out this: 如果您确实想使用装饰器路线,请查看以下内容:
http://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/ http://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/
for a good explanation of how decorators work and how you control exactly when the wrapped function gets called. 很好地解释了装饰器如何工作以及如何在调用包装函数时精确控制。
Let me know if I misunderstood what you're trying to do. 如果我误解了您要做什么,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.