问题描述
我正在尝试使用 flask_restful 构建 API,但我不知道如何将继承自 Resource 的类与实际应用程序连接起来.我有以下结构
I'm trying to build an API with flask_restful, but I don't know how to connect classes that inherit from Resource, with the actual app.I have the following structure
page
├───api
│ └───__init__.py
│ └───resources.py
└───__init__.py
page/api/resources.py:
page/api/resources.py:
from flask_restful import Resource
from page import api
@api.resource("/hello-world")
class HelloWorld(Resource):
def get(self):
return {"hello": "World"}
page/init.py:
from flask import Flask
from flask_restful import Api
from page.config import Config1
api = Api()
def create_app(config_class=Config1):
app = Flask(__name__)
app.config.from_object(config_class)
api.init_app(app)
return app
run.py(页面包外):
run.py (outside of the page package):
from page import create_app
if __name__ == "__main__":
app = create_app()
app.run(debug=True)
测试:
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.get(BASE + "hello-world")
print(response.json())
显然,向/hello-world"发出请求不起作用.我怎样才能让 Flask 意识到"?资源,以便我得到有效的响应.
Obviously, making a request to "/hello-world" doesn't work. How can I "make Flask aware" of the resources, so that I get a valid response.
推荐答案
可能有一个非常聪明的方法来做到这一点,但对我来说,解决方案是删除装饰器 @api.resource
page/api/resources.py
中的装饰器,并在 page/init.py
Probably there is a much clever way of doing this but for me, the solution would be to remove the decorator @api.resource
decorator at page/api/resources.py
and make the following changes at page/init.py
from flask import Flask
from page.config import Config1
def create_app(config_class=Config1):
app = Flask(__name__)
app.config.from_object(config_class)
return app
我还将根据 Flask 文档将 run.py
移动到 page
文件夹中,并将其重命名为 app.py
.这个 app.py
应该有你的路线,所以把它改成这样的:
I would also move the run.py
inside the page
folder and rename it to app.py
according to Flask documentation. This app.py
should have your routes so change it to something like this:
from page import create_app
from page.api.resources import HelloWorld
from flask_restfull import api
app = create_app()
api = Api(app)
api.add_resource(HelloWorld, '/hello-world')
要运行它,只需在 page
文件夹中键入 flask run
.
And to run it just type flask run
inside the page
folder.
这篇关于Flask 应用无法识别flask_restful 资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!