The development environment

Python version: 3.x


Package: flask


Tools:


1.Pycharm
2.Postman


Goal: Develop an interface that accepts only get methods, takes name and age, and returns the corresponding content.

The implementation code

from flask import Flask,request
import json
 
app=Flask(__name__)
 
Only get access is allowed
@ app. The route ("/test_1. 0 ", the methods = / "GET")
def check(a):
    # Return content by default
    return_dict= {'return_code': '200'.'return_info': 'Processing successful'.'result': False}
    Check whether the input parameter is empty
    if request.args is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'Request parameters are empty'
        return json.dumps(return_dict, ensure_ascii=False)
    Get the params parameter passed in
    get_data=request.args.to_dict()
    name=get_data.get('name')
    age=get_data.get('age')
    # operation on parameters
    return_dict['result']=tt(name,age)
 
    return json.dumps(return_dict, ensure_ascii=False)
 
# function function
def tt(name,age):
    result_str="%s is %s this year" %(name,age)
    return result_str
 
if __name__ == "__main__":
    app.run(debug=True)
Copy the code

Implementation effect

Pycharm runs as follows:



1. Use the postman tool to send the request to the interface address 127.0.0.1:5000/test_1.0

The results are as follows:



2. If the interface is changed to support only post access, the code is as follows:

from flask import Flask,request
import json
 
app=Flask(__name__)
 
Only POST is allowed
@ app. The route ("/test_1. 0 ", the methods = (" POST "))
def check(a):
    # Return content by default
    return_dict= {'return_code': '200'.'return_info': 'Processing successful'.'result': False}
    Check whether the incoming JSON data is null
    if request.get_data() is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'Request parameters are empty'
        return json.dumps(return_dict, ensure_ascii=False)
    Get the parameters passed in
    get_Data=request.get_data()
    The arguments passed in are bytes and need to be converted to JSON
    get_Data=json.loads(get_Data)
    name=get_Data.get('name')
    age=get_Data.get('age')
    # operation on parameters
    return_dict['result']=tt(name,age)
 
    return json.dumps(return_dict, ensure_ascii=False)
 
# function function
def tt(name,age):
    result_str="%s is %s this year" %(name,age)
    return result_str
 
if __name__ == "__main__":
    app.run(debug=True)
Copy the code

Using the Postman test interface:



So that’s it for this time.

Welcome to wechat public number: Programming Technology circle