烧瓶未在导入的模块中找到路线 [英] Flask not finding routes in imported modules

查看:72
本文介绍了烧瓶未在导入的模块中找到路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了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注册模块的线索.

基本上,当run.py作为脚本运行时,其名称为__main__,这是sys.modules中为模块指定的名称(

When I run 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.

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 run.py from

import views.home

to

from views.home import *

makes everything work, which gave me the clue as to why the modules are not being registered using import views.home.

Basically, when 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)

Then when I import app from 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.

The solution was to move the creation of the 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.

So run.py now looks like this:

from web_app import app

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

and web_app.py looks like this:

from flask import Flask

app = Flask(__name__)

import view.home

这篇关于烧瓶未在导入的模块中找到路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