Flask -- 请求、上传文件、Cookies
请求对象
from flask import request request.method #值为form表单提交的method 'POST'、 'GET'等 #如果值为'POST'或'PUT',则可以通过reques.form['xxx']来访问表单数据,'xxx'来自<input name='xxx'>
上传文件
impor os from flask import Flask, render_template, request, url_for, redirect from werzegug import sercure_filename app = Flask(__name__) UPLOAD_FOLDER = 'C:\User\Zoro\Uploads' #服务器上的任意目录 '/var/www/uploads' ALLOWED_EXTENSIONS = set(['txt', 'jpg', 'png', 'jpeg', 'gif', 'pdf']) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST' : file = request.files['file'] if file and allowed_file(file.filename): filename = secure_filename(file) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return redirect(url_for('uploaded_file', filename=filename)) #重定向到uploaded_file函数 return ''' <!doctype html> <form action="" method=post enctype=multipart/from-data> <input type=file name=file> <input type=submit value=Upload> </form> ''' @app.route('/upload/<filename>') def uploaded_file(filename): return render_template('upload_ok.html', filename=filename)
Cookies
你可以通过 cookies 属性来访问 Cookies,用响应对象的 set_cookie 方法来设置 Cookies。请求对象的 cookies 属性是一个内容为客户端提交的所有 Cookies 的字典
#读取 cookies: from flask import request @app.route('/') def index(): username = request.cookies.get('username') # use cookies.get(key) instead of cookies[key] to not get a # KeyError if the cookie is missing. #存储cookies from flask import make_response @app.route('/') def index(): resp = make_response(render_template(...)) resp.set_cookie('username', 'the username') return resp
可注意到的是,Cookies 是设置在响应对象上的。由于通常视图函数只是返回字符串,之后 Flask 将字符串转换为响应对象。如果你要显式地转换,你可以使用 make_response()函数然后再进行修改。
KEEP LEARNING!