[PYTHON] Creating a web application using Flask ②

Handle database

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.

SQLAlchemy initialization

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).

Creating a model (Model on MTV)

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.

Model definition

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.

Attribute definition

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.

Processing after model creation

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")

Define the display format when referenced

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.

Creating a script that allows you to use fixed processes in common

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.

Create manage.py

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

Creating a web application using Flask ②
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
Creating a voice transcription web application
Try using the web application framework Flask
Creating a data analysis application using Streamlit
Web application using Bottle (1)
Creating an interactive application using a topic model
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
I want to make a web application using React and Python flask
WEB application development using django-Development 1-
Web application development with Flask
Web application with Python + Flask ② ③
Web application with Python + Flask ④
(Python) Try to develop a web application using Django
[Raspberry Pi] Publish a web application on https using Apache + WSGI + Python Flask
WEB application development using Django [Django startup]
WEB application development using Django [Application addition]
Creating a Flask server with Docker
Creating a simple table using prettytable
Creating a simple app with flask
Build a web application with Django
Make Flask a Cloud Native application
Creating a learning model using MNIST
Let's make a WEB application for phone book with flask Part 1
Web application created with Python + Flask (using VScode) # 1-Virtual environment construction-
Python: Introduction to Flask: Creating a number identification app using MNIST
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Let's make a WEB application for phone book with flask Part 2
Let's make a WEB application for phone book with flask Part 3
Let's make a WEB application for phone book with flask Part 4
WEB application development using Django [Model definition]
WEB application development using Django [Initial settings]
WEB application development using django-Development environment construction-
Display matplotlib diagrams in a web application
Impressions of using Flask for a month
WEB application development using Django [Request processing]
WEB application development using Django [Template addition]
[Python] A quick web application with Bottle!
Create a simple web app with flask
Run a Python web application with Docker
Create a web service with Docker + Flask
I tried benchmarking a web application framework
I made a WEB application with Django
Create a Python3.4 + Nginx + uWSGI + Flask Web application execution environment with haste using pyenv on Ubuntu 12.04
Flask application settings
Start a web server using Bottle and Flask (I also tried using Apache)
Implement a simple application with Python full scratch without using a web framework.
[Python] Split a large Flask file using Blueprint
WEB application development using Django [Admin screen creation]
Create a web map using Python and GDAL
Steps to develop a web application in Python
Launch a web server with Python and Flask
What I was addicted to when creating a web application in a windows environment
Go beginner tried to create a cloud native web application using Datastore / GAE
[ES Lab] I tried to develop a WEB application with Python and Flask ②
A story about creating a web application that automatically generates Minecraft sound block performances
Create a web app that converts PDF to text using Flask and PyPDF2
Try creating a web application with Vue.js and Django (Mac)-(1) Environment construction, application creation
Create a web application execution environment of Python3.4 + Nginx + uWSGI + Flask with haste using venv on Ubuntu 14.04 LTS