当前位置:网站首页>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

边栏推荐
- JD 7 head search navigation layout
- Kubernetes cluster dashboard & kuboard installation demo
- Brief introduction and use of JSON
- Laravel8+ wechat applet generates QR code
- Comparison test of mono 120W high power class D power amplifier chip cs8683-tpa3116
- Which of the top ten securities companies has the lowest Commission and is the most safe and reliable? Do you know anything
- Single lithium battery 3.7V power supply 2x12w stereo boost audio power amplifier IC combination solution
- ACWING2013. 三条线
- 使用OpenGL绘制shp文件
- Understand what MSS is
猜你喜欢

Ht7180 3.7V L 12v/2a built in MOS high current boost IC solution

Three laws of go reflection

Drosophila played VR and entered nature. It was found that there were attention mechanisms and working memory. The insect brain was no worse than that of mammals

Can TCP syn handshake messages transmit data

有能力的人从不抱怨大环境!

Sophomores majoring in mechanics build a manipulator by hand -- full of compromise

Understand what ICMP Protocol is

Introduction to sap ui5 tools

Face++ realizes face detection by flow

R & D thinking 07 - embedded intelligent product safety certification required
随机推荐
十大券商公司哪个佣金最低,最安全可靠?有知道的吗
@Principle of preauthorize permission control
Aviator an expression evaluation engine
JD 7 head search navigation layout
How two hosts in different network segments directly connected communicate
[speech discrimination] discrimination of speech signals based on MATLAB double threshold method [including Matlab source code 1720]
Single lithium battery 3.7V power supply 2x12w stereo boost audio power amplifier IC combination solution
Wan Yin revealed that he was rejected by MIT in this way: "the department doesn't like you". He confronted the principal and realized
How do I check swift if two arrays contain the same elements, regardless of the order in which they appear?
An interview question record about where in MySQL
アルマ / 炼金妹
TCP BBR as rate based
【ROS2】为什么要使用ROS2?《ROS2系统特性介绍》
After five years of software testing in ByteDance, I was dismissed in December to remind my brother of paddling
Metauniverse in 2022: robbing people, burning money and breaking through the experience boundary
ACWING/2004. Misspelling
VMware virtual machine prompt: the virtual device ide1:0 cannot be connected because there is no corresponding device on the host.
Tp6 interface returns three elements
直接选择排序和快速排序
了解zbrush雕刻软件,以及游戏建模的分析