当前位置:网站首页>Entry level use of flask
Entry level use of flask
2022-06-25 06:40:00 【Ten thousand miles' journey to】
Flash yes python The next lightweight web Service Framework , adopt Flash It can be built quickly api Servers and websites , In deep learning Flash The most commonly used is the deployment of models . Some coordination c++ dll Library call , For example, this library (python Customize by importing dll Realize the release of video memory _ A flash of hope to my blog -CSDN Blog ) Can achieve python The video memory under is released , It is perfect in engineering .
Bloggers here simply analyze Flash Experience in building stations , Such as url binding 、get Parameters to obtain 、 Upload files 、 Download files and so on .
Flask Installation :pip install Flask
1、 Basic use
The following code implements flask Basic use of ,app Both are flask Running objects of ,python Function by @app.route('url') Realization url Binding to functions , One python Functions can be bound to multiple url. function return Value , It is the display result of the browser client page .
from flask import Flask, render_template, request
from flask import jsonify, session, make_response, request,send_file
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
@app.route('/')
@app.route('/index')
@app.route('/index.html')
def index():
return request.host+"<br/>"+ request.url+" <br/>hello world"
if __name__ == '__main__':
#host=0.0.0.0 Indicates all that support this server ip Address
#port Refers to the port
#debug=True It refers to the output of debugging information
app.run(host="0.0.0.0",debug=True,port=14000)
2、html Templates (template) Use
Use template return html Content can greatly simplify server code , Achieve mvc The separation of ( Model m、 View v、 controller c). Here the model refers to the database model 、 View means html page 、 The controller refers to the back-end specific function code .flask You can put some python Variables are passed to the template , And then in html Dynamically generate content in . The details are as follows
@app.route('/get_template_html')
def template():
kwargs = {
"files": ["dir1", "dir2", "file1.txt", "file2.jpg"]
}
return render_template('hello.html',**kwargs)The file name of the template here is hello.html, Template files must be stored in ./template Under the table of contents . What you can see is , Template files support variable traversal 、 Judge , Some filters are also supported to get the attributes of variables ( such as : length 、first、last、join Operation, etc. ), For more template syntax, please refer to flask Template syntax __missTu_ The blog of -CSDN Blog _flask Template syntax
<html>
<head>
<title>File Upload</title>
</head>
<body>
Control structure {
{ '{% %}' }}<br/>
Variable value {
{ '{
{ }}' }} Support list、dict、tuple And basic python Variable type <br/>
notes {
{ '{# #}' }}<br/>
' Variable file The length of is :'{
{files|length}}, This is obtained through the filter . For more filter functions, please refer to https://blog.csdn.net/weixin_29370077/article/details/112575271
{% for file in files %}
{% if loop.index0<=1 %}
<li>dir: <a href="{
{file + '\\'}}">{
{file+ '\\'}}</a></li>
{% else %}
<li>file: <a href="{
{file}}">{
{file}}</a></li>
{% endif %}
{% endfor %}
<br/>
<br/>
This is an interface for uploading files
<form action="/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value=" Submit " />
</form>
Download the pictures :<a href="/webhdfs/v1?filename=0007A.jpg">download</a>
Download the pictures :<a href="/downfile?filename=0007A.jpg">downfile</a>
</body>
</html>
The effect of opening in the browser is

