from flask import Flask, render_template, flash, request, abort
app = Flask(__name__)
app.secret_key = '345'
# Flask会使用secret_key对消息进行加密
'''
消息提示
抛出异常
异常处理
flask提供了消息闪现机制
'''
@app.route('/')
def hello_world():
flash('消息闪现')
return render_template('index_flash.html')
@app.route('/login', methods=['POST'])
def login():
form = request.form
username = form.get('username')
password = form.get('password')
print(type(username))
print(type(password))
if not username:
flash('请输入用户名')
return render_template('index_flash.html')
if not password:
flash('请输入密码')
return render_template('index_flash.html')
if str(username) == '123' and str(password) == '123':
flash('登陆成功')
return render_template('index_flash.html')
else:
flash('username or password id wrong')
return render_template('index_flash.html')
@app.errorhandler(404)
def not_found(e): # 此处有个参数e,不然会报错
return render_template('404.html')
@app.route('/users/<user_id>')
def users(user_id):
if int(user_id) == 1:
return render_template('user.html')
else:
abort(404) # 这里直接抛出404异常
if __name__ == '__main__':
app.run()
简单了解了下能从request中获得什么东西
request.method # 请求方式
request.form # 存放FormData中的数据 to_dict 序列化成字典
request.args # 获取URL中的数据 to_dict 序列化成字典
request.url # 访问的完整路径
request.path # 路由地址
request.host # 主机地址
request.values # 获取 FormData and URL中的数据 不要用to_dict
request.json # 如果提交时请求头中的Content-Type:application/json 字典操作
request.data # 如果提交时请求头中的Content-Type 无法被识别 将请求体中的原始数据存放 byte
request.cookies # 获取Cookie中的数据
request.headers # 获取请求头
request.files # 序列化文件存储 save()