赞
踩
①定义:它是对sqlalchemy进行的简单封装,使得在flask中使用sqlalchemy的时候更加的方便
②安装:通过pipenv shell进入虚拟环境然后pip install flask-sqlalchemy安装
③使用:数据库初始化、创建ORM类、映射模型到数据库、对映射的数据进行CRUD操作
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
USERNAME = 'root'
PASSWORD = 'root'
HOSTNAME = '127.0.0.1'
PORT = '3306'
DATABASE = 'demo1107'
DB_URL = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL # 相当于以前的engine=create_engine(DB_URL)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 解决警告,将它设为false让他支持警告
db = SQLAlchemy(app) # 相当于以前的Base=declarative_base(bind=engine)
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
# def __str__(self):
# return 'User:name(%s)'%self.name
def __repr__(self): # 相当于str的升级版
return 'User:name(%s)' % self.name
class Article(db.Model):
__tablename__ = 'article' # 如果不写表名,映射的表会以模型名字的小写来定义表名
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(50))
uid = db.Column(db.Integer, db.ForeignKey('users.id'))
author = db.relationship('User', backref='articles')
db.drop_all() # 相当于Base.metadata.drop_all()
db.create_all() # 相当于Base.metadata.create_all()
# 添加数据
user = User(name='wchao')
article = Article(title='python')
article.author = user
db.session.add(article)
db.session.commit()
# 查询数据 以前是session.query().all()
user = User.query.all()
users = User.query.order_by(User.id.desc()).all() # 根据id进行排序
print(user)
# 删除数据
user = User.query.filter(User.name == 'wchao').first()
db.session.delete(user)
db.session.commit()
@app.route('/')
def index():
return '首页'
if __name__ == '__main__':
app.run(debug=True)
①作用:可以通过cmd客户端命令来来操作flask,通过pip install flask-script安装,通常把脚本命令文件放到manage.py文件中,再终端通过python manage.py hello就可以执行
from flask_script import Manager
from flask_add_admin.flask_script_demo import app, AdminUser ,db
manage = Manager(app)
@manage.option('-u','--name',dest='name')
@manage.option('-e','--email',dest='email')
def add_user(name,email):
user = AdminUser(name=name,email=email)
db.session.add(user)
db.session.commit()
if __name__ == '__main__':
manage.run()
再开发环境中想要修改数据库,可以通过修改ORM的模型,这时候就可以使用Flask-Migrate,它是基于Alembic的一个封装,并且集成到了Flask中,安装:pip install flask-migrate
为了避免相互引用要创建第三个文件作为介质来避免报错
flask-wtf是简化了wtforms操作的一个第三方库,主要功能是验证用户提交数据的合法性以及渲染模板,安装pip install flask-wtf ,想要将form表单的数据渲染到前端中,直接在rendom_template(‘index.html’,form=form)就可以在form中引用form.属性去使用渲染功能
①写一个表单验证模块
from wtforms import Form, StringField, validators
from wtforms.validators import Length,Regexp,EqualTo
class RegistForm(Form):
username = StringField(validators=[Length(min=3,max=10,message='用户名长度不正确')])
password = StringField(validators=[Length(min=3,max=10)])
password_repate = StringField(validators=[Length(min=3,max=10),EqualTo('password',message='两次密码不一致')])
②写一个主函数入口引入表单验证模块
from flask import Flask,request,render_template
from day10.form_wtf_demo.forms import RegistForm
app = Flask(__name__)
@app.route('/')
def index():
return '首页'
@app.route('/regist',methods=['GET','POST'])
def demo():
if request.method=='GET':
return render_template('regist.html')
else:
# form = RegistForm(request.form)
# if form.validate():
# return 'success'
# else:
# print(form.errors)
# return 'false'
username = request.form.get('username')
password = request.form.get('password')
password_repate = request.form.get('password_repate')
if len(username)<3 or len(username)>10:
return '用户名长度不对'
if password != password_repate:
return '两次密码不一致'
else:
pass
if __name__ == '__main__':
app.run(debug=True)
③写一个模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
用户名:<input type="text" name="username">
密码:<input type="text" name="password">
确认密码:<input type="text" name="password_repate">
<input type="submit" value="注册">
</form>
</body>
</html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。