我是相对较新的python和我试图建立一个flask服务器。我想做的是有一个叫做端点的包它有一个模块列表,其中每个模块定义了应用程序路由的子集。当我用下面的代码创建一个名为server.py的文件时,它的工作原理如下
import os
from flask import Flask
app = Flask(__name__)
from endpoint import *
if __name__ == '__main__':
app.run(debug=True, use_reloader=True)
现在只有一个端点模块叫做hello。py它是这样的
from __main__ import app
# a simple page that says hello
# @app.route defines the url off of the BASE url e.g. www.appname.com/api +
# @app.route
# in dev this will be literally http://localhost:5000/hello
@app.route('/hello')
def hello():
return 'Hello, World!'
所以…当我运行python server.py时,上面的工作正常,当我尝试使用flask运行应用程序时,问题发生了。
它调用的不是server。py而是__init__.py
,看起来像这样
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from endpoint import *
当我在终端运行flask run
时,我得到ModuleNotFoundError: No module named 'endpoint'
但是如果我再次更改代码,使其看起来像下面这样,那么flask run
工作。
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
# @app.route defines the url off of the BASE url e.g. www.appname.com/api +
# @app.route
# in dev this will be literally http://localhost:5000/hello
@app.route('/hello')
def hello():
return 'Hello, World!'
我很确定这是发生的,因为我不完全理解导入是如何工作的…
那么,我如何设置__init__.py
,使其从"端点"导入所有模块?当我调用flask run
?
当您使用__init__.py
文件时(您应该这样做),Python将该目录视为包。
这意味着你必须从包中导入,而不是直接从模块中导入。
同样,通常你不会在__init__.py
文件中放入太多或任何代码。
您的目录结构可能像这样,其中stack
是我使用的包的名称。
stack/
├── endpoint.py
├── __init__.py
└── main.py
您的__init__.py
文件为空。
main.py
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from stack.endpoint import *
<<p>端点/strong>from stack.main import app
# a simple page that says hello
# @app.route defines the url off of the BASE url e.g. www.appname.com/api +
# @app.route
# in dev this will be literally http://localhost:5000/hello
@app.route('/hello')
def hello():
return 'Hello, World!'
你可以运行你的应用程序…
export FLASK_APP=main.py
# followed by a...
flask run
这就是说,当我创建一个新的Flask应用程序时,我通常只使用一个文件,这使得初始开发更容易,只有当应用程序真正变大时才分成模块。
另外,为了分离视图,或者让我们称之为子包,Flask提供了所谓的蓝图。这不是你现在需要担心的,但是当你试图将应用分割成子应用时,它会特别方便。