get方法
代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
# coding:utf-8 import json from urlparse import parse_qs from wsgiref.simple_server import make_server # 定義函數,參數是函數的兩個參數,都是python本身定義的,默認就行了。 def application(environ, start_response): # 定義文件請求的類型和當前請求成功的code start_response( '200 ok' , [( 'content-type' , 'text/html' )]) # environ是當前請求的所有數據,包括header和url,body,這里只涉及到get # 獲取當前get請求的所有數據,返回是string類型 params = parse_qs(environ[ 'query_string' ]) # 獲取get中key為name的值 name = params.get( 'name' , [''])[ 0 ] no = params.get( 'no' , [''])[ 0 ] # 組成一個數組,數組中只有一個字典 dic = { 'name' : name, 'no' : no} return [json.dumps(dic)] if __name__ = = "__main__" : port = 5088 httpd = make_server( "0.0.0.0" , port, application) print "serving http on port {0}..." . format ( str (port)) httpd.serve_forever() |
請求實例
post方法
代碼實現
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
# coding:utf-8 import json from wsgiref.simple_server import make_server # 定義函數,參數是函數的兩個參數,都是python本身定義的,默認就行了。 def application(environ, start_response): # 定義文件請求的類型和當前請求成功的code start_response( '200 ok' , [( 'content-type' , 'application/json' )]) # environ是當前請求的所有數據,包括header和url,body request_body = environ[ "wsgi.input" ].read( int (environ.get( "content_length" , 0 ))) request_body = json.loads(request_body) name = request_body[ "name" ] no = request_body[ "no" ] # input your method here # for instance: # 增刪改查 dic = { 'mynameis' : name, 'mynois' : no} return [json.dumps(dic)] if __name__ = = "__main__" : port = 6088 httpd = make_server( "0.0.0.0" , port, application) print "serving http on port {0}..." . format ( str (port)) httpd.serve_forever() |
請求實例
疑問
怎么實現請求的路徑限制?
怎么限制接口調用方的headers?
以上這篇對python實現簡單的api接口實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/u013040887/article/details/78895323