简体   繁体   English

烧瓶RESTful得到404错误?

[英]python - Flask-RESTful get 404 error?

I followed the official docs of flask-RESTful and I'm trying to implement the first hello world demo. 我遵循了flask-RESTful官方文档 ,并且试图实现第一个hello world演示。

At first, I put all the example code in a single file and every thing works fine. 首先,我将所有示例代码放在一个文件中,并且一切正常。

However, when I split the code in three separated files (trying to make the project more structured), I always got a 404 error . 但是,当我将代码分成三个单独的文件时(试图使项目更结构化),我总是遇到404错误

file stucture 文件结构

.
├── app.py
├── app
    ├── __init__.py
    ├── __api__.py
└── venv

__init__.py __init__.py

# -*- coding: utf-8 -*-
#initialization
from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

api.py api.py

# -*- coding: utf-8 -*-
from app import app, api
from flask_restful import Resource, Api

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

app.py app.py

# -*- coding: utf-8 -*-
from app import app

if __name__ == '__main__':
    app.run(debug=True)

In python console: 在python控制台中:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 250-643-552
127.0.0.1 - - [03/May/2016 22:35:20] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [03/May/2016 22:35:24] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [03/May/2016 22:38:15] "GET / HTTP/1.1" 404 -

What's wrong? 怎么了?


EDIT 编辑

I can now get the expected result by move api.add_resource(HelloWorld, '/') to app.py 现在我可以通过移动预期的结果api.add_resource(HelloWorld, '/')app.py

app.py (edited) app.py(已编辑)

# -*- coding: utf-8 -*-
from app import app, api
from app.api import HelloWorld

api.add_resource(HelloWorld, '/')


if __name__ == '__main__':
    app.run(debug=True)

Can't figure out why? 不知道为什么吗?

The reason why your previous version doesn't work is that module api.py is never loaded and thus below code (for mapping the URI to the given resource) does NOT get executed: 您以前的版本不起作用的原因是模块api.py从未加载,因此以下代码(用于将URI映射到给定资源)不会被执行:

api.add_resource(HelloWorld, '/')

Actually in your edited/latest version, you don't have to rewrite that line of code in app.py. 实际上,在您的编辑/最新版本中,您不必重写app.py中的该行代码。 Instead you just need to import something from api.py. 相反,您只需要从api.py导入某些内容即可。

Just a side note, normally it is more often that decorator api.resource is used to declare the mapping. 只是一点说明,通常使用装饰器api.resource来声明映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM