圖書管理html
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 DataRequiredmysql
# import pymysql
# pymysql.install_as_MySQLdb()ios
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)sql
# 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')json
# 書籍表
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'))flask
"""增"""
@app.route('/add')
def add():
# 添加數據,實例化三個對象
a1=Author(name='劉備')
a2=Author(name='關羽')
a3=Author(name='張飛')
# 給服務器添加多條數據
db.session.add_all([a1,a2,a3])
# 提交會話
db.session.commit()axios
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()session
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'