Python Flask study notes the database

Flask in the database

Flask itself does not support databases, database plug-in uses the freedom of choice.

Database is divided into two categories, following the model of the relationship between a class is a relational database, the other is non-relational database, referred to as NoSQL, they do not support the performance of the popular relational query language SQL.

Use Flask-SQLAlchemy database management

Flask-SQLAlchemy Flask extension is a simplified operational use SQLAlchemy in Flask program. SQLAlchemy is a very powerful relational database framework that supports contains a lot of database software MySQL, PostgreSQL and SQLite, including.

  • installation
pip install flask-sqlalchemy
  • Common URL database format
mysql   mysql://username:password@hostname/database
postgres    postgresql://username:password@hostname/database
sqlite  sqlite:///absolute/path/to/database
  • Configuration database
# config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
   
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'marksecret'

    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'mysql://root:root@localhost/flask' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACk_MODIFICATIONS = True
    SQLALCHEMY_COMMIT_TEARDOWN = True

# __init__.py变更后
from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app,db)

from app import routes,models

model

A class definition in the database tables and fields, often called the data model. Examples ORM (SQLAlchemy) will be associated with the class data row in the database table, and the translation related operations.

mysql> desc user;
+---------------+--------------+------+-----+---------+-------+
| Field         | Type         | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+-------+
| id            | int(11)      | NO   | PRI | NULL    |       |
| username      | varchar(64)  | YES  |     | NULL    |       |
| email         | varchar(120) | YES  |     | NULL    |       |
| password_hash | varchar(128) | YES  |     | NULL    |       |
+---------------+--------------+------+-----+---------+-------+

Code

# models.py
from app import db

class User(db.Model):
    
    id =db.Column(db.String(64), primary_key=True,index=True, unique=True)
    username = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))

    def __repr__(self):
        return '<User {}>'.format(self.username)

test

>>> from app.models import User
>>> u = User(username='mark',email='[email protected]')
>>> u
<User mark>
>>> 

relationship

Relational databases using relationships to different rows in a table linked. Once established relationship, the database can show it in the query.

roles table stores all available user roles, each with a unique id values ​​(i.e., the primary key of the table) are identified. In addition users table id primary key, foreign key role_id, reference character id, designated role for each user in this way.

Sample Code

# hello.py
class Role(db.Model):
    #...
    users = db.relationship('User',backref='role')

class User(db.Model):
    #...
    role_id = db.Column(db.Integer,db.ForeignKey('role.id'))

Users using the foreign key relation table connect two lines. Added to the user model role_id is defined as a foreign key, foreign key is this established relationship. Passed db.ForeignKey () role_id parameter indicates that this value is the id column of the table values ​​roles

db.relationship () The first parameter indicates that the relationship is the other end of which model. backref a role attribute parameter added to the user model to define the inverse relationship. This attribute Alternatively role_id accessible role model is a model of the object acquired at this time, instead of the value of a foreign key.

Database operations

  • increase
  • check
  • delete
  • change

    In view of the operation of the database function

    python shell

Database Migration

Guess you like

Origin www.cnblogs.com/mark-zh/p/11290340.html