3、cookie Set and get
cookie The setup code for is simple , Only response.set_cookie('Name','Hyman') a line . however cookie It's with the server http Corresponding bound meta information , Set up cookie You need to get response. Here bloggers pass make_response('Hello World') obtain response,make_response The template or str Package as response Used to return to the browser . Use directly in the front return Output information to browser , In fact, it has passed on the back end make_response Packaging . In the access to response After the object , We can also set other information , such as headers.
@app.route('/set_cookie')
def set_cookie():
#temp = render_template('hello.html')
#response = make_response(temp)
response=make_response('Hello World');
response.headers['X-Parachutes'] = 'parachutes are cool'
response.set_cookie('Name','Hyman')
#name=request.cookies.get('Name')
return responseobtain cookie The code for request.cookies.get('Name')
4、session Set and get
Use session It should be noted that , To set up app.secret_key, And also set session The validity of the . See the following code for details .app.secret_key It could be any string .
# Use session You need to set secret_key
app.secret_key = "affedasafafqwe"
@app.route("/setAgetSession")
def setAgetSession():
name = request.args.get("name")
session['name'] = name # Set up “ Dictionaries ” Key value pair
session.permanent = True # Set up session Effective time of , Long term effectiveness , One month is valid ,
return "now session name: "+session['name']5、 Upload files
The request method is used here (GET、POST The way ) Judge , Because in many sites, the page for uploading files and the back-end interface are the same url, Judge the specific situation through different request methods .GET The request corresponds to the upload page ,POST The request corresponds to the upload file . Before uploading pictures , Please create first upload Catalog
app.config['UPLOAD_FOLDER'] = 'upload/'
# Request mode judgment request.method
@app.route('/uploader',methods=['GET','POST'])
def uploader():
if request.method == 'POST':
f = request.files['file']# Follow the list file Medium name To be the same
f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))
return 'file uploaded successfully'
else:
return render_template('hello.html')In the form page ,post The request is to be set separately , Otherwise, the default is get The way
This is an interface for uploading files
<form action="/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value=" Submit " />
</form>6、 Download the file
There is only one way to download files , But I'm asking url There are two formats on .
Format 1 : Download files directly through the directory , Example url:http://localhost:14000/down/static/image/head.tif
@app.route("/down/<path:sub_dir1>/<path:sub_dir2>/<filename>", methods=['GET', 'POST'])
def down(sub_dir1, sub_dir2, filename):
file_path = os.path.join(os.getcwd()+ "\\"+sub_dir1+"\\"+sub_dir2+"\\" , filename)
if os.path.isfile(file_path):
send_file(file_path, as_attachment=True)
else:
return "<br/>"+file_path+"<br/>The downloaded file does not exist" The page request result is as follows
Format two : adopt get The parameter passes the file name to be downloaded , Example url: http://localhost:14000/downfile?filename=stasdfstic-sdfsdfsfdssfs/head.tif
@app.route("/downfile")
def download_file():
filename = request.args.get('filename')
file_path = os.path.join(os.getcwd() , filename)
if os.path.isfile(file_path):
return send_file(file_path, as_attachment=True)
else:
return "<br/>"+file_path+"<br/>The downloaded file does not exist"The running results are as follows
7、 obtain get Parameter return json
Here we need to pay attention to the transmission get The format is url?key1=value1&key2=value2......., first get Parameters and url Through between ? Connect , hinder get Parameters are passed through & Connect .json Objects cannot be returned between , Use jsonify take json After converting to a string, you can .
Example url:http://localhost:14000/jsonstr?key1=aaaaaaaaaaaaaa&kery2=bbbbbbbbbbbbbbb
@app.route("/jsonstr")
def jsonstr():
key1 = request.args.get('key1')
key2 = request.args.get('key2')
json={
'key1':key1,'key2':key2}
return jsonify(json)Request the results

边栏推荐
- JS dynamic table creation
- Cloning and importing DOM nodes
- 集群常用群起脚本
- Analysis of common interview questions in redis
- DataX tutorial (09) - how does dataX achieve speed limit?
- [no title] dream notes 2022-02-20
- How to realize hierarchical management of application and hardware in embedded projects
- Cs8683 (120W mono class D power amplifier IC)
- The "&" character will destroy the data stored in the web The "&" character breaks passwords that are stored in the web config
- Brief introduction and use of JSON
猜你喜欢

Acwing2013. three lines
![[v2.0] automatic update system based on motion step API (support disconnection reconnection and data compensation)](/img/73/2ec957d58616d692e571a70826787f.jpg)
[v2.0] automatic update system based on motion step API (support disconnection reconnection and data compensation)

JSON. toJSONString(object, SerializerFeature.WriteMapNullValue); Second parameter action

Viewing Chinese science and technology from the Winter Olympics (V): the Internet of things

Flask 的入门级使用

Arm register (cortex-a), coprocessor and pipeline

Sleep quality today 67 points

Self adjustment process of MySQL index tree when adding data

JS dynamic table creation

Cs8683 (120W mono class D power amplifier IC)
随机推荐
Talk about TCP and UDP
sin(a+b)=sina*cosb+sinb*cosa的推导过程
ACWING/2004. 錯字
Large funds support ecological construction, and Plato farm builds a real meta universe with Dao as its governance
聚类和分类的最基本区别。
In a single-page app, what is the right way to deal with wrong URLs (404 errors)?
直接选择排序和快速排序
In depth inventory: 23 vscode plug-in artifacts that improve development efficiency and aesthetics
How to deploy locally developed SAP ui5 applications to ABAP servers
fastadmin 联级清空数据
这些老系统代码,是猪写的么?
Analysis on the scale of China's smart airport industry in 2020: there is still a large space for competition in the market [figure]
2022 AI trend 8 forecast!
Detailed explanation of @jsoninclude annotation in Jackson
Are these old system codes written by pigs?
[200 opencv routines of youcans] 104 Motion blur degradation model
STL map的用法
Flask 的入门级使用
Single lithium battery 3.7V power supply 2x12w stereo boost audio power amplifier IC combination solution
joda.time获取日期总结