假设有两个类别的模块:admin和user模块
一、flask-sqlachemy的使用
1、使用建立mysql的连接
新建一个目录:app,以下操作全部在app目录下
a)新建config.py文件,写入以下内容
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:xxxxx@localhost:3306/test?charset=utf8' # 使用pymysql建立连接
SQLALCHEMY_TRACK_MODIFICATIONS = True
b)在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') # 完成app与配置文件的关联 db = SQLAlchemy(app) # 生成一个可以操作app数据库的SQLAlchemy实例db from app import models,views
2、创建model.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
from app import db
db.create_all()
表结构设计完成后执行python create_db.py即可完成表的创建
二、视图函数
1、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) # 增 obj = User(username=p_user, email=p_email, password=p_password) db.session.add(obj) db.session.commit() # 提交操作 # 删 obj = User(username=p_user, email=p_email, password=p_password) db.session.delete(obj) db.session.commit() # 提交操作 # 查(此种方法,不存在返回None) result = User.query.filter_by(username=p_user).first() result_list = User.query.all() # 改 User.query.filter_by(username=p_user).update({'username':'abc123'}) return render_template('user/add.html',users=users) else: users = User.query.all() return render_template('user/add.html',users=users)
2、admin.py
from flask import Blueprint admin = Blueprint('admin',__name__) @admin.route('/index') def index(): return "hello,world!"
3、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()
参考于:这里