小编典典

获取相对于已执行flask应用程序的路径

flask

在我的烧瓶应用程序中,我每次启动时都会重新创建一个sqlite数据库。
为此,我使用官方网页上显示的代码

我的项目结构如下所示

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失败并显示:

在get_db中的文件“ app / StubbyServer.py”中,第43行
带有open(’ schema.sql ‘,mode =’r’),其开头为f:
FileNotFoundError:[Errno 2]没有此类文件或目录:’schema.sql’

我知道为什么会这样,但是我不知道该如何解决。我希望我的烧瓶应用程序能够独立于当前工作目录正常运行,该如何实现?


阅读 485

收藏
2020-04-06

共1个答案

小编典典

这个确切的用例恰好是flask的open_resource API调用文档以及问题中链接的蓝图文档中使用的示例。

具体来说,参考文档说:

若要查看其工作原理,请考虑以下文件夹结构:

/myapplication.py 
     /schema.sql 
     /static
         /style.css 
     /templates
         /layout.html
         /index.html 

如果要打开schema.sql文件,请执行以下操作:

 with app.open_resource('schema.sql') as f:
     contents = f.read()
     do_something_with(contents)
2020-04-06