Skip to main content
 首页 » 编程设计

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

2024年10月01日7birdshome

在我的 flask 应用程序中,我每次启动时都会重新创建一个 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'

我知道为什么会这样,但我不知道该如何解决。 我希望我的 Flask 应用独立于我当前的工作目录正常工作,我该如何实现?

请您参考如下方法:

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

具体来说,引用文档说:

To see how this works, consider the following folder structure:

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

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)