2021-09-12 mapping binding configuration from virtual environment to MYSQL

Create a virtual environment under directory 123

c:/123
virtualenv 123

Installing flash 1.12

pip install flask==1.1.2

Install pymysql 1.0.2

pip install pymysql

Install flash script

pip install flask-script

Install flash Sqlalchemy

pip install flask-sqlalchemy

When installing flash migrate, pay attention to version 2.5.3, otherwise there is no MigrateCommand command

pip install flask-migrate

Establish a flash project in pycharm and use virtual environment 123

Write the contents of the configuration setting.py file under the project root directory

class Config(object):
    DEBUG=1
    SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:password@127.0.0.1:3306/mysql01'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    EVN='development'

Create two packages at the root of the project

  1. apps
  2. exts

Write factory configuration function in app.init.py

from setting import Config

def create_app(app):

    app.config.from_object(Config)

    return  app

The main function app.py currently introduces the factory function status

from flask import Flask
from apps import create_app
app = Flask(__name__)
app = create_app(app)#The app goes out and then comes back to ensure that the app location remains unchanged

@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    app.run()

Then add

from flask_script import Manager
manager =Manager(app=app)

Then modify

if __name__ == '__main__':
    app.run()

Modify the startup function app.run() to manager.run()

if __name__ == '__main__':
    manager.run()

The above builds flash_ Script part, which realizes the function of executing Python internal functions from the command line*

Here is flask SQL alchemy

Write in exts.init.py

from flask_sqlalchemy import SQLAlchemy
db =SQLAlchemy()

Next, configure the DB into the factory function

from setting import Config
from exts import db #  This DB is made by SQLAlchemy

def create_app(app):

    app.config.from_object(Config)
    db.init_app(app)  # This is the binding method provided by SQLAlchemy
    return  app

Pay attention to flash in this section_ Sqlalchemy has some environment configuration information in setting that belongs to him.

Finally, the flash migrate section is imported from app.py

from flask_migrate import Migrate ,MigrateCommand    #Last bound
from exts import db                  # db import

Then migrate binding

migrate = Migrate(app=app,db=db)
manager.add_command('db',MigrateCommand)

So far, the main link has been built, and the program can only be started on the command line. Here's a note: you can't run away from the virtual environment, otherwise you won't find the package.

The following is how to use. First, create a user class

  1. Create a user package in the apps directory and create a new models.py file in the package

The file writes model classes internally

from exts import db
from datetime import datetime
class User(db.Model):# The loading of db here is not his own method
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username = db.Column(db.String(15),nullable=False)
    password = db.Column(db.String(12),nullable=False)
    phone = db.Column(db.String(1),unique=True)#This unique means unique
    rdatetime =db.Column(db.DateTime,default=datetime.now) #Note that there are no parentheses after the date function now
    def __str__(self):# This method must have a return name
        return self.username

After the model is established, pay attention to the following

To introduce this model into the main function

That is, it is introduced in app.py

from apps.user.models import User  # This line must have

The portal app.py is now

from flask import Flask
from flask_script import Manager
from apps import create_app
from flask_migrate import Migrate ,MigrateCommand    #Last bound
from exts import db                  # db import
from apps.user.models import User  # This line must have
app = Flask(__name__)
app = create_app(app)

manager =Manager(app=app) #Command line correlation
migrate = Migrate(app=app,db=db)
manager.add_command('db',MigrateCommand)
@app.route('/')
def hello_world():
    return 'Hello World!'


if __name__ == '__main__':
    manager.run()

Execute in the virtual environment after the whole is completed

  1. Establish a set of directories and files locally
Python app.py db init  
  1. Add files to local directory
python mysql.py db migrate

Note here that this command will connect to the database. If the database does not have the specified name, an error will be reported. Be sure to establish the database to connect in advance.

  1. Execute synchronization instruction
python mysql.py db upgrade

db internal commands are as follows

 init                Creates a new migration repository
    revision            Create a new revision file.
    migrate             Alias for 'revision --autogenerate'
    edit                Edit current revision.
    merge               Merge two revisions together. Creates a new migration
                        file
    upgrade             Upgrade to a later version
    downgrade           Revert to a previous version
    show                Show the revision denoted by the given symbol.
    history             List changeset scripts in chronological order.
    heads               Show current available heads in the script directory
    branches            Show current branch points
    current             Display the current revision for each database.
    stamp               'stamp' the revision table with the given revision;
                        don't run any migrations

So far, China Unicom has been realized, and a table called user has been established in the specified database.

Tags: Python MySQL Flask

Posted on Fri, 19 Nov 2021 20:50:35 -0500 by DocUK