调用烧瓶安静的API资源方法 [英] Calling flask restful API resource methods
问题描述
pre $ c $类FooAPI(资源)
def __init __( self):
#做一些事情
super(FooAPI,self).__ init __()
def post(self,id):
#return something
def get (self):
#return something
api = Api(app)
api.add_resource(FooAPI,'/ api / foo',endpoint ='foo')
然后在我想要的控制器中:
<$ p $
def bar():
#获取FooAPI中post()的返回值
如何从FooAPI获取post()的返回值?我可以通过api变量以某种方式做到这一点吗?或者我必须在控制器中创建FooAPI的实例?这似乎是必须有一个简单的方法来做到这一点,我只是不理解...
显而易见应用程序使用API的方式是像调用其他客户端一样调用它。应用程序同时作为服务器和客户端的事实并不重要,客户端部分可以将请求放入 localhost
中,服务器部分将获得它们以同样的方式获得外部请求。要生成HTTP请求,您可以使用标准库中的请求或urllib2。
但是,虽然上面的方法将工作得很好,似乎矫枉过正给我。在我看来,更好的方法是以常规应用程序和API可以调用的方式公开应用程序的通用功能。例如,你可以有一个名为 FooLib
的包来实现所有的共享逻辑,然后 FooAPI
成为一个简单的包装器 FooLib
和 FooAPI
和 FooApp
调用 FooLib
来完成任务。
I'm creating an API with Flask that is being used for a mobile platform, but I also want the application itself to digest the API in order to render web content. I'm wondering what the best way is to access API resource methods inside of Flask? For instance if I have the following class added as a resource:
class FooAPI(Resource):
def __init__(self):
# Do some things
super(FooAPI, self).__init__()
def post(self, id):
#return something
def get(self):
#return something
api = Api(app)
api.add_resource(FooAPI, '/api/foo', endpoint = 'foo')
Then in a controller I want:
@app.route("/bar")
def bar():
#Get return value from post() in FooAPI
How do I get the return value of post() from FooAPI? Can I do it somehow through the api variable? Or do I have to create an instance of FooAPI in the controller? It seems like there has to be an easy way to do this that I'm just not understanding...
The obvious way for your application to consume the API is to invoke it like any other client. The fact that the application would be acting as a server and a client at the same time does not matter, the client portion can place requests into localhost
and the server part will get them in the same way it gets external requests. To generate HTTP requests you can use requests, or urllib2 from the standard library.
But while the above method will work just fine it seems overkill to me. In my opinion a better approach is to expose the common functionality of your application in a way that both the regular application and the API can invoke. For example, you could have a package called FooLib
that implements all the shared logic, then FooAPI
becomes a thin wrapper around FooLib
, and both FooAPI
and FooApp
call FooLib
to get things done.
这篇关于调用烧瓶安静的API资源方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!