烧瓶未在导入的模块中找到路线 [英] Flask not finding routes in imported modules
问题描述
我遇到了Flask的问题,其中导入的模块中声明的路由未注册,并且始终生成404.我正在Python 2.7上运行最新版本的Flask.
我具有以下目录结构: run.py具有以下代码: 从烧瓶进口烧瓶
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
import views.home
if __name__ == '__main__':
app.run()
home.py具有以下代码:
from run import app
@app.route('/test')
def test():
return "test"
当我运行run.py
时,在home.py
中声明的路由( http://localhost:5000/test )始终返回404,即使run.py
导入views.home
.在run.py
中声明的根视图( http://localhost:5000 )可以正常工作.
我编写了一个函数,该函数可以打印出所有已注册的路由,并且/test不在其中(解决方案
我发现从
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
import views.home
if __name__ == '__main__':
app.run()
切换了run.py
中的import语句
import views.home
到
from views.home import *
使一切正常工作,这为我提供了为什么不使用import views.home
注册模块的线索.
基本上,当 When I run I have written a function that prints out all the registered routes and /test is not in there (get a list of all routes defined in the app). Any idea why? I have discovered that switching the import statement in to makes everything work, which gave me the clue as to why the modules are not being registered using Basically, when Then when I import app from The solution was to move the creation of the So and
这篇关于烧瓶未在导入的模块中找到路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!run.py
作为脚本运行时,其名称为__main__
,这是sys.modules
中为模块指定的名称(run.py
the route declared in home.py
(http://localhost:5000/test) always returns a 404 even though run.py
imports views.home
. The root view (http://localhost:5000) declared in run.py
works fine.run.py
fromimport views.home
from views.home import *
import views.home
.run.py
is run as a script it is given the name __main__
and this is the name given to the module in sys.modules
(Importing modules: __main__ vs import as module)run.py
in views.home.py
a new instance of run.py
is registered in sys.modules
with the name run
. As this point, the reference to app
in run.py
and views.home.py
are two different references hence the routes not being registered.app
variable out of run.py
and in to a separate python file (I called it web_app.py
) that is imported into run.py
. This guarantees that the Flask app
variable declared inside web_app.py
is the always referenced correctly wherever web_app.py
is imported.run.py
now looks like this:from web_app import app
if __name__ == '__main__':
app.run()
web_app.py
looks like this:from flask import Flask
app = Flask(__name__)
import view.home