1

I am writing a simple social media app using flask python framework and Sqlite as database. But after running the program, it shows the following error. I am kind of confused what is causing the bug.

peewee.OperationalError: Connection already open

My plan is to create a login view so that users can enter their email, and passoword to login. So far I've created a view for logging in and it redirects users back to the index page. The above error suggests I haven't closed the database. However, the two functions (in models.py) I've written for connecting to, and closing the database are given below:

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

And I call it in app.py by models.initialize()

if __name__ == '__main__':
    models.initialize()
    app.run(debug=True, port=8000, host='0.0.0.0')

With that the app.py has the following methods with function decorator:

@app.before_request
def before_request():
    """Connect to the database before each request"""
    g.db = models.DATABASE
    g.db.connect()


@app.after_request
def after_request(response):
    """Close the database after each request"""
    g.db.close()
    return response
Naz Islam
  • 409
  • 1
  • 6
  • 20

1 Answers1

0

Somehow it would seem like a connection is being leaked. You can use get_conn() instead of connect() and this will ensure a connection is not opened twice.

coleifer
  • 24,887
  • 6
  • 60
  • 75