加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
sqlLibrary.py 8.19 KB
一键复制 编辑 原始数据 按行查看 历史
Mercury 提交于 2021-04-19 20:33 . archive 1.0
from flask import (Flask, flash, make_response, redirect, render_template,
request, url_for)
from util.sqlQuery import *
app = Flask(__name__)
app.secret_key = 'Mercury' # flash需要密钥
# 实现简单的登录逻辑:GET + POST,用户名和密码都要填写,且要匹配
@app.route('/favicon.ico')
def favicon():
return app.send_static_file('favicon.ico')
@app.route('/', methods=['GET', 'POST']) # 同时需要GET和POST路由方式
def index():
if request.method == 'POST':
username = request.form.get('username') # 从前端name=username获取username
password = request.form.get('password')
print('username =', username)
print('password =', password)
if not all([username, password]):
print('Empty input detected') # 参数不完整
flash('用户名或密码为空!') # flash可以给template传递消息
else:
identity = checkLoginQuery(username, password)
if identity is None: # 用户名与密码不匹配,登录失败
print('Username and password do not match')
flash('用户名或密码错误!')
else:
response = make_response(redirect(url_for('home'))) # 跳转
# 必须用cookie存储用户名和密码
response.set_cookie('userId', username, max_age=60*60*24*7)
response.set_cookie('password', password, max_age=60*60*24*7)
return response
return render_template('index.html')
@app.route('/home')
def home():
userId = request.cookies.get('userId')
print("current userId =", userId)
if userId is None:
welcomePrompt = '初始化中,请稍后……'
else:
welcomePrompt = '欢迎您,' + userId
flash(welcomePrompt) # flash可以给template传递消息
if userId is None: # cookie失效
return make_response(redirect(url_for('index')))
return render_template('home.html')
@app.route('/error?error=<error>')
def error(error):
return render_template('error.html', error=error)
@app.route('/result?prompt=<prompt>')
def result(prompt, result=''):
return render_template('result.html', prompt=prompt, result=result)
@app.route('/addSingle', methods=['POST'])
def addSingle():
print('In addSingle')
userId = request.cookies.get('userId')
if checkPrivilege(userId) is False:
return make_response(redirect(url_for('error', error='您无权限进行图书入库操作')))
bookData = {}
attributes = ['id', 'type', 'title', 'press',
'publishYear', 'author', 'price', 'totNum']
for attribute in attributes:
bookData[attribute] = request.form[attribute] # 从表单中获取信息
if not request.form[attribute]:
return make_response(redirect(url_for('error', error='图书入库操作有字段为空')))
prompt = addSingleQuery(bookData) # 分为两种可能:新书——单本添加、旧书——单本添加
return render_template('result.html', prompt=prompt)
@app.route('/addMultiple', methods=['POST'])
def addMultiple():
userId = request.cookies.get('userId')
if checkPrivilege(userId) is False:
return make_response(redirect(url_for('error', error="您无权限进行图书入库操作")))
raw = request.form['raw'] # 后端处理
if not raw:
return make_response(redirect(url_for('error', error='批量添加数据为空')))
print(raw)
# e.g.
# raw = '''11,政治,他改变了中国,上海译文出版社,2005,Robert,48,2
# 22,数学,高等数学,高等教育出版社,2002,马保国,42,3
# 33,计算机,算法导论,机械工业出版社,2000,Thomas & Ronald,999,1
# 44,文学,杀死一只知更鸟,译林出版社,2015,哈珀,55,4
# '''
bookList = raw.strip().split('\n') # strip()去除行首行尾的空格和\n
keyList = ['id', 'type', 'title', 'press',
'publishYear', 'author', 'price', 'totNum']
for book in bookList:
valList = book.split(',')
bookData = dict(zip(keyList, valList))
addSingleQuery(bookData)
return render_template('result.html', prompt='批量添加')
@app.route('/addUser', methods=['POST'])
def addUser():
userId = request.cookies.get('userId')
if checkPrivilege(userId) is False:
return make_response(redirect(url_for('error', error="您无权限进行添加用户操作")))
userData = {}
attributes = ['id', 'name']
for attribute in attributes:
userData[attribute] = request.form[attribute]
if not request.form[attribute]:
return make_response(redirect(url_for('error', error='用户添加操作有字段为空')))
flag = addUserQuery(userData)
if flag is False:
return make_response(redirect(url_for('error', error="该学工号对应借书卡已存在")))
else:
return render_template('result.html', prompt='添加用户')
@app.route('/delUser', methods=['POST'])
def delUser():
userId = request.cookies.get('userId')
if checkPrivilege(userId) is False:
return make_response(redirect(url_for('error', error="您无权限进行删除用户操作")))
if not request.form['id']:
return make_response(redirect(url_for('error', error='学工号字段为空')))
userData = {'id': request.form['id']}
flag = delUserQuery(userData)
if flag is False:
return make_response(redirect(url_for('error', error="该学工号对应借书卡不存在,无须删除")))
else:
return render_template('result.html', prompt='删除用户')
@app.route('/findBook', methods=['POST'])
def findBook():
query = {}
attributes = ['type', 'title', 'press',
'publishYearL', 'publishYearR', 'author', 'priceL', 'priceR']
# <!-- 类别,书名,出版社,年份,作者,价格 -->
for attribute in attributes:
query[attribute] = request.form[attribute]
result = findBooksQuery(query)
return render_template('findBookResult.html', result=result)
@app.route('/borrowBook', methods=['POST'])
def borrowBook():
userId = request.cookies.get('userId')
print("Borrowing book. Current userId =", userId)
if userId is None: # cookie失效
return make_response(redirect(url_for('index')))
bookData = {}
if not request.form['id']:
return make_response(redirect(url_for('error', error='书号字段为空')))
bookData['id'] = request.form['id']
flag, prompt = borrowBookQuery(userId, bookData)
if flag: # 借出成功
return render_template("result.html", prompt=prompt)
else:
return make_response(redirect(url_for('error', error=prompt)))
@app.route('/returnBook', methods=['POST'])
def returnBook():
userId = request.cookies.get('userId')
print("Returning book. Current userId =", userId)
if userId is None: # cookie失效
return make_response(redirect(url_for('index')))
bookData = {}
if not request.form['id']:
return make_response(redirect(url_for('error', error='书号字段为空')))
bookData['id'] = request.form['id']
flag, prompt = returnBookQuery(userId, bookData)
if flag: # 归还成功
return render_template("result.html", prompt=prompt)
else:
return make_response(redirect(url_for('error', error=prompt)))
@app.route('/historyRecords', methods=['POST'])
def historyRecords():
targetId = ''
if not request.form['id']: # 未给出,默认查询自己
targetId = request.cookies.get('userId')
print("Self checking history Records. Current userId =", targetId)
if targetId is None: # cookie失效
return make_response(redirect(url_for('index')))
else:
targetId = request.form['id']
print("Checking history Records. targetId =", targetId)
flag, result = historyRecordsQuery(targetId)
if flag: # 查询成功
return render_template("historyRecordResult.html", result=result)
else:
return make_response(redirect(url_for('error', error=result)))
@app.errorhandler(404) # 自定义404 handler
def pageNotFound(err): # 必须指定一个参数
return render_template("404.html")
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化