This time, first of all, we will set up and use the database. In order to post and browse articles, it is necessary to save the article data so that the data can be retrieved as needed. The database is the place to store article data, and it processes the system for efficiently storing and retrieving data from the database. SQLAlchemy SQLAlchamy is a library that makes it easy to work with databases in Flask.
Set as follows in config.py. This time we will use a database called SQLite.
python:./cafesite/config.py
SQLALCHEMY_DATABASE_URI = 'sqlite:///cafe_site.db'
SQLALCHEMY_TRACK_MODIFICATIONS = True
DEBUG = True
SECRET_KEY = 'secret key'
USERNAME = 'john'
PASSWORD = 'abc123'
Also edit ** __ init__.py **.
python:./cafesite/config.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('cafe_site.config')
db = SQLAlchemy(app)
import cafe_site.views
You can handle the database from the db variable by installing the SQLAlchemy library and writing db = SQLAlchemy (app)
.
Next, define the database model. Articles need three attributes: title, body, and date and time of posting. We will define such attributes in the database model.
Now let's model the article. Create a ** models ** folder under the ** cafe_site ** folder, and create a ** reviews.py ** file in it.
python:./cafesite/models/reviews.py
from cafe_site import db
from datetime import datetime
class Review(db.Model):
__tablename__ = 'Reviews'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
text = db.Column(db.Text)
created_at = db.Column(db.DateTime)
def __init__(self, title=None, text=None):
self.title = title
self.text = text
self.created_at = datetime.utcnow()
def __repr__(self):
return '<Review id:{} title:{} text:{}>'.format(self.id, self.title, self.text)
class Review (db.Model):
defines the model and __tablename__ ='Reviews'
names the tables stored in the database.
python:./cafesite/models/reviews.py
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
text = db.Column(db.Text)
created_at = db.Column(db.DateTime)
When retrieving data, use the ** primary_key ** ʻid. The * id attribute * is an important attribute that is always required when defining a model. The attributes are defined according to the rules from the second line onward. ʻUnique = True
is a process to prevent duplication.
def __init __ (self, title = None, text = None):
defines the standard behavior when the model is created.
python:./cafesite/models/reviews.py
def __init__(self, title=None, text=None):
self.title = title
self.text = text
self.created_at = datetime.utcnow()
With this definition, article data will be created with the specified title and content and the current time as the posting date and time by writing as follows in the future.
Review(title="Article title", text="Article content")
python:./cafesite/models/reviews.py
def __repr__(self):
return '<Review id:{} title:{} text:{}>'.format(self.id, self.title, self.text)
Here, ** id **, ** title **, and ** text ** are displayed on the console.
Create a ** scripts ** folder under cafe_site and create a ** db.py ** file in it.
python:./cafe_site/scripts/db.py
from flask_script import Command
from cafe_site import db
class InitDB(Command):
"create database"
def run(self):
db.create_all()
Define a class with class InitDB (Command):
. By setting (Command)
, it is defined as a class for script execution.
" createdatabse "
is a comment to describe the class.
def run (self):
is what is actually executed by the script. The model definition is reflected in the database by setting db.create_all ()
as the execution content.
Next, register the created scripts.py
so that it can be executed on the console.
Create a file named manage.py directly under the root directory.
python:./manage.py
from flask_script import Manager
from cafe_site import app
from cafe_site.scripts.db import InitDB
if __name__ == "__main__":
manager = Manager(app)
manager.add_command('init_db', InitDB())
manager.run()
The script file is registered with ʻif__name__ =="main ":. By setting
manager.add_command ('init_db', InitDB ())`, the created InitDB () module can be executed with the name init_db.
console
python manage.py init_db
After execution, a ** cafe_site.db ** file will be created under the ** cafe_site ** folder.
The continuation will be explained in Creating a web application using Flask ③.
Recommended Posts