• Flask


    图书管理

    from flask import *
    from flask_sqlalchemy import SQLAlchemy
    # 多条件查询,and_等于where id=1 and name='张飞'
    # 多条件查询,or_等于where id=1 and name='张飞'
    from sqlalchemy import and_,or_
    # 导入表单 FlaskForm祖宗级别的基类
    from flask_wtf import FlaskForm
    # 表单中到文本框,按钮,下拉框,下拉菜单等
    from wtforms import StringField,SubmitField
    # 表单非空验证,例如:用户名不能为空
    from wtforms.validators import DataRequired

    # import pymysql
    # pymysql.install_as_MySQLdb()

    app=Flask(__name__)
    #设置连接数据
    app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:@127.0.0.1:3306/bookmanager'
    # 忽略警告信息
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
    # 密钥
    app.config['SECRET_KEY']='111'
    db=SQLAlchemy(app)


    # create table author{
    # id int primary_key auto_increment,
    # name varchar(50) not null
    # }
    #
    # create table books{
    # id int primary key auto_increment,
    # name varchar(50) not null,
    # author_id int foreign key references(author_id)
    # }
    # 作者:xxxx 非空
    # 书籍:xxxx 非空
    # 提交按钮
    # 用类建表
    class MyForm(FlaskForm):
    author_name=StringField('作者:',validators=[DataRequired()])
    book_name=StringField('书籍:',validators=[DataRequired()])
    btn_submit=SubmitField('添加')

    # 作者表
    class Author(db.Model):
    __tablename__='author'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(50),unique=True,nullable=False)
    books=db.relationship('Books',backref='author',lazy='dynamic')

    # 书籍表
    class Books(db.Model):
    __tablename__ = 'books'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50),unique=True,nullable=False)
    author_id=db.Column(db.Integer,db.ForeignKey('author.id'))

    """增"""
    @app.route('/add')
    def add():
    # 添加数据,实例化三个对象
    a1=Author(name='刘备')
    a2=Author(name='关羽')
    a3=Author(name='张飞')
    # 给服务器添加多条数据
    db.session.add_all([a1,a2,a3])
    # 提交会话
    db.session.commit()

    b1=Books(name='红楼梦',author_id=a3.id)
    b2=Books(name='西游记',author_id=a1.id)
    b3=Books(name='水浒传',author_id=a2.id)
    b4=Books(name='三国志',author_id=a1.id)
    b5=Books(name='魂斗罗',author_id=a1.id)
    b6=Books(name='超级玛丽',author_id=a2.id)
    db.session.add_all([b1,b2,b3,b4,b5,b6])
    db.session.commit()
    return 'ok'

    """查"""
    @app.route('/',methods=['GET','POST'])
    def index():
    f=MyForm()
    # 添加作者 书籍
    if request.method=='POST':
    a_name=f.author_name.data
    b_name=f.book_name.data
    author=Author.query.filter(Author.name==a_name).first()
    if author:
    if b_name in [item.name for item in author.books]:
    flash('此作者下存在相同书籍')
    else:
    b=Books(name=b_name,author_id=author.id)
    db.session.add(b)
    db.session.commit()
    else:
    a=Author(name=a_name)
    db.session.add(a)
    db.session.commit()

    b=Books(name=b_name,author_id=a.id)
    db.session.add(b)
    db.session.commit()
    # 查询author表中所有数据
    a_list = Author.query.all()
    return render_template('views.html',a_list=a_list,f=f)

    @app.route('/delbook/<int:bookid>')
    def delete_book(bookid):
    # 查
    b=Books.query.filter(Books.id==bookid).first()
    print(b.name)
    # 删
    if b:
    db.session.delete(b)
    db.session.commit()
    else:
    flash('数据不存在')
    return redirect(url_for('index'))

    @app.route('/delauthor/<int:authorid>')
    def delete_author(authorid):
    a=Author.query.filter(Author.id==authorid).first()
    if a:
    db.session.delete(a)
    db.session.commit()
    else:
    flash('书籍不存在')
    return redirect(url_for('index'))

    if __name__ == '__main__':
    # 自动删除所有表格
    # db.drop_all()
    # 自动创建表格
    # db.create_all()
    app.run(debug=True)


    多对多
    #多对多
    from flask import *

    from flask_sqlalchemy import SQLAlchemy

    app=Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:@127.0.0.1:3306/test'
    db=SQLAlchemy(app)

    # 学生表
    class Student(db.Model):
    __tablename__='student'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)
    # 1.course存在关系的表格类名;
    # 2.secondary='table_s_c'指向多对多关联表table_s_c
    # 3.backref='students'科目表进行反向查找使用(将students定义为course类的一个属性)
    courses=db.relationship('Course',secondary='table_s_c',backref='students',lazy='dynamic')

    # 课程表
    class Course(db.Model):
    __tablename__ = 'course'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=False)

    # 学生课程关联表
    table_s_c=db.Table(
    'table_s_c',
    db.Column('s_id',db.ForeignKey('student.id')),#学生表外键
    db.Column('c_id',db.ForeignKey('course.id'))#课程表外键
    )

    #添加数据
    @app.route('/add')
    def add():
    s1=Student(name='张三')
    s2=Student(name='李四')
    s3=Student(name='王五')

    c1=Course(name='数学')
    c2=Course(name='语文')
    c3=Course(name='化学')

    s1.courses=[c1,c2,c3]
    s3.courses=[c1,c2]
    s3.courses=[c2,c3]
    db.session.add_all([s1,s2,s3,c1,c2,c3])
    db.session.commit()
    return 'ok'

    # 打印数据
    @app.route('/')
    def index():
    # s=Student.query.all() #查找所有学生
    # for i in s: #遍历每个学生
    # print(i.name) #打印学生姓名
    # for j in i.courses: #遍历每个学生所学的课程
    # print(j.name) #打印课程名称

    c=Course.query.all() #查找所有的课程
    for i in c: #遍历每个课程
    print(i.name) #打印课程名称
    for j in i.student: #遍历每门课程对应的学生(反向查找对应backref)
    print(j.name) #打印学生名称

    return 'ok'

    if __name__ == '__main__':
    db.create_all()
    app.run()


    数据库迁移
    from flask import Flask
    from flask_script import Manager
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate,MigrateCommand


    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:mysql@localhost:3306/hehehe'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    manager = Manager(app)
    db = SQLAlchemy(app)
    migrate = Migrate(app, db)
    manager.add_command('db',MigrateCommand)


    class Book(db.Model):
    id = db.Column(db.String,primary_key=True)
    name = db.Column(db.String(50),unique=True, nullable=False)
    authorid = db.Column(db.Integer)


    @app.route('/')
    def index():
    return 'hehehehe'

    if __name__ == '__main__':
    manager.run()

    数据库一对多
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    import pymysql
    pymysql.install_as_MySQLdb()
    app=Flask(__name__)

    app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:@127.0.0.1:3306/test'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True

    db=SQLAlchemy(app)
    # 所有的类都记成db.model
    class Role(db.Model):
    # 定义表名
    __tablename__='roles'
    # 定义列对象
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),unique=True)
    us=db.relationship('User',backref='role',lazy=dynamic)
    #
    # #repr()方法显示一个可读字符串
    # def __repr__(self):
    # return 'Role:%s'% self.name

    class User(db.Model):
    __tablename__='users'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),unique=True,index=True)
    email=db.Column(db.String(64),unique=True)
    password=db.Column(db.String(64))
    role_id=db.Column(db.Integer,db.ForeignKey('roles.id'))
    # def __repr__(self):
    # return 'User:%s'%self.name


    @app.route('/')
    def index():
    return 'hello'
    if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    r1=Role()
    r1.name='zhangsan'

    r2=Role()
    r2.name='lisi'

    db.session.add_all([r1,r2])
    db.session.commit()
    # db.session.execute("")
    app.run()

    购物车
    from flask import * # 导入flask类

    from course import newsql

    app=Flask(__name__) #实例化对象
    app.secret_key='111' #设置秘密钥匙
    app.config['JSON_AS_ASCII']=False #防止中文乱码

    # 购物车登录页面
    @app.route('/',methods=['GET','POST']) #路由方法
    def index(): #定义购物车函数
    if request.method=='POST': #判断获取请求方法
    if request.form.get('btnregister') is not None: #如果注册不为空
    return redirect(url_for('register')) #返回重定向注册页面
    else: #否则
    username=request.form.get('username') #客户端获取到的用户名 密码一致
    password=request.form.get('password')
    #查询用户名 密码
    user = newsql.get('select id from customer where username="{}" and password="{}"' .format(username, password))
    print(user)
    if len(user)>0: #判断用户名 密码大于零
    session['userId']=user[0][0] #把用户名写入session
    print('登录成功') #则登录成功
    return redirect(url_for('goods')) #返回重定向商品页面
    else:
    flash('登陆失败') #如果用户名密码有一个不满足条件登录失败
    if username=='' or password=='': #如果用户名 密码有一个为空
    print('请输入用户名,密码') #请输入用户名 密码
    return render_template('form1.html') #返回模板登录

    # 商品页面
    @app.route('/goods',methods=['GET','POST'])
    def goods():
    if request.form.get('jin') is not None:
    return redirect(url_for('cart'))
    if session.get('userId') is None: #如果服务端获取到的用户名为空
    return redirect(url_for('index')) #返回重定向登陆页面
    else:
    g_list = newsql.get('select * from goods') #定义一个变量获取商品信息
    p_list=[] #定义一个空列表
    for i in g_list: #循环遍历商品信息
    item={} #定义一个空字典
    item['id']=i[0]
    item['name']=i[1]
    item['price']=str(i[2])
    item['inventory']=i[3]
    p_list.append(item) #列表添加到字典里
    return render_template('lianxi.html',p_good=p_list) #返回商品列表模板
    #注册页面
    @app.route('/register',methods=['GET','POST'])
    def register():
    if request.method=='POST':
    if request.form.get('btnregister') is not None: #注册不为空
    username=request.form.get('username') #客户端获取到的用户名 密码 确认密码 手机号一致
    password=request.form.get('password')
    repassword=request.form.get('repassword')
    tel=request.form.get('tel')
    if not all([username,password,repassword,tel]): #如果用户名 密码 确认密码 手机号有一个为空
    flash('信息不全') #闪现 信息不全
    elif password==repassword: #密码和确认密码一致
    tag=True
    if tag:
    return redirect(url_for('index')) #登陆
    return render_template('register.html') #否则注册

    # 添加购物车
    @app.route('/addgoods',methods=['GET','post'])
    def addgoods():
    item=request.json #获取axios传递的post信息
    id=item['id'] #生成新添加到商品的数据结构
    uid=session.get('userId') #购物车id等于服务端获取到的用户名id
    print(id,uid)
    cart_msg = newsql.get('select * from cart where uid={} and gid={}'.format(uid, id)) #查询购物车的用户id 和商品id


    if len(cart_msg)>0: #如果所添加的商品存在于购物车,则购物车中数量+1
    #则购物车中数量+1
    db_result_count = newsql.get1('update cart set count=count+1 where uid={} and gid={}'.format(uid, id))
    else: #如果购物车不为空,则判断新增商品是否已经存在
    # 将商品信息添加到购物车列表中
    db_result_count = newsql.get1('insert into cart values(0,{},{},1) '.format(uid, int(id)))
    # if db_result_count>0:
    # msg['status']='200'
    # msg['message']='添加购物车成功'
    # else:
    # msg['status']='650'
    # msg['message']='添加购物车失败'
    return jsonify(item)

    #购物车展示
    @app.route('/cart',methods=['GET','POST'])
    def cart():
    #三张表链表查询需要的数据
    ret = newsql.get('select uid,customer.username,goods.id,goods.name,price,count from customer,goods,cart where cart.gid=goods.id and cart.uid=customer.id')
    alist=[]
    for i in ret:
    set={}
    set['uid']=i[0]
    set['cname']=i[1]
    set['gid']=i[2]
    set['gname']=i[3]
    set['price']=str(i[4])
    set['count']=i[5]
    alist.append(set)
    return render_template('cart.html',pp_good=alist) #返回购物车模板

    # 移除购物车
    @app.route('/delgoods',methods=['GET','POST'])
    def delgoods():
    if request.json is not None:
    gid=request.json['gid']
    uid=request.json['uid']
    newsql.get1('delete from cart where gid={} and uid={} '.format(gid, uid))
    return redirect(url_for('cart'))
    # print(request.json)
    return jsonify(request.json)

    if __name__ == '__main__':
    app.run(debug=True)


    期中题

    from flask import * # 导入flask类

    import new

    app=Flask(__name__) #实例化对象
    app.secret_key='111' #设置秘密钥匙
    app.config['JSON_AS_ASCII']=False #防止中文乱码

    # 添加商品类别
    @app.route('/',methods=['GET','POST'])
    def index():
    if request.method=='POST':
    if request.form.get('aaa') is not None:
    return redirect(url_for('leibie'))
    if request.form.get('bbb') is not None:
    return redirect(url_for('addgoods'))
    if request.form.get('ccc') is not None:
    return redirect(url_for('show'))
    return render_template('index.html')

    @app.route('/leibie',methods=['GET','POST']) #路由方法
    def leibie(): #定义购物车函数
    if request.method=='POST': #判断获取请求方法
    if request.form.get('leibie') is not None: #如果注册不为空
    flash('信息为空') #返回重定向注册页面
    else: #否则
    name=request.form.get('name') #客户端获取到的用户名 密码一致
    new.get('insert into cate(name) values("{}")'.format(name))
    return render_template('leibie.html') #查询用户名 密码

    # 添加商品
    @app.route('/addgoods',methods=['GET','POST'])
    def addgoods():
    if request.method=='POST':
    print(111)
    if request.form.get('btn') is not None:
    name=request.form.get('name')
    price=request.form.get('price')
    lx=request.form.get('lx')
    print(lx)
    a=new.get('insert into good values("{}",{},"{}")'.format(name,price,lx))
    print(a)
    return redirect(url_for('show'))
    return render_template('addgoods.html')

    #购物车展示
    @app.route('/show',methods=['GET','POST'])
    def show():
    ret = new.get('select * from good')
    alist=[]
    for i in ret:
    set={}
    set['name']=i[0]
    set['price']=i[1]
    set['lx']=i[2]
    alist.append(set)
    return render_template('show.html',p_good=alist) #返回商品模板
    if __name__ == '__main__':
    app.run(debug=True)

    from flask import *
    import new
    from flask_sqlalchemy import SQLAlchemy
    # 多条件查询,and_等于where id=1 and name='张飞'
    # 多条件查询,or_等于where id=1 and name='张飞'
    from sqlalchemy import and_,or_
    # 导入表单 FlaskForm祖宗级别的基类
    from flask_wtf import FlaskForm
    # 表单中到文本框,按钮,下拉框,下拉菜单等
    from wtforms import StringField,SubmitField
    # 表单非空验证,例如:用户名不能为空
    from wtforms.validators import DataRequired

    # import pymysql
    # pymysql.install_as_MySQLdb()

    app=Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://root:@127.0.0.1:3306/qz'
    # 忽略警告信息
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
    # 密钥
    app.config['SECRET_KEY']='111'
    db=SQLAlchemy(app)

    # 服装
    @app.route('/',methods=['GET','POST'])
    def index():
    if request.method=='POST':
    if request.form.get('aaa') is not None:
    return redirect(url_for('goods'))
    return render_template('clothes.html')


    # 服装表
    class Clothes(db.Model):
    __tablename__='clothes'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(50),nullable=False)
    goods=db.relationship('Goods',backref='clothes',lazy='dynamic')

    # 商品表
    class Goods(db.Model):
    __tablename__ = 'goods'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50),nullable=False)
    clothes_id=db.Column(db.Integer,db.ForeignKey('clothes.id'))

    # 服装
    @app.route('/goods',methods=['GET','POST'])
    def goods():
    g_list = new.get('select * from goods') # 定义一个变量获取商品信息
    p_list = [] # 定义一个空列表
    for i in g_list: # 循环遍历商品信息
    item = {} # 定义一个空字典
    item['id'] = i[0]
    item['name'] = i[1]
    item['clothes_id'] = i[2]
    p_list.append(item)
    if request.form.get('aaa') is not None:
    return redirect(url_for('xiugai'))
    if request.form.get('bbb') is not None:
    return redirect(url_for('shanchu'))
    return render_template('goods1.html',p_good=p_list)


    # 改
    @app.route('/xiugai',methods=['GET','POST'])
    def xiugai():
    a=Clothes.query.filter(or_(Clothes.name=='鞋',id==3)).first()
    a.name='跑鞋'
    db.session.commit()

    return 'ok'

    #删
    @app.route('/shanchu', methods=['GET', 'POST'])
    def shanchu():
    a=Clothes.query.filter(or_(Clothes.name=='裤子',Clothes.id==2)).first()
    db.session.delete(a)
    db.session.commit()
    return 'ok1'


    """增"""
    @app.route('/add',methods=['GET','POST'])
    def add():
    # 添加数据,实例化三个对象
    a1=Clothes(name='上衣')
    a2=Clothes(name='裤子')
    a3=Clothes(name='鞋')
    # 给服务器添加多条数据
    db.session.add_all([a1,a2,a3])
    # 提交会话
    db.session.commit()

    b1=Goods(name='短袖',clothes_id=a3.id)
    b2=Goods(name='衬衣',clothes_id=a1.id)
    b3=Goods(name='外套',clothes_id=a2.id)
    b4=Goods(name='牛仔裤',clothes_id=a1.id)
    b5=Goods(name='运动裤',clothes_id=a1.id)
    b6=Goods(name='新百伦鞋',clothes_id=a2.id)
    db.session.add_all([b1,b2,b3,b4,b5,b6])
    db.session.commit()
    return 'ok'


    if __name__ == '__main__':
    # 自动删除所有表格
    # db.drop_all()
    # 自动创建表格
    # db.create_all()
    app.run(debug=True)

    蓝图
    """蓝图"""
    # 导入蓝图的文件名
    from flask import Flask
    from view.blue import *
    # from文件夹.文件名 import 实例名
    from view.Y import *

    # 实例化对象。
    app=Flask(__name__)
    # 注册蓝图,将blue(为子例化的对象)导入到app中。生成到路由地址为 http"//127.0.0.1:5000/Blue/XXXXX
    app.register_blueprint(blue,url_prefix='/blue')
    # 注册蓝图,将yellow(为子例化的对象)导入到app中。生成到路由地址为 http"//127.0.0.1:5000/Blue/XXXXX
    app.register_blueprint(yellow,url_prefix='/yellow')

    @app.route('/')
    def index():
    return 'hello'

    if __name__ == '__main__':
    app.run()


    from flask import Blueprint
    # from view.bule import bule

    blue=Blueprint(name='blue',import_name=__name__)
    @blue.route('/A')
    def showA():
    return 'hello1'

    @blue.route('/B')
    def showB():
    return 'hello2'

    @blue.route('/C')
    def showC():
    return 'hello3'


    from flask import Blueprint

    yellow=Blueprint(name='yellow',import_name=__name__)
    @yellow.route('/a')
    def yellow1():
    return 'yellow1'


    @yellow.route('/b')
    def yellow2():
    return 'yellow2'

  • 相关阅读:
    C中的system函数
    结构体数组
    转载--C++的反思
    oracle临时表空间
    oracle行转列,列转行
    oracle查询表结构语句
    实例化内部类
    Java非静态内部类为什么不能有静态成员
    oracle显示转换字段类型cast()函数
    linux中vim常用命令
  • 原文地址:https://www.cnblogs.com/wyf2019/p/10959474.html
Copyright © 2020-2023  润新知