Flask request 屬性詳解
一、關於request
在Flask的官方文檔中是這樣介紹request的:對於 Web 應用,與客戶端發送給服務器的數據交互至關重要。在 Flask 中由全局的 request 對象來提供這些信息。
從Flask模塊導入request:from flask import request
request的屬性:下面是request可使用的屬性,其中黑體是比較常用的。
二、常用方法的使用
#代碼示例,僅僅是為了測試request的屬性值 @app.route('/login', methods = ['GET','POST']) def login(): if request.method == 'POST': if request.form['username'] == request.form['password']: return 'TRUE' else: #當form中的兩個字段內容不一致時,返回我們所需要的測試信息 return str(request.headers) #需要替換的部分 else: return render_template('login.html')
1、method:請求的方法
return request.method #POST
2、form:返回form的內容
return json.dumps(request.form) #{"username": "123", "password": "1234"}
3、args和values:args返回請求中的參數,values返回請求中的參數和form
return json.dumps(request.args) #url:http://192.168.1.183:5000/login?a=1&b=2、返回值:{"a": "1", "b": "2"} print(request.args['a']) #輸出:1 return str(request.values) #CombinedMultiDict([ImmutableMultiDict([('a', '1'), ('b', '2')]), ImmutableMultiDict([('username', '123'), ('password', '1234')])])
4、cookies:cookies信息
return str(request.headers) #headers信息 request.headers.get('User-Agent') #獲取User-Agent信息
6、url、path、script_root、base_url、url_root:看結果比較直觀
return 'url: %s , script_root: %s , path: %s , base_url: %s , url_root : %s' % (request.url,request.script_root, request.path,request.base_url,request.url_root) ''' url: http://192.168.1.183:5000/testrequest?a&b , script_root: , path: /testrequest , base_url: http://192.168.1.183:5000/testrequest , url_root : http://192.168.1.183:5000/ '''
7、date、files:date是請求的數據,files隨請求上傳的文件
@app.route('/upload',methods=['GET','POST']) def upload(): if request.method == 'POST': f = request.files['file'] filename = secure_filename(f.filename) #f.save(os.path.join('app/static',filename)) f.save('app/static/'+str(filename)) return 'ok' else: return render_template('upload.html') #html <!DOCTYPE html> <html> <body> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /><br /> <input type="submit" value="Upload" /> </form> </body> </html>