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)
这篇关于获取相对于执行的烧瓶应用程序的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取相对于执行的烧瓶应用程序的路径
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 无法解决整理冲突 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
