SQLAlchemy Script

SQLAlchemy:

1. Since the choice method is not provided in sqlalchemy, the choice method provided by the SQLAlchemy-Utils component is used.

 from sqlalchemy_utils import ChoiceType

 Base = declarative_base()

 class Xuan(Base):

     __tablename__ = 'xuan'

     types_choices = (

         (1,'Europe and America'),

         (2, 'Japan and South Korea'),

         (3,'Old Boy'),

     )

     id = Column(Integer,primary_key=True,autoincrement=True)

     name = Column(String(64))

     types = Column(ChoiceType(types_choices,Integer()))

 

     __table_args__ = {

         'mysql_engine':'Innodb',

         'mysql_charset':'utf8',

     }

    

2.scoped_session:

 from sqlalchemy.orm import sessionmaker

 from sqlalchemy import create_engine

 from sqlalchemy.orm import scoped_session

 SessionFactory = sessionmaker(bind=engine)

 # Method 1: Since the thread sharing function cannot be provided, all attention should be paid to creating a session in each thread during development.

 #         from sqlalchemy.orm.session import Session

 # Own operation database: 'close', 'commit', 'connection', 'delete', 'execute', 'expire',.....

 session = SessionFactory()

 # print ('primitive session', session)

 # operate

 session.close()

 # Method 2: Support thread safety, create a session for each thread

 #               - threading.Local

 # - Uniquely identifies

 # ScopedSession object

 # self.registry(), add parentheses to create a session

 # self.registry(), add parentheses to create a session

 # self.registry(), add parentheses to create a session

 from greenlet import getcurrent as get_ident

 session = scoped_session(SessionFactory,get_ident)

 # session.add

 # operate

 session.remove()

3.Flask-SQLAlchemy Flask-Migrate

Flask-SQLAlchemy: Bringing Flask and SQLAlchemy together, the glue

    in the __init__.py file

        1 Introduce SQLAlchemy in Flask-SQLAlchemy and instantiate a SQLAlchemy object

        2 Register Flask-SQLAlchemy:

            - There are two ways

                Method 1: In the function, SQLAlchemy(app) #If you want to use this method in other places, it is not easy to use

                Method 2: Globally:

                    db = SQLAlchemy(),

                    In the function db.init_app(app) #Call the init_app method and put the app in it

        3. Import the class of models

        4. The imported class inherits db.model, but in fact it inherits the Base class in essence

       5. manage.py creates database tables, which can be created by commands. Do it with the help of the Flask-Migrate component

Flask-Migrate:

    - The old 5 was killed: import db in manage.py, then execute db.create_all() to create a table, and then execute drop_all() to delete the table

      This is not good, we can combine it with Flask-Migrate to use

    -新5:Flask-Migrate

        - Install components: pip install Flask-Migrate

        - 5.1 Import   

            from flask_migrate import Migrate, MigrateCommand

            from app import db, app

        - 5.2 migrate = Migrate(app,db) #Create an instance

        - 5.3 Create command

            manager.add_command("db",MigrateCommand)

        - 5.4 Execute command

            python manage.py db init #Execute only the first time

            python manage.py db migrate

            python manage.py db upgrade

    Before executing the command, he has to connect to the database first, and he will know where the table is placed.

from flask_sqlalchemy import SQLAlchemy

from flask import FLask

db = SQLAlchemy()

def create_app():

    app = Flask(__name__)

    db.init_app(app)

    return app

All used components

 Flask

 Two operations to connect to the database

     or DBUtils: for executing native SQL

         Use the sqlhelper in your own util to complete

     or SQLAlchemy: follow his own syntax for chaining

         Method 1: SQLAlchemy (app) This method has limitations. What if I have to use it elsewhere? Can it be written globally?

         Method 2: Advantages,

             Instantiate it: db = SQLAlchemy()

             register:

                 Configure the database connection method in settings

                     SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:[email protected]:3306/s6?charset=utf8"

                     SQLALCHEMY_POOL_SIZE = 2

                     SQLALCHEMY_POOL_TIMEOUT = 30

                     SQLALCHEMY_POOL_RECYCLE = -1

                 Flask-SQLAlchemy: db.init_app(app)       

 Flask-Session #Used to save the session elsewhere

 Flask-Script #Generate command

 Flask-Migrate #Database migration

 Flask-SQLAlchemy #Combines Flask and SQLAlchemy well

     #Essence,: Each time the database is operated, a session connection will be automatically created, and it will be automatically closed when finished.

 Blinker # signal

 Wtforms #FORM component

 Components and versions used

     pip3 freeze #Get all installed modules in the environment

     pip3 freeze > a.txt

     pip3 freeze > requirements.txt

     #pip3 install pipreqs #Help you find all modules of the current program, and automatically generate the requirements.txt file and write the content

     pipreqs ./ #root directory

    

     In the future, someone will give you a program to inform you of the components that need to be installed in a folder: requirements.txt

          Enter the program directory:

             pip install -r requirements.txt # will install all the designed components

    

     structure:

         app

             static

             templates

             views

             __init__.py

             models.py

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325144653&siteId=291194637