2017-06-12 148 views
1

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

我知道为什么会这样,但我不知道我怎么能解决这个问题。 我希望我的烧瓶应用能够独立于我目前的工作目录工作,我该如何实现这一目标?

+0

通过做正确的事 - 有你的应用需要一个配置参数与在你把你的临时文件的可写目录(或者在操作系统提供的临时目录中写入)。 – pvg

+0

@pvg我不确定你的确切含义以及应该如何帮助。它不是关于写文件,而是关于读取特定文件? – Altoyyr

+0

也许我误解了这一点。你不是在说每次运行创建一个新的sqldb吗? – pvg

回答

1

这个确切的用例恰好是在文档中使用的例子,用于烧瓶open_resourceAPI 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)