Flask结构 - 无法从__init__.py中导入应用程序 [英] Flask structure -- can't import application from __init__.py

查看:195
本文介绍了Flask结构 - 无法从__init__.py中导入应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名Python初学者,使用 __ init __。py 设置我的应用程序结构时遇到了很多麻烦,甚至在查找了几个教程之后。

目前,我目前的目录结构如下所示:

  / parent 
/ myapp
__init__.py
views.py
/ virtualenv

以前,我有(如果有任何区别的话)

pre $ $ $ $ $ $ $ $ / myapp
/ bin
/ include
/ lib

__ init __。py 的内容如下:

  from flask import Flask 
app = Flask(__ name__)

和我的views.py

  from myapp导入应用程序
@ app.route('/')
def test():
return'This是一个新的测试'

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

如果myapp正在用init文件初始化,为什么我不能把它叫做视图?我得到一个错误,说明我不能导入应用程序,我没有名为myapp的模块。如果我删除init文件并将其内容复制到views.py文件的顶部,一切正常。

解决方案

您正在使用 views 作为主脚本。你不能把一个脚本放在一个包里;它所在的目录不能被视为这样。 Python将父/ myapp 目录添加到Python路径,而不是路径。 b

在顶层( myapp )旁边添加单独的脚本:

  from myapp import app 
$ b if if __name__ =='__main__':
app.run(debug = True)

并将导入添加到 __ init __。py 你的看法:

pre $ from flask import Flask
app = Flask(__ name__)

import views

并且移除 if __name__ =='__main __': block from views.py


I'm a beginner with python and I've been having a lot of trouble setting up the structure of my applications using __init__.py even after searching through several tutorials.

At the moment, my current directory structure looks like the following

/parent
   /myapp
       __init__.py
       views.py
   /virtualenv

Previously, I had (if it makes any difference)

/parent
   /myapp
   /bin
   /include
   /lib

The contents of __init__.py are below:

 from flask import Flask
 app = Flask(__name__)

and my views.py

 from myapp import app
 @app.route('/')
 def test():
    return 'This is a new test'

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

If myapp is being initialized with the init file, why cannot I not call it into the views? I get an error stating I cannot import app and I have no module named myapp. If I remove the init file and copy the contents into the top of the views.py file, everything works fine.

解决方案

You are using views as the main script. You cannot put a script inside a package; the directory it is in cannot be treated as such. Python adds the parent/myapp directory to the Python path, not the parent path.

Add a separate script at the top level (next to myapp):

from myapp import app

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

and add an import to __init__.py to import your views:

from flask import Flask
app = Flask(__name__)

import views

and remove the if __name__ == '__main__': block from views.py.

这篇关于Flask结构 - 无法从__init__.py中导入应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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