Connection between flask and sqlite3

# Introduction We use Flask to create an application from scratch and organize it so that you can learn the necessary technology.

-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

Access database

Database installation / configuration

This time we will use SQLite.

$ 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

Model definition

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

Execution of common processing in script

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

Connection between flask and sqlite3
Flask and sqlite3 are like bulletin boards
speed difference between wsgi, Bottle and Flask
Easy connection between Raspberry Pi and AWS IoT
Between parametric and nonparametric
[Ruby vs Python] Benchmark comparison between Rails and Flask
Flask automatically switches template directories between PC and mobile
Visualization of the connection between malware and the callback server
Difference between process and job
Correspondence between pandas and SQL
Conversion between unixtime and datetime
Install Python and Flask (Windows 10)
Difference between regression and classification
Collaboration between PTVS and Anaconda
Send and receive Flask images
React and Flask to GCP
Difference between np.array and np.arange
Difference between MicroPython and CPython
Cooperation between py2exe and setuptools
Boundary between C and Golang
Difference between ps a and ps -a
Difference between return and print-Python
[Free study] Is there a connection between Wikipedia updates and trends?
Difference between Ruby and Python split
Differences between Windows and Linux directories
Django's MVT-Relationship between Models and Modules-
Difference between java and python (memo)
Differences between yum commands and APT commands
Difference between == and is in python
[Note] Conflict between matplotlib and zstd
Memorandum (difference between csv.reader and csv.dictreader)
Correspondence between RecyclerView and Marker (Kotlin)
(Note) Difference between gateway and default gateway
Cooperation between python module and API
Difference between Numpy randint and Random randint
Differences between Python, stftime and strptime
Basic authentication and Digest authentication with Flask
Difference between sort and sorted (memorial)
Difference between python2 series and python3 series dict.keys ()
Speed comparison between CPython and PyPy
[Python] Difference between function and method
Difference between SQLAlchemy flush () and commit ()
Python --Difference between exec and eval
[Python] Difference between randrange () and randint ()
[Python] Difference between sorted and sorted (Colaboratory)