Python: simple usage of request object in flask

Because the written Python program needs to be rewritten into an API interface for other departments to use, this blog focuses on using the request object of flash to complete data transmission. For deeper theoretical content, it will be supplemented later;
This article only covers the local server, and does not cover the deployment on the remote server. The version information of Flask and Python used in this article is as follows:
Flask:1.1.2
Python:3.8.8

1. Flask package

   Flask is a lightweight customizable framework written in Python language, which is more flexible, lightweight, safe and easy to use than other similar frameworks. Start with the simplest example:

from flask import Flask
app = Flask(__name__) #This statement is used to create an instance of a Web application
@app.route('/') #Define routing rules
def index():
    return 'Hello World'
if __name__ == '__main__':
    app.run(debug=True)

After running in Anaconda, open in the browser: http://127.0.0.1:5000 You can see the running results. As follows:

2. Flash Request object
2.1 GET mode
from flask import Flask,request
import json
app=Flask(__name__)
@app.route('/test_1',methods=['GET'])
def check():
    return_dict={'statusCode':200,'message':'successful','result':False}
    name=request.args.get('name') #
    age=request.args.get('age')
    return_dict['result']=tt(name,age)
    return json.dumps(return_dict,ensure_ascii=False)#ensure_ Chinese can be displayed when ASCII is set to False
def tt(name,age):
    result_str='{}this year{}year'.format(name,age)
    return result_str
if __name__=='__main__':
    app.run(debug=True)

Run the above code successfully and output the following code:

 * Serving Flask app "server" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with windowsapi reloader

Enter the following web address in the browser: http://127.0.0.1:5000/test_1?name = Xiaoming & age = 20 (note that although name is a string type, quotation marks are not required in this writing method). The specific execution results are as follows:

2.2 POST mode

  many materials on the Internet say that Postman needs to be installed to debug in this mode, but I didn't install Postman here, so I directly used Anaconda to debug. Two code files need to be written in POST mode:
server.py

from flask import Flask,request
import json

app=Flask(__name__)
@app.route('/test_1',methods=['POST'])
def check():
    return_dict={'statusCode':200,'message':'successful','result':False}
    if not request.get_json():
        return json.dumps(return_dict,ensure_ascii=False)
    name=request.get_json()['name']
    age=request.get_json()['age']
    result=tt(name,age)
    return_dict['result']=result
    return json.dumps(return_dict,ensure_ascii=False)

def tt(name,age):
    result_str='{}this year{}year'.format(name,age)
    return result_str

if __name__=='__main__':
    app.run(debug=True)

At this time, run the file in Anaconda's spyder. The specific results are as follows (this indicates that the server has been started normally):

Write another test.py file as follows:

import requests
if __name__=="__main__":
    testData={'name':'Xiao Ming','age':12}
    r=requests.post('http://127.0.0.1:5000/test_1',json=testData)
    print(r.json())

Re open a console in Anaconda and execute the test.py file. You can directly see the returned results:

Because Postman is not used here, it may be a little troublesome to debug the code. If the program is not executed correctly and you want to view the error message, you can enter the following command in the console to view it:

3. Problems encountered

(1)ConnectionError exception. Specific error information

ConnectionError: HTTPConnectionPool(host='localhaost', port=5000): Max retries exceeded with url: /test_1 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001D008A10070>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))
This problem may be caused by the use of localhost in the code. Change localhost to specific http://127.0.0.1:5000 It's OK (if the port number has been modified, 5000 can't be used here)

reference material
  1. Baidu Encyclopedia: Flask
  2. https://www.jianshu.com/p/6452596c4edb
  3. https://blog.csdn.net/xxn_723911/article/details/90293421

Tags: Python

Posted on Wed, 17 Nov 2021 05:37:29 -0500 by jwstockwell