python code generation API interface
To generate API interfaces from our written Python code, we need to take advantage of theFlask Framework
1. Install Flask
pip install Flask
2. Writing Flask applications
(1) Create a new python file (note that the name of the python file you create cannot be, as this will conflict with Flask itself)
(2) Write the following in the newly created file:
# from flask import Flask app = Flask(__name__) @('/test',methos=['post']) def hello_world(): return 'Hello, World!' if __name__ == '__main__': (debug=True)
First we import the Flask class, then we create an instance of that class. The first parameter is the name of the application module or package.
If you are using a single module (as in this example), then you should use thename because the name changes depending on whether the module is used per-application or imported as a module (possibly 'main', which may also be the name of the actual import).
This parameter is required so that Flask knows where to find things like templates and static files. We then use the route() decorator to tell Flask the URL that triggers the function. The function name is used to generate the associated URL. The function finally returns the information that needs to be displayed in the user's browser.
3. Run the Flaks application
(1) Export the FLASK_APP environment variable in the terminal.
$ export FLASK_APP=
(2) Run the program
$ flask run 1. Running on http://127.0.0.1:5000/
4. Use of the interface
Used Postman (an interface testing tool) for testing:
This will return the result "Hello, World!"
At this point, we have completed a simple example of generating an API interface from Python code!
See the official Flask documentation for more:
Official Flask Documentation
python write api interface practice
procedure
1. import: import flask,json
2. Instantiation: api = (name)
3. Define the interface access path and access methods: @('/index',methods=['get/post/PUT/DELETE'])
4. Define the function, note the need to be consistent with the name of the path, set the return type and support for Chinese: def index(): return (ren,ensure_ascii=False)
5. Three format entry parameters to access the interface:
- 5.1 url format entry: ('id')
- 5.2 Form-data entry: pwd = ('pwd')
- 5.3 josn format entry: pwd = ('pwd')
6. Start the service: (port=8888,debug=True,host='127.0.0.1'), after turning on the service, you can access the interface via ip+port+path+input.
source code example
#!/usr/bin/python3 # encoding:utf-8 import flask,json # Instantiate the api, treating the current python file as a service, with __name__ representing the current python file api = (__name__) # 'index' is the interface path, methods is not written, default get request @('/index',methods=['get']) # get method access def index(): ren = {'msg':'Successful visit to home page','msg_code':200} # Serialize Chinese with ascii encoding by default. You need to specify ensure_ascii=False to output Chinese. return (ren,ensure_ascii=False) #post in-parameter access mode 1: url format parameters @('/article',methods=['post']) def article(): #url format parameters?id=12589&name='lishi' id = ('id') if id: if id == '12589': ren = {'msg':'Successful access to articles','msg_code':200} else: ren = {'msg':'Article not found','msg_code':400} else: ren = {'msg':'Please enter the article id parameter','msg_code':-1} return (ren,ensure_ascii=False) #post in-parameter access mode 2: from-data (k-v) format parameters @('/login',methods=['post']) def login(): #from-data format parameters usrname = ('usrname') pwd = ('pwd') if usrname and pwd: if usrname =='test' and pwd =='123456': ren = {'msg':'Login successful','msg_code':200} else: ren = {'msg':'Username or password error','msg_code':-1} else: ren = {'msg':'Username or password is empty','msg_code':1001} return (ren,ensure_ascii=False) #post entry access mode two: josn format parameters @('/loginjosn',methods=['post']) def loginjosn(): #from-data format parameters usrname = ('usrname') pwd = ('pwd') if usrname and pwd: if usrname =='test' and pwd =='123456': ren = {'msg':'Login successful','msg_code':200} else: ren = {'msg':'Username or password error','msg_code':-1} else: ren = {'msg':'Username or password is empty','msg_code':1001} return (ren,ensure_ascii=False) if __name__ == '__main__': (port=8888,debug=True,host='127.0.0.1') # Start the service # debug=True, after changing the code, no need to reboot, it will reboot automatically # 'host='127.0.0.1'classifyIPaccess address
Run results:
* Serving Flask app 'monitor' (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 stat
* Debugger is active!
* Debugger PIN: 991-833-116
* Running on http://127.0.0.1:8888/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Jan/2022 14:05:53] "POST /login?usrname=test&pwd=123456 HTTP/1.1" 200 -
127.0.0.1 - - [16/Jan/2022 14:08:34] "GET /index HTTP/1.1" 200 -
request method
Use postman to test if the interface works
As:
url:127.0.0.1:8888/login
Parameters: usrname=test;pwd=123456
Several ways to get request parameters
("key", type=str, default=None) Getting form data, ("key") gaingetRequest Parameters, ("key") gain所有参数。
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.