Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to achieve Flask request data acquisition response in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to implement Flask request data acquisition and response in Python. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

First, request data and its acquisition 1.1 request related data # request parameters of the client generally exist in three places: 1, request body 2, request header 3) URL parameter 1). National parameters 2). Query string # carrying parameters of request parameters the following table: serial number parameter or information explanation 1 components of fixed parameter URL, not missing 2 query string: args according to demand Optional or not 3 form data submission form form is transmitted data 4 file upload: file uploaded by files user to server 5 request header: headers request header 6 request method: request method used in method request 7URL address: url request URL address 1.2 fixed parameter and converter # content abstract 1. Fixed parameter 2. Acquisition of fixed parameters 3. Converter 4. Custom converter # 1, fixed parameter fixed parameter refers to fixed in URL, is an inaccessible part, different from query string, query string is optional fixed parameter: / article/1: if 1 is the id of the article, it is an inaccessible part / art/1?title= "decorator": title follows? Followed by the query string # 2. Acquisition of request parameters # (1). The syntax form: @ app.route ('/ users/') def user_info (user_id): return 'gets the userid as: {}' .format (user_id) # (2). Syntax explanation: used in routing to receive fixed parameters, and do not forget to pass the view, that is, the view must define the formal parameter user_id. Note:-user_id in the route can be limited before the type, written reference:, defined the type, the fixed parameters from the front end must meet the type requirements, otherwise an error is reported; if the type is not defined, the default received is a string type-the view must define the formal parameter, and the name of the formal parameter must be the same as that in the route, that is, user_id is written in the route, and the formal parameter of the view function must also be user_id#3. The fixed parameters above the converter are implemented using converters. Flask comes with six converters:-UnicodeConverter: string converter-AnyConverter: matches any path in any, written as'/ users/'-PathConverter: path converter, similar to string converter. But the parameter can include "/"-IntergerConverter: shaping converter-FloatConverter: floating-point converter-UUIDConverter:UUID unique identification code converter # 4. Custom converter if the flask built-in converter can not meet specific needs, you can customize the converter, custom converter can participate in the source code implementation # (1). Custom Converter step-Custom Converter Class: inherited from BaseConverter, internally specified regular matching rules-Custom Converter Class added to Converter Container assignment-use Custom Converter # (2). Custom converter instance # imports BaseConverterfrom werkzaug.routing import BaseConverter# custom Converter class calss phoneConverter (BaseConverter): regex = rns1 [3-9]\ d {9}'# add to Converter container app.url_map.converters ['phone'] = phoneConverter# (3). Use the custom converter @ app.route ('/ user/') def user_info (user_id): return user_id1.3 query parameter to get # args: query parameter # (1). Query parameters query parameters in URL? Separated from the main route, the query parameters are in the form of key-value pairs, which are connected with "=" as follows: / user/?userid=333 # (2). Query parameter acquisition request.args.get ('key') request.args [' key'] # (3). Example: from flask import Flaskfrom flask import request app = Flask (_ _ name__) @ app.route ('/') def user_info (): # get user_id user_id_1 = request.args in query parameters in ['key'] form [' userid'] # get user_id user_id_2 = request.args.get ('userid') return' user_id_1 in query by get method: {} User_id_2: {} '.format (user_id_1,user_id_2) # access route: http://127.0.0.1:5000/?userid=333, can see the result on the page 1.4 form data acquisition # form: form data # (1). Form data form form data, generally used for login, registration, information submission and so on. When used with front-end form forms, general form forms are post requests. Note that the POST request method is specified in the route, and the form data is encapsulated in the request body # (2). Form data acquisition method request.form.get ('key') # (3). Example from flask import Flaskfrom flask import request app = Flask (_ _ name__) @ app.route ('/' Methods= ['post]) def login (): # get the user name in the form form username = request.form.get (' uname') # get the password in the form form password = request.form.get ('pwd') # judgment of the user name and password if username = =' admin' and password = = 'admin123': return' login successful 'else: return' login failed'if _ _ name__ = ='_ _ main__': app.run () # postman access http://127.0.0.1:5000/, And specify form-data as {'uname':' admin', 'pwd':' admin123'} 1.5 File upload # files: file data # (1). The acquisition of the file object file_obj = request.files.get ('key') # (2). Attribute file_obj.filename of file object: file name of uploaded file file_obj.name: keyfile_obj.save specified for uploading file ('path'): file object saving method # example: from flask import Flaskfrom flask import request # create Flask instance object app = Flask (_ _ name__) @ app.route (' / upload') Methods= ['POST']) def upload_file (): # get the file object passed by the front end img = request.files.get (' pic') # get the file name of the file object file_name = img.filename # Save the file object img.save (file_name) return 'uploaded successfully!' If _ _ name__ = ='_ main__': app.run () 1.6 other request parameters # other parameters:-headers: message header in the record request header-method: HTTP request method used by the record request-url: record request URL address # example: from flask import Flaskfrom flask import request # create Flask instance object app = Flask (_ _ name _ _) @ app.route ('/') def index (): # print request header information print (request.headers) print ('-'* 50) # print request method print (request.method) print ('-'* 50) # print request URL print (request.url) return 'other args' if _ _ name__ = =' _ main__': app.run () II Response data new book three-piece set 2.1 string response form # string returns a string directly using the return keyword: return 'hello flask'2.2 template response format # template return-create a templates folder (Mark Directory as Template Folder in pycharm In pycharm, you also need to set the template engine to jinjia2)-create the HTML page to be returned in template-use render_template ('HTML file name') to return the template in the view # example: from flask import Flaskfrom flask import render_template app = Flask (_ _ name__) @ app.route ('/') def index (): # render_template () returns the template return render_template ('index.html') if _ _ Name__ = ='_ _ main__': app.run ()

