Detailed description of instances connected by flask and mysql (python)

Source: Internet
Author: User
A flask-based web application was born in the fourth article. This article mainly introduces how to interconnect flask and mysql, which has a certain reference value, interested friends can refer to the fourth article on flask-based web application birth. This article mainly introduces how to interconnect flask and mysql, which has a certain reference value, for more information, see

In the previous chapter, some functions of logon are implemented. The reason is that it is not possible to write the username and password as a fixed value. a complete function requires at least registration and logon, password modification, which requires the ability to store these values in the database.

The current mainstream databases are divided into two types: relational databases and NoSql databases. for small and medium-sized systems, the performance and ease of use of these two types of databases are quite good choices.

Basic configuration

Here we use the flask integration package of the SQLAlchemy database framework, namely, flask-SQLAlchemy, to perform database operations.

SQLAlchemy is a very good framework that simplifies database operations. It provides high-level ORM and low-level SQL functions, making it easy to use.

Installation method and previous type, or pip command:

pip3.6 install flask-sqlalchemy

After the installation is complete, modify the default configuration. first import the package:

from flask.ext.sqlalchemy import SQLAlchemy

Then configure the link string:

app.config["SQLALCHEMY_DATABASE_URI"]='mysql://root:1234@localhost/cblog'

After the configuration request is complete, changes are automatically submitted:

app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"]=True

Instantiate SQLAlchemy:

db=SQLAlchemy(app)

Model settings

After the installation is complete, continue to improve the logon example, modify the default. py file, and add the User model (class) and Role model (to show Association)

Role class

Class Role (db. model): # inherit from Model _ tablename __= "roles" # the database indicates that if this parameter is not set, the default name id = db will be the same as that of the class. column (db. integer, primary_key = True) # SQLAlchemy requires a primary key. generally, name = db after the name is id. column (db. string (50), unique = True) # indicates that name is a String and users = db is not repeated. relationship ("User", backref = 'role') # associate the user model and add backref to the user)

User class

Class User (db. model): _ tablename __= "users" id = db. column (db. integer, primary_key = True) username = db. column (db. string (50), unique = True, index = True) # this column contains the index password = db. column (db. string (50) role_id = db. column (db. integer, db. foreignKey ("roles. id ") # The foreign key points to the id column in the roles table

The following describes how to execute the code, which is convenient and cannot intrude into the logic code. This requires that the code cannot be hardcoded into the logic code, for example, the code used to determine the database status is passed to the app as a parameter. run (). at this time, shell came in handy.

Configuration script

To enable flask to support command line scripts, you must first install the flask-script extension:

pip3.6 install flask-script

Modify the default. py code:

from flask.ext.script import Managermamager=Manager(app)....if __name__=='__main__': #app.run(debug=True) mamager.run()

After modification, run the following command again:

python default.py

The error message is displayed as follows:

Install the c ++ toolkit as prompted.

Landinghub.visualstudio.com/visual-cpp-build-tools

The downloaded file is an exe file.

After the restart, install MySQL-python and find that it is still not available. only after Baidu found that the MySQLdb library supports only python2.7, not 3.x, so you have to use other methods to use the PyMySQL Library:

pip3.6 install PyMySQL

Then modify the default. py code and add two lines:

import pymysqlpymysql.install_as_MySQLdb()

Go to the source code and pay attention to this line:

sys.modules["MySQLdb"] = sys.modules["_mysql"] = sys.modules["pymysql"]

You can use and connect to mysql.
Enter the connection in the browser and enter the site correctly.

Next, use shell to create a database table and enter the default. py root directory:

python default.py shellfrom default import dbdb.create_all()

If no error is reported at this time, the database table should be created:

The problem arises. at this time, modifying the model will not be reflected in the db. what should I do if I modify the model? For the moment, it is also very simple:

db.drop_all()db.create_all()

However, this is only used during debugging. if data already exists in the database, it is definitely intolerable. at this time, it is the turn of the database migration plug-in Migrate to debut. The first thing is the same, installation required:

pip3.6 install flask-migrate

As before, after the installation is complete, modify the default. py file for configuration:

From flask. ext. migrate import Migrate, MigrateCommandmigrate = Migrate (app, db) # configure migration mamager. add_command ("db", MigrateCommand) # configure migration commands

Use the init command to initialize the migration warehouse.

 python default.py db init

Command line display:

Indicates that the migration file has been initialized.

The migrate framework provides some commands for Migration (using the default. py file as an example ):

# Create and migrate python default. py db migrate-m according to the difference "# change difference python default. py db upgrade # cancel the difference change python default. py db downgrade

Return to Form

Next, let's take a look at how to associate the login with the database and modify the code in the login method:

@ App. route ("/login", methods = ["POST"]) def loginPost (): username = request. form. get ("username", "") password = request. form. get ("password", "") user = User. query. filter_by (username = username, password = password ). first () # Database query if user is not None: session ["user"] = username return render_template ("/index.html", name = username, site_name = 'myblog ') else: flash ("the user name or password you entered is incorrect") return render_template ("/login.html") # The logon page is still returned.

The execution result is perfect.

Summary

Below are some summative things about the connection between python and db.

Data type

After these chapters, the login function has been basically completed. in the next chapter, we will explain the functions related to user registration.

The above is the detailed description of the instance (python) connecting flask and mysql. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.