-
Notifications
You must be signed in to change notification settings - Fork 1
Database setup
when building an application we need some way to store user and user related information. We do that using database.
In this project, we will be using sqlalchemy library to manage configuration and interactions with the database.
Install the sqlalchemy using the command given below:
pip install flask-sqlalchemy
flask-sqlalchemy is sqlalchemy with default configuration set for flask which makes it easier to use.
Once we have installed this library, we will instantiate sqlalchemy with our app so that it can interact with models(tables) defined in our app.
We do this as follows:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'
db = SQLAlchemy(app)
from blog import routes
- Remember to keep import for the routes at the end to avoid circular import
here, SQLALCHEMY_DATABASE_URI informs the sqlalchemy about the database that our application needs to interact with
- sqlite -> type of database
- /// -> refers to current directory(location where the database file will be stored)
- blog.db -> name of the database
Now, we can create the database as follows:
- go the python console by typing python in your terminal
- import db from blog
- db.create_all()
after you enter the command, you should see a file name blog.db created in your blog directory
├── blog
│ ├── blog.db
│ ├── __init__.py
│ ├── routes.py
│ └── templates
│ ├── about.html
│ └── home.html
├── run.py
The advantage of using sqlalchemy is that is you can switch between any database just by changing the SQLACHEMY_DATABASE_URI.
lets say we wanted to use postgres or mysql instead of sqlite, all we need to do is
for postgres
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://scot:tiger@localhost/my_database'
for mysql
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://scott:tiger@localhost/my_database'
here,
- scot -> user of the database
- tiger-> password for the user
- localhost-> hostname
- my_database -> name of your database
Implementation can be found over this commit