Get path relative to executed flask app(获取相对于执行的烧瓶应用程序的路径)
问题描述
在我的 Flask 应用程序中,我每次启动时都会重新创建一个 sqlite 数据库.
为此,我使用 官方网页
In my flask app I recreate a sqlite database at every start.
For this I use code as shown on the 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
工作正常
If my working directory is /path/project_dir/app
the command python StubbyServer.py
works fine
如果我的工作目录是 /path/project_dir
命令 python app/StubbyServer.py
失败:
If my working directory is /path/project_dir
the command python app/StubbyServer.py
fails with:
文件app/StubbyServer.py",第 43 行,在 get_db
with open('schema.sql', mode='r') as f:
FileNotFoundError: [Errno 2] 没有这样的文件或目录:'schema.sql'
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'
我知道为什么会发生这种情况,但我不知道如何解决这个问题.我希望我的 Flask 应用程序能够独立于我当前的工作目录而正常工作,我该如何实现?
I know why this happens but I don't know how I can work around this. I want my flask app to work fine independent from my current working dir, how can I achieve this?
推荐答案
这个确切的用例恰好是flask的open_resource
文档中使用的示例API 调用 以及您问题中链接的蓝图文档.
This exact use case happens to be the example used in the documentation for flask's open_resource
API call as well as the blueprint documentation linked in your question.
具体来说,参考文档说:
Specifically, the reference doc says:
要了解其工作原理,请考虑以下文件夹结构:
To see how this works, consider the following folder structure:
/myapplication.py
/schema.sql
/static
/style.css
/templates
/layout.html
/index.html
如果要打开 schema.sql 文件,请执行以下操作:
If you want to open the schema.sql file you would do the following:
with app.open_resource('schema.sql') as f:
contents = f.read()
do_something_with(contents)
这篇关于获取相对于执行的烧瓶应用程序的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取相对于执行的烧瓶应用程序的路径


- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01