Flask 应用无法识别flask

编程入门 行业动态 更新时间:2024-10-27 08:28:34
本文介绍了Flask 应用无法识别flask_restful 资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 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.resourcepage/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 资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 04:47:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/930574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法识别   Flask   flask

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!