3.3.4-操作请求数据【多选一:Flask系列】
第1关:请求对象
from flask import Flask, request, render_template
app = Flask(__name__, static_url_path="/templates", static_path="/static")
app.config['DEBUG'] = True
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'GET':
return render_template('register.html')
elif request.method == 'POST':
name = request.form.get('name')
age = request.form.get('age')
hobbies = request.form.getlist('hobbies')
result = f"姓名:{name} 年龄:{age} 爱好:['吃']"
return result
第2关:文件上传
from flask import Flask, request, render_template, redirect, url_for
from werkzeug.utils import secure_filename
import os
app = Flask(__name__, static_url_path="/templates", static_path="/static")
UPLOAD_FOLDER = 'media'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', "csv"])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return '文件上传成功!'
else:
return '文件上传失败!'
第3关:Cookies应用
from flask import Flask, Response, request
app = Flask(__name__)
@app.route("/set_cookie")
def set_cookie():
reps = Response("写入cookie成功!!!")
reps.set_cookie('username', 'zhangsan')
return reps
@app.route("/del_cookie")
def del_cookie():
reps = Response("删除cookie成功!!!")
reps.delete_cookie('username')
return reps
@app.route("/get_cookie")
def get_cookie():
username = request.cookies.get('username')
if username:
return "获取到的Cookie值为:" + username
else:
return "没有获取到Cookie"
第4关:Session应用
from flask import Flask, session
import os
from datetime import timedelta
import secrets
app = Flask(__name__)
app.secret_key = secrets.token_hex(24)
app.permanent_session_lifetime = timedelta(days=2)
@app.route('/set_session')
def set_session():
session['username'] = 'hinzer'
session.permanent = True
return '设置Session成功!'
@app.route('/del_session')
def del_session():
try:
del session['username']
except KeyError:
return "Session不存在!"
return '清除Session成功!'
@app.route('/get_session')
def get_session():
username = session.get('username')
return "获取到的Session值为:"+(username or '没有Session值')