【发布时间】:2021-04-27 09:31:16
【问题描述】:
我对 python 比较陌生,正在尝试构建一个烧瓶服务器。我想做的是有一个名为“endpoints”的包,它有一个模块列表,其中每个模块定义应用程序路由的子集。当我使用以下代码创建一个名为 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 时工作?
【问题讨论】:
标签: python flask import package modulenotfounderror