在我的烧瓶应用程序中,我在每次启动时重新创建一个sqlite数据库。
为此,我使用的代码在official webpage获取相对于执行烧瓶的路径应用程序
我的项目结构看起来像这样
project_dir/
|-README.md
`-app/
|-StubbyServer.py (contains the flask root)
|-schema.sql
`- (all the other files)
现在如我StubbyServer.py
包含:
def get_db():
db = getattr(Flask, '_database', None)
if db is None:
db = Flask._database = sqlite3.connect(DATABASE)
with open('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
db.row_factory = sqlite3.Row
return db
如果我的工作目录是/path/project_dir/app
命令python StubbyServer.py
正常工作
如果我的工作目录是/path/project_dir
命令python app/StubbyServer.py
失败:
File "app/StubbyServer.py", line 43, in get_db
with open('schema.sql', mode='r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'schema.sql'
我知道为什么会这样,但我不知道我怎么能解决这个问题。 我希望我的烧瓶应用能够独立于我目前的工作目录工作,我该如何实现这一目标?
通过做正确的事 - 有你的应用需要一个配置参数与在你把你的临时文件的可写目录(或者在操作系统提供的临时目录中写入)。 – pvg
@pvg我不确定你的确切含义以及应该如何帮助。它不是关于写文件,而是关于读取特定文件? – Altoyyr
也许我误解了这一点。你不是在说每次运行创建一个新的sqldb吗? – pvg