Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

python - Get path relative to executed flask app

In my flask app I recreate a sqlite database at every start.
For this I use code as shown on the official webpage

My project structure looks like this

project_dir/
|-README.md
`-app/
  |-StubbyServer.py (contains the flask root)
  |-schema.sql
  `- (all the other files)

Now my StubbyServer.py contains:

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

If my working directory is /path/project_dir/app the command python StubbyServer.py works fine

If my working directory is /path/project_dir the command python app/StubbyServer.py fails with:

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'

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...