Flask 结合SQLAlchemy 打通数据库通讯

使用豆瓣源安装flask_sqlalchemypip install -i https://pypi.douban.com/simple/ flask_sqlalchemy

使用豆瓣源安装mysqlclientpip install -i https://pypi.douban.com/simple/ mysqlclient

数据库配置

application.py

# -*- coding: utf-8 -*-
from flask import Flask

from flask_sqlalchemy import SQLAlchemy
app = Flask( __name__ )

app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:123456@127.0.0.1/mysql"
db = SQLAlchemy( app )

Flask查询数据库

from sqlalchemy import text

@index_page.route( "/" )
def index_page_index():
    sql = text("select * from `user`")
    result = db.engine.execute(sql)
    context = {}
    context['result'] = result
    return render_template("index.html", **context)

通过 Model 访问 数据库

在项目的子文件夹下创建common->models目录,
创建user.py模块

# -*- coding: utf-8 -*-
from application import db
class User( db.Model ):
    Host = db.Column( db.String( 80 ),primary_key=True )
    User = db.Column( db.String( 120 ) )

indexController.py

from common.models.user import User

@index_page.route( "/" )
def index_page_index():
    result = User.query.all()
    context = {}
    context['result'] = result
    return render_template("index.html", **context)

自动生成model

  • 使用豆瓣源安装flask-sqlacodegenpip install -i https://pypi.douban.com/simple/ flask-sqlacodegen

  • 自动生成model的语法如下:
    flask-sqlacodegen "mysql://root:123456@127.0.0.1/movie_cat" --tables user --outfile "common/models/user.py" --flask