SoFunction
Updated on 2024-11-10

Introduction to the Python Flask model and how to configure it

Flask data model and connecting to a database

flask is based on the structure of MTV, where M refers to the model, that is, the data model, in the project corresponds to the database. flask and the database to establish a connection there are many ways, but generally divided into two kinds, one is to use pymsql to establish a connection to the database; and one is the way of ORM mapping (based on pymysql), this way is commonly used in web development. In the form of objects and database tables to do mapping, easy to object in the page display. The following record to mysql and orm way to connect to the database.

I. Installation

To prepare, install the library:

pip3 install pymysql        highway construction

pip3 install flask-sqlalchemy    realizationORMmap (math.)

pip3 install flask-migrate     Release Command Tool

II. Configuring database connections and creating model classes

Steps:
(1) Configure the connection path to the database

# mysql+pymysql://user:password@hostip:port/databasename
# database+pymysql://username:password@hostip:port/database name
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/flaskdemo'

(2) flask-sqlalchemy construction: in the apps package to create package ext (third-party libraries are usually configured to build an ext folder to store), used to store the code related to the database, in the __init__.py to add:

   db = SQLAlchemy()   ---->have to followappliaison

In apps/init.py file (here I have separated the startup of the app from the app initialization, here __init__ is the initialization of the app) under the connection to the app:

   def create_app():
        ....
        # Talk to the app
        db.init_app(app)

        return app

(3) Create a model:, a model is a class, often called a model class.

  class User():      ------> usera meter (measuring sth)
    id = (, primary_key=True, autoincrement=True)
    username = ((15), nullable=False)
    password = ((12), nullable=False)
    phone = ((11), unique=True)
    rdatetime = (, default=)

Common data types:
Integer
String(size) String type, be sure to specify the size.
Text Long text type
DateTime
Float Floating point type
Boolean Boolean type
PickleType stores the pickle type, mainly related to serialization.
LargeBinary Stores large binary types.

Optional:
primary_key=True primary_key
autoincrement=True Self-incrementing
nullable=False does not allow nulls
unique=True unique
default= default value Can be set to the current system time or any other value.

III. Using commands to create database tables

a. Import the model in: from import User - "Associate the model with the app".
b. At the terminal, use the command: db to create a database/update a database.
flask db init -----" generate a folder migrations
flask db migrate -----> a version file is automatically generated
flask db upgrade ------> synchronize, complete database table creation

     Project structure
      | ---apps
      | ---ext
      | ---migrations    flask db init     simplyinit(math.) linear (of degree one)
               |---versions   version folder
                    |---71edde7ee937_.py    ---》 flask db migrate  migration
                    |---cc0dca61130f_.py
                                                  flask  db upgrade synchronization
                                                  flask  db downgrade demote

IV. Registration as an example

1. Create app, migrate (bind app, database), start the portal

The __init__.py file under the file initializes the app configuration

3. Database Configuration

4. Create a model class

5. Create database tables by command
flask db init -----" generate a folder migrations
flask db migrate -----> a version file is automatically generated
flask db upgrade ------> synchronize, complete database table creation
At the moment you can see the created database tables in pycharm's database view

6. Write registration logic (views)

# User registration
@user_bp.route('/register', methods=['GET', 'POST'])
def register():
    if  == 'POST':
        username = ('username')
        password = ('password')
        repassword = ('repassword')
        phone = ('phone')
        email = ('email')
        if password == repassword:
            # Registered users
            user = User()
             = username
            # Custom encryption: new_password = hashlib.sha256(('utf-8')).hexdigest()
            # Implement encryption using its own function: generate_password_hash
             = generate_password_hash(password)
            print(len())
             = phone
             = email
            # Add and submit
            (user)
            ()
            return redirect(url_for(''))
    return render_template('user/')

7. Writing templates that html page can realize the simple registration function to achieve the integration of MTV

To this point this article on the Python Flask model and configuration method of the article is introduced to this, more related Python Flask model content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!