我对 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 运行应用程序时会出现问题。
它只是调用 __init__.py
而不是 server.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
时工作?
答案 0 :(得分:0)
当您使用 __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 *
端点
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 提供了所谓的 Blue prints。这不是您现在需要担心的,但在尝试将应用拆分为子应用时特别方便。