2
votes

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?

1
By doing the right thing - have your app take a config parameter with a writeable dir where you keep your temporary files (or write in an OS-provided temp dir). - pvg
@pvg I am not sure what you exactly mean and how that should help. It is not about writing files it is about reading a specific file? - JDurstberger
Maybe I'm misunderstanding this then. Aren't you talking about creating a new sqldb on every run? - pvg
Actually you are right, my database path is also using a relative one, so it will create a DB in the working dir. But fixing this would still not solve the problem of reading the schema. :( - JDurstberger
The docs you are linking show reading the schema from the resource dir. Is there some reason you're not doing it that way? - pvg

1 Answers

2
votes

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)