Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Todo API with Flask

Alx Ki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alx Ki
Python Web Development Techdegree Graduate 14,822 Points

Unable to open database file Error

Please, help, Kenneth Love ! I've got a problem: I can initialize the db from console with models.initialize() BUT when I run my app i get an exception right on initialization. Can't recognize the problem..

app.py:

from flask import Flask, g, jsonify, render_template

import config

import models

from resources.todos import todos_api

app = Flask(__name__)
app.register_blueprint(todos_api, url_prefix='/api/v1')


@app.route('/')
def my_todos():
    return render_template('index.html')

if __name__ == '__main__':
    models.initialize()
    app.run(debug=config.DEBUG)

models.py:

import datetime

from peewee import *

import config

DATABASE = SqliteDatabase('todos.sqlite', threadlocals=True)
HASHER = PasswordHasher()


class User(Model):
    username = CharField(unique=True)
    email = CharField(unique=True)
    password = CharField()

    class Meta:
        database = DATABASE



class Todo(Model):
    name = CharField(max_length=255, unique=True)
    completed = BooleanField(default=False)
    created_at = CharField(default=datetime.datetime.now)

    class Meta:
        database = DATABASE


def initialize():
    DATABASE.connect()
    DATABASE.create_tables([User, Todo], safe=True)
    DATABASE.close()

exception:

sqlite3.OperationalError: unable to open database file

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C://angular-todo_v2/app.py", line 18, in <module>
    models.initialize()
  File "C:\\angular-todo_v2\models.py", line 70, in initialize
    DATABASE.connect()

4 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

So, I got it to work. Not sure exactly why this works, though.

import os

DATABASE = SqliteDatabase(
    os.path.join(
        os.path.dirname(os.path.realpath(__file__)),
        'todos.db'
    ),
    threadlocals=True
)

All this is really doing is finding the current directory and then prepending that to the database file name.

You'd probably want to put this in config.py or something as like BASE_DIR and then use that everywhere you need a file path.

So weird.

Alx Ki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alx Ki
Python Web Development Techdegree Graduate 14,822 Points

Thank You! I'd spend years on it! Probably whole life.))

So it founds its place with os.path.realpath(file) and then "puts it here"/todos.db. OK... But why? I mean DB is in the same folder!

Can I ask how did you get to it?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Uh, shear doggedness? :)

It wasn't able to find the file when the app.py script was run but it did work when the function was run directly through the shell. Well, the only thing that changes between those is the entry point, right? Now, they're both in the same directory, so I don't see why that matters at all but that's what lead me down that path. When I hardcoded a full path, the app.py function call worked. So...use Python to find the full path.

Kenneth Love & Alexey Kislitsin ,

You guys saved my life, I was trying to solve this problem for hours at work, I guess Kenneth too. Anyhow thank you.

Alexey, are you using windows? I am wondering because I have used peewee many times in OSX and Linux with not problem. The only time I've seen this in on windows.

Just for future reference, I believe that the 'threadlocals' argument is 'True' by default in the BaseModel class definition in peewee.py

-Dan

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Just checking, after you run models.initialize(), does the DB file exist? Does it have any weird permissions that would stop you from accessing it (unlikely but still good to check)?

Alx Ki
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alx Ki
Python Web Development Techdegree Graduate 14,822 Points

Hello, Kenneth! If I run:

import models
models.initialize()

From console, everything runs as expected. DB file being created well.

But if i run app.py (no matter with existing DB or without) than exception happens.

PS Just realized that same thing happens with courses.py from Flask REST API. It worked well couple days ago! Must be something wrong.. reinstalled venv - does not help.

Traceback (most recent call last):
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3600, in connect
    **self.connect_kwargs)
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3869, in _connect
    conn = sqlite3.connect(database, **kwargs)
sqlite3.OperationalError: unable to open database file

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C://courses/courses.py", line 40, in <module>
    models.initialize()
  File "C:\\courses\models.py", line 81, in initialize
    DATABASE.connect()
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3602, in connect
    self.initialize_connection(self._local.conn)
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3514, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "C:\\virtenv\lib\site-packages\peewee.py", line 134, in reraise
    raise value.with_traceback(tb)
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3600, in connect
    **self.connect_kwargs)
  File "C:\\virtenv\lib\site-packages\peewee.py", line 3869, in _connect
    conn = sqlite3.connect(database, **kwargs)
peewee.OperationalError: unable to open database file

What kind of permissions do you mean?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

File and folder permissions. If, for some extremely odd reason you could write but not read or something.

Hmm, wonder if there have been any updates to Peewee to make this work differently. I'll check and report back.

EDIT

Nope, the docs still support exactly this format. Let me try it myself.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

WEIRD

I get the exact same output (so you're not hallucinating!) but I have no idea why it would do that.

Still investigating.