获取相对于执行的烧瓶应用程序的路径

2021-12-14 00:00:00 python flask sqlite

在我的 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)

相关文章