-Creating a simple app with flask -Try to create a Home screen -Try to create an authentication function --Try using the database ← ★ Currently here -Try to create CRUD function
This time we will use SQLite.
Mac users are installed by default.
For windows, please install from here. Also, refer to here for the settings.
Installation confirmation
$ sqlite3 -version
3.28.0 ...
Also, install the ORM (Object Relational Mapper) used this time.
mac
$ pip3 install Flask-SQLAlchemy
windows
$ pip install Flask-SQLAlchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SECRET_KEY"] = b'_5#y2L"F4Q8z\n\xec]dasfe/'
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///flask_blog.db'
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy(app)
import src.views
Since we are creating a blog this time, we will have a title and body, and we will also manage the posting date and time in the database. Create a new "models" in the src directory and create "entires.py".
from src import db
from datetime import datetime
class Entry(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
text = db.Column(db.Text)
create_at = db.Column(db.DateTime)
def __init__(self, title=None, text=None):
self.title = title
self.text = text
self.create_at = datetime.now()
Finally, the contents defined in the model are reflected in the database. There are two reactions to the database:
This time, I will introduce the execution with a script. (This is less likely to make mistakes and is often used in actual development environments.)
First, install the libraries needed to run the script.
mac
$ pip3 install Flask-Script
windows
$ pip install Flask-Script
The actual script is as follows.
import sys
sys.dont_write_bytecode = True
from flask_script import Command
from flask_script import Manager
from src import app
from src import db
class InitDB(Command):
def run(self):
db.create_all()
if __name__ == '__main__':
m = Manager(app)
m.add_command('init_db', InitDB())
m.run()
Execute the created script file.
mac
$ python3 manage.py init_db
windows
$ python manage.py init_db
After running, you should see a file called'flask_blog.db'created in the'src' directory.
Recommended Posts