Expand some jinjia2 template engines:

The syntax of the Jinjia2 template is basically the same as that of our django built-in template, and we simply understand

We define the variable data in the view

@ app.route ("/", methods= ["GET", "POST"]) def hello_world (): new_list = ["News 1", "News 2", "News 3", "News 4"] return render_template ("home.html", news= {"news_list": new_list, "title": "I am the new title"})

Use defined variable data in a template

{{variable name}} displays the value of the variable

{% for statement%} loop body {% endfor%}

{{news.title}} "meritorious service-Li Yannian" {% for item in news.news_list%}

{{item}}

{% endfor%} 2.3Redirect response form # redirect: redirect is to jump to a new route, using redirect # redirect form:-redirect an outer link directly-redirect an internal link # redirect outer chain example: from flask import Flaskfrom flask import redirect app = Flask (_ _ name__) @ app.route ('/') def index (): # access / root route Jump directly to Baidu homepage return redirect ('http://www.baidu.com/') if _ _ name__ = =' _ main__': app.run () # redirect to internal connection from flask import Flaskfrom flask import redirectfrom flask import url_for app = Flask (_ _ name__) @ app.route ('/') def start (): # use url_for to jump to internal link The appointment value of a route specified in url_for () return redirect (url_for ('idx')) # redirect jumps directly, passing in the specified route # return redirect (' / index') @ app.route ('/ index', endpoint='idx') def index (): return 'index page' if _ name__ = ='_ main__': app.run (debug=True) three Response json data and tuple data 3.1json data response # return json data return json data needs to be implemented with jsonify provided by flask # example: from flask import Flaskfrom flask import jsonify app = Flask (_ _ name__) @ app.route ('/ index', endpoint='idx') def index (): # Dictionary form data data = {'name':' jeremy' 'age': 18} # return json data return jsonify (data) # take a look at the source code if _ _ name__ = =' _ main__': app.run (debug=True) 3.2 tuple data response # you can return a tuple in tuple format Such tuples must be of the form (response, status, headers) and contain at least one element. The status value overrides the status code, and headers can be a list or dictionary as an additional message header value. # example is as follows: from flask import Flaskfrom flask import jsonify app = Flask (_ _ name__) @ app.route ('/ index', endpoint='idx') def index (): # return ('string to be returned', 6969 is the status code, {'author':' jeremy'} dictionary is the key-value pair information set in the response header) return ('string to be returned', 6969 {'author':' jeremy'}) if _ _ name__ = ='_ main__': app.run (debug=True) four Make_response () Custom response # redirect: redirect is to jump to a new route, using redirect # redirect form:-redirect an outer link directly-redirect an internal link # redirect outer chain example: from flask import Flaskfrom flask import redirect app = Flask (_ _ name__) @ app.route ('/') def index (): # access / root route Jump directly to Baidu homepage return redirect ('http://www.baidu.com/') if _ _ name__ = =' _ main__': app.run () # redirect to internal connection from flask import Flaskfrom flask import redirectfrom flask import url_for app = Flask (_ _ name__) @ app.route ('/') def start (): # use url_for to jump to internal link The appointment value of a route specified in url_for () return redirect (url_for ('idx')) # redirect jumps directly, passing in the specified route # return redirect (' / index') @ app.route ('/ index', endpoint='idx') def index (): return 'index page' if _ name__ = ='_ main__': app.run (debug=True) Thank you for reading! This is the end of the article on "how to achieve Flask request data acquisition response in Python". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report