A, preparation,

  1. Install MySQL: Install MySQL
  2. Install the required Python libraries

    pip install flask
    pip install flask-sqlalchemy
    pip install pymysql

Write Python code

From flask import flask from flask_sqlalchemy import SQLAlchemy app= flask (__name__) app.config['SECRET_KEY']='2333' # password App. config[' sqlAlchemy_database_uri ']=' MySQL + PyMySQL ://root:2333@localhost:3306/runoob' # localhost # localhost # localhost # localhost # localhost # localhost # localhost App.config [' SQLAlchemy_commit_on_teardown ']=True db=SQLAlchemy(app) __tablename__='roles' # id=db.Column(db.Integer, primary_key=True) # id, int type, Name =db.Column(db.String(64), unique=True) Def __repr__(self): users=db.relationship('User', backref='role', lazy='dynamic') def __repr__(self): Mysql > create table User class User(db.model) select User from User class User(db.model); __tablename__='users' id=db.Column(db.Integer, primary_key=True) username=db.Column(db.String(64), unique=True, Index =True) # def __repr__(self): def __repr__(self): Return '<User %r>' %self.username if __name__=='__main__': db.drop_all()

Run it. The results of successful operation are as follows:

* Serving Flask app "HelloMysql" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug Mode: Off * Running on http://127.0.0.1:5000/ (Press Ctrl +C to quit)

Third, look at the database

mysql> SHOW DATABASES; mysql> use RUNOOB; // mysql> SHOW TABLES;

The table was created successfully:

+------------------+
| Tables_in_runoob |
+------------------+
| roles            |
| users            |
+------------------+

Four, reference

Communication University of China “data visualization” class 33