python3.5+flask+mysql
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3.5+flask+mysql相关的知识,希望对你有一定的参考价值。
该篇博客配置环境为:python版本3.5,flask2.0,python3中已经不再支持MySQLdb模块,所有这里我用了pymysql,所有使用前应该
安装pymysql:pip install pymysql
在网上的好多资料都给的是使用sqlite的例子,由于很不喜欢所以今天分享一下flask-sqlalchemy操作mysql的方法.
以前习惯使用sqlalchemy,后来发现使用flask-sqlchemy还是要简单一些(起码省去了好多模块和类的导入,create_engine,sessionmaker,declarative。。。)不过flask官方的例子用的是sqlchemy,去官网, flask-sqlalchemy官方文档
这里写一个简单的flask web程序,来说明flask-sqlalchemy如何驱动msyql数据库.为了偷懒,这个例子以上一篇博文flask蓝图的使用为基础.
首先看一下程序结构:
相比上一节只多了两个文件,create_db.py,models.py
1.建立mysql和app的连接
在config.py中加入以下两项配置:
SQLALCHEMY_DATABASE_URI = ‘mysql+pymysql://root:[email protected]:3306/test?charset=utf8‘
SQLALCHEMY_TRACK_MODIFICATIONS = True
如此在app/__init__.py中加入
app.config.from_object(‘config‘)
db = SQLAlchemy(app)
就可以完成app和数据的关联,并生成一个可以操作app数据库的SQLAlchemy实例db
完整的app/__init__.py代码如下:
from flask import Flask, url_for, request, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object(‘config‘) db = SQLAlchemy(app) from app import models,views
2.创建app/models.py模块
上代码
from app import db #db是在app/__init__.py生成的关联后的SQLAlchemy实例 class User(db.Model): __tablename__ = ‘users‘ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(320), unique=True) password = db.Column(db.String(32), nullable=False) def __repr__(self): return ‘<User %r>‘ % self.username class Admin(db.Model): __tablename__ = ‘admins‘ id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(320), unique=True) password = db.Column(db.String(32), nullable=False) def __repr__(self): return ‘<User %r>‘ % self.username
3.创建create_db.py,表结构设计完成后执行python create_db.py即可完成表的创建,如下图
#app/create_db.py
from app import db db.create_all()
4.表已经创建完成了,接下来是我们的业务逻辑使用表的时候了
分别在user和admin蓝图中增加一个add用户的业务
#app/user.py
from flask import Blueprint, render_template, redirect,request from app import db from .models import User user = Blueprint(‘user‘,__name__) @user.route(‘/index‘) def index(): return render_template(‘user/index.html‘) @user.route(‘/add/‘,methods=[‘GET‘,‘POST‘]) def add(): if request.method == ‘POST‘: p_user = request.form.get(‘username‘,None) p_email = request.form.get(‘email‘,None) p_password = request.form.get(‘password‘,None) if not p_user or not p_email or not p_password: return ‘input error‘ newobj = User(username=p_user, email=p_email, password=p_password) db.session.add(newobj) db.session.commit() users = User.query.all() return render_template(‘user/add.html‘,users=users) users = User.query.all() return render_template(‘user/add.html‘,users=users) @user.route(‘/show‘) def show(): return ‘user_show‘
#app/admin.py
#admin.py from flask import Blueprint,render_template, request, redirect from app import db from .models import Admin admin = Blueprint(‘admin‘,__name__) @admin.route(‘/index‘) def index(): return render_template(‘admin/index.html‘) @admin.route(‘/add/‘,methods=[‘POST‘,‘GET‘]) def add(): if request.method == ‘POST‘: p_admin = request.form.get(‘username‘,None) p_email = request.form.get(‘email‘,None) p_password = request.form.get(‘password‘,None) if not p_admin or not p_email or not p_password: return ‘input error‘ newobj = Admin(username=p_admin, email=p_email, password=p_password) db.session.add(newobj) db.session.commit() admins = Admin.query.all() return render_template(‘admin/add.html‘,admins=admins) admins = Admin.query.all() return render_template(‘admin/add.html‘,admins=admins) @admin.route(‘/show‘) def show(): return ‘admin_show‘
#app/templates/admin/add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AdminsAdd</title> </head> <body> <form action="/admin/add/" method="POST"> user:<input type="text" name="username" /> email:<input type="text" name="email" /> pwd:<input type="password" name="password" /> <input type="submit" value="add" /> </form> {% if admins %} <table border="1px"> <tr> <th>UserName</th> <th>Email</th> </tr> {% for u in admins %} <tr> <td>{{u.username}}</td> <td>{{u.email}}</td> </tr> {% endfor %} </table> {% endif %} </body> </html>
#app/templates/user/add.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>UserAdd</title> </head> <body> <form action="/user/add/" method="POST"> user:<input type="text" name="username" /> email:<input type="text" name="email" /> pwd:<input type="password" name="password" /> <input type="submit" value="add" /> </form> {% if users %} <table border="1px"> <tr> <th>UserName</th> <th>Email</th> </tr> {% for u in users %} <tr> <td>{{u.username}}</td> <td>{{u.email}}</td> </tr> {% endfor %} </table> {% endif %} </body> </html>
#app/views.py
from app import app
from .admin import admin
from .user import user
app.register_blueprint(admin,url_prefix=‘/admin‘)
app.register_blueprint(user, url_prefix=‘/user‘)
#run.py
from app import app app.run()
到这里也就结束了,这样这个例子就结合了蓝图和flask-sqlalchemy.本例中只使用了db.session.add(),其它的还有db.session.delete()...
看一下效果:
localhost:5000/user/add
localhost:5000/admin/add
以上是关于python3.5+flask+mysql的主要内容,如果未能解决你的问题,请参考以下文章
Bad Gateway 502 - 在 centos 7 上使用 gunicorn nginx 部署 Flask (python 3.5.2)