-->
How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python

How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python

Back to top

Updated by Ashirafu Kibalama on April 03, 2024

10 Steps To Fix "The Database Is Created Outside Of The Instance Folder" Error in Flask Python








Adhering to best practices ensures a robust and maintainable codebase in Flask application development. 


However, encountering unexpected hurdles, such as creating a database outside the instance folder, can impede progress and leave developers scratching their heads for solutions. 


In this comprehensive guide, we'll delve into the nuances of this common Flask dilemma and equip you with the knowledge and strategies needed to rectify it effectively. 


If the database is created outside the instance folder, you might encounter an issue with the relative path or your SQLAlchemy connection string configuration. 


Here's what you can do to resolve it: The Database Is Created Outside Of The Instance Folder Flask Python.


10 Steps To Fix The Database Is Created Outside Of The Instance Folder Flask Python.


Step 1.
Import os and from sqlalchemy import create_engine:


import os
from sqlalchemy import create_engine



Create_engine imported from sqlalchemy:

  • This creates an SQLAlchemy engine object based on the provided database URI (DATABASE_URI).
  • The engine object connects to the database and executes SQL commands.
  • It's typically used to establish a connection to the database and perform database operations directly, such as executing queries, inserts, updates, and deletes.


Step 2.
Define the path to the SQLite database file:

# path to the SQLite database file.
DATABASE_URI = 'sqlite:///instance/database.db'


Step 3.
Check if the database file exists:

# Check if the database file exists
if not os.path.exists(DATABASE_URI):
print(f"Error: SQLite database file '{DATABASE_URI}' not found.")
# You might want to handle this error condition appropriately,
# such as creating the database file or exiting the application.


Step 4.
Check permissions of the database file:

# Check permissions of the database file
if not os.access(DATABASE_URI, os.R_OK | os.W_OK):
print(f"Error: Insufficient permissions to access SQLite database file '{DATABASE_URI}'.")
# You might want to handle this error condition appropriately,
# such as modifying file permissions or exiting the application.


Step 5.
Print/debug the SQLAlchemy connection string:

# Print/debug the SQLAlchemy connection string
print("SQLAlchemy Connection String:", DATABASE_URI)



Step 6.
Create SQLAlchemy engine:

# Create SQLAlchemy engine
engine = create_engine(DATABASE_URI)



Step 7.
Attempt to connect to the database:


# Attempt to connect to the database
try:
# This will attempt to connect to the database using the provided URI
connection = engine.connect()
print("Connected to the database successfully!")
connection.close()
except Exception as e:
print("Failed to connect to the database:", e)


Here's the complete code snippet:




# path to the SQLite database file.
DATABASE_URI = 'sqlite:///instance/posts.db'

# Check if the database file exists
if not os.path.exists(DATABASE_URI):
print(f"Error: SQLite database file '{DATABASE_URI}' not found.")
# You might want to handle this error condition appropriately,
# such as creating the database file or exiting the application.

# Check permissions of the database file
if not os.access(DATABASE_URI, os.R_OK | os.W_OK):
print(f"Error: Insufficient permissions to access SQLite database file '{DATABASE_URI}'.")
# You might want to handle this error condition appropriately,
# such as modifying file permissions or exiting the application.

# Print/debug the SQLAlchemy connection string
print("SQLAlchemy Connection String:", DATABASE_URI)

# Create SQLAlchemy engine
engine = create_engine(DATABASE_URI)

# Attempt to connect to the database
try:
# This will attempt to connect to the database using the provided URI
connection = engine.connect()
print("Connected to the database successfully!")
connection.close()
except Exception as e:
print("Failed to connect to the database:", e)





Step 8) Add these lines into your requirements.txt:


gunicorn==21.2.0
psycopg2-binary==2.9.6


Step 9) Modify your SQLALCHEMY_DATABASE_URI:


Remember: DATABASE_URI = 'sqlite:///instance/database.db'. 
So Replace this code'sqlite:///instance/database.db'.

With:

DATABASE_URI.

For example:


1- Change this line:


app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'


To this line:


# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI


2- Change this line:



# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DB_URI", "sqlite:///posts.db")


To this line:


# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DB_URI", "sqlite:///posts.db")
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DB_URI", DATABASE_URI)


Step 10) Finally, Restart your Python app:


In cPanel, go to setup Python app, then click the restart button.


   



Click that Restart button:   



Conclusion:

Flask developers may encounter the "The Database Is Created Outside Of The Instance Folder" error. 


However, this error can be overcome by following the ten steps explained in this blog post. For further assistance, seek help from Flask's community and documentation. 


Embrace the learning process, and may your Flask applications thrive without the hindrance of database creation errors outside of the instance folder.


Please feel free to comment on how helpful this post was or suggest anything we missed.


Happy coding!

Related Posts:


A Beginner's Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting 


How Do I Add or Connect a Flask Python Website To Google Search Console? 


How Do I Add or Connect Google Analytics to a Flask Python Website? 


Other Posts:


What To Look For While Selecting Any Web Hosting Company 


What is Better Than cPanel?


When To Use cPanel? 


Is cPanel Good for Hosting? 


Why do People use cPanel? 


What are the Disadvantages of cPanel Hosting? 


How To Fix: Your Session Cookie is Invalid. Please Log in Again./ Why is cPanel Login Invalid?


Why is there no terminal in cPanel?/ Enable Terminal in Cpanel on Shared Hosting like Namecheap 


How To Approve or Unapproved Results in Flask Python example.


10 When should you use PostgreSQL over SQLite?