Flask Restful添加资源参数 [英] Flask Restful add resource parameters
问题描述
我希望将对象实例作为参数传递给 Flask-RESTfull 资源.
I am looking to pass an object instance as a parameter into a Flask-RESTfull Resource.
这是我的设置:
# in main.py
from flask import Flask
from flask.ext.restful import Api
from bar import Bar
from foo import views
app = Flask(__name__)
api = Api(app)
my_bar = Bar()
api.add_resource(views.ApiPage, "/api/my/end/point/")
然后在views.py中,我的资源设置如下:
Then in views.py I have the resource set up as follows:
# In views.py
from flask.ext.restful import Resource
class ApiPage(Resource):
def get(self):
serialized = str(my_bar)
return serialized
所以我遇到的问题是我需要将Bar()
的实例传递到api资源中.有没有办法像api.add_resource(views.ApiPage, "/api/my/end/point/", instance=bar)
那样通过add_resource
方法传递它?
So the issue that I am having is that I need to pass my instance of Bar()
into the api resource. Is there any way to pass it in through the add_resource
method like api.add_resource(views.ApiPage, "/api/my/end/point/", instance=bar)
?
推荐答案
自版本0.3.3(2015年5月22日发布)以来,add_resource()
可以将参数传递给您的Resource
构造函数.
Since version 0.3.3 (released May 22, 2015), add_resource()
is able to pass parameters to your Resource
constructor.
在原始示例之后,这是views.py
:
Following the original example, here is the views.py
:
from flask.ext.restful import Resource
class ApiPage(Resource):
def __init__(self, bar):
self.bar = bar
def get(self):
serialized = str(my_bar)
return serialized
以及main.py
的相关代码:
# ...
my_bar = Bar()
api.add_resource(views.ApiPage, '/api/my/end/point/',
resource_class_kwargs={'bar': my_bar})
这篇关于Flask Restful添加资源参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!