Flask 学习笔记(八)-模型Model连接数据库
flask-sqlalchemy
文档:http://flask-sqlalchemy.pocoo.org/2.3/
安装:pip install flask-sqlalchemy
这次使用Pycharm创建一个Flask项目,目录结构如下:
models.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def init_db(app):
db.init_app(app)
class Person(db.Model):
p_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
p_name = db.Column(db.String(16))
创建一个Person类作为ORM模型,有id和name两个字段
init_db为初始化函数,在manage中调用
from flask import Flask
from flask_script import Manager
from App.models import init_db
from App.views import blue
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite3.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.register_blueprint(blueprint=blue)
init_db(app)
manager = Manager(app=app)
if __name__ == '__main__':
manager.run()
其中使用sqlite作为数据库
import random
from flask import Blueprint, render_template
from App.models import Person, db
blue = Blueprint('first_blue', __name__)
@blue.route('/createdb/')
def create_db():
"""建表"""
db.create_all()
return 'DB Create Success'
@blue.route('/addperson/')
def add_person():
"""添加成员"""
p = Person()
p.p_name = "睡着了,拉去除枪毙%d" % random.randrange(100)
db.session.add(p)
db.session.commit()
return 'Person Add Success'
@blue.route('/getpersons/')
def get_persons():
"""查询所有成员"""
persons = Person.query.all()
print(type(persons))
print(persons)
return render_template('PersonList.html', persons=persons)
PersionList.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PersonList</title>
</head>
<body>
<ul>
{% for person in persons %}
<li>{{ person.p_name }}</li>
{% endfor %}
</ul>
</body>
</html>
创建表:http://127.0.0.1:5000/createdb/
先访问createdb创建sqlite3.db数据
添加成员:http://127.0.0.1:5000/addperson/
然后多次访问addperson,添加几个成员
使用pycharm连接sqlite数据库,可以看到刚添加的六个成员信息
查询所有成员:http://127.0.0.1:5000/getpersons/
最后通过模板渲染查询所有成员
使用mysql储存
首先连接mysql创建数据库FlaskModel
create database FlaskModel charset='utf8';
只需将
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite3.db'
改为
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://user:[email protected]:3306/databasename'
# 本机user为 root, password为zzx,databasename为FlaskModel 所以
# app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/FlaskModel'
创建表:http://127.0.0.1:5000/createdb/
先访问createdb创建sqlite3.db数据
添加成员:http://127.0.0.1:5000/addperson/
然后多次访问addperson,添加几个成员
查询所有成员:http://127.0.0.1:5000/getpersons/
最后通过模板渲染查询所有成员
源码地址:https://github.com/565785929/StudyFlask/tree/master/d08