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

  obtain 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

 

原网站

版权声明
本文为[Ten thousand miles' journey to]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250434458324.html