为什么从.导入视图可以解决Flask中的圆导入? [英] Why `from . import views` can solve circle import in Flask?

查看:43
本文介绍了为什么从.导入视图可以解决Flask中的圆导入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从较大的应用程序中学习.在本文档中,它说:所有视图函数(顶部带有route()装饰器的视图函数)都必须导入 init .py文件中.不是对象本身,而是其中的模块."
我不知道为什么这样做: from.导入视图,成功.尽管从视图导入* 也可以很好地工作.
我这样组织这些文件:

I learn from Larger Applications.In this document, It says: "all the view functions (the ones with a route() decorator on top) have to be imported in the init.py file. Not the object itself, but the module it is in."
I don't know why should when I do this: from . import views,It succeed.Though from views import * can also work well.
I organize these file like this:

myapplication/
  runner.py
  myflask/
    __init__.py
    views.py
    templates/
    static/
    ...

runner.py:

runner.py:

from testFlask import app
app.run()

myflask/__ init __.py:

myflask/__init__.py:

from flask import Flask
app = Flask(__name__)
from . import views # why this can work????

myflask/views.py:

myflask/views.py:

from . import app
@app.route('/')
def index():
    return 'Hello World!'

我运行它:

$ cd myapplication
$ python runner.py

可以运行此Flask应用.但是我想知道为什么 from.导入视图可以解决烧瓶中的此圆导入问题吗?以及为什么文档说:不是对象本身,而是对象所在的模块 ??

It's OK to run this Flask app. However I want to know why from . import views can solve this circle import problem in flask? And why the doc says: Not the object itself, but the module it is in????

但是,当我这样做时:

#some_dir/
#  application.py
#  views.py

#application.py
from flask import Flask
app = Flask(__name__)
import views # it doesn't work
# from views import * # it works
app.run()

#views.py
from application import app
@app.route('/')
def index():
    return 'Hello World!'

#run it
$ python application.py

它不起作用.

推荐答案

这是循环导入.但是在您的情况下,可能有问题的变量(app)已经在导入的脚本中定义,因此导入只会导致第一个"app"实例被导入的"app"实例覆盖.没有实际效果.

It is a circular import. But in your case, the variable that might have been problematic (app) has already been defined in the imported script, so the import just causes the first "app" instance to be overwritten by the imported "app" instance. Which has no practical effect.

有关此循环导入情况的详细信息,请阅读此帖子.

For details about this circular import situation, please read this post.

如果要遵循大型烧瓶应用程序的模式,则应查看蓝图应用程序工厂.

If you want to follow the pattern for a large flask application, you should look into blueprints and application factories.

这篇关于为什么从.导入视图可以解决Flask中的圆导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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