Web API學習筆記(Python實現)


 

 

 參考指南:

Web API入門指南

http://www.cnblogs.com/guyun/p/4589115.html

用Python寫一個簡單的Web框架

http://www.cnblogs.com/russellluo/p/3338616.html

WSGI接口 def application(environ, start_response)

https://blog.csdn.net/tycoon1988/article/details/40394555

GET和POST兩種基本請求方法的區別

https://www.cnblogs.com/logsharing/p/8448446.html

 

 

Web API :

面向如瀏覽器,移動設備等各種客戶端,提供Http服務的框架。

支持基於HTTP的各種操作(get,post,put,delete)。

請求的回復格式支持JSON,XML,CSV等。

 

使用場景:

1)服務在http協議之上,利用http協議的各種功能;

2)服務需被各種客戶端(尤其是移動客戶端)調用。

 

WISG(Web Server Gateway Interface):

在Python中,WSGI(Web Server Gateway Interface)定義了Web服務器與Web應用(或Web框架)之間的標准接口.

利用WSGI,可以很方便寫一個Web框架。

引用方式是:from wsgiref.simple_server import make_server。

application()函數就是符合WSGI標准的一個HTTP處理函數,它接收兩個參數:

1)environ:一個包含所有HTTP請求信息的dict對象;

2)start_response:一個發送HTTP響應的函數。

 

urlparse解析URL參數模塊:

可以對URL按照一定格式進行拆分或拼接。

urlparse.parse_qs()方法返回解析URL后的字典

 

Json(JavaScriptObject Notation, JS 對象標記):

是輕量級的數據交換格式

格式:雙引號 "" 包裹健名,使用冒號 : 分隔,然后緊接着值:

如 {"firstName": "Json"}

優點:使用的字符比xml與html等少,大大節約傳輸數據占用的帶寬;

語法格式與層次結構比較清晰,容易閱讀。

json.dumps()函數是將字典轉化為字符串.

 

get/post請求:

get:請求參數都是通過url傳遞,如url?param1=xxx&param2=xxx

post:請求參數通過request body傳遞,需要知道請求參數類型(如application/json、application/x-www-form-urlencoded、multipart/form-data、text/html等),url,返回結果格式,是否有是否有header、cookie等

 

實例:

 實例1:啟動一個簡單web,訪問時返回hello world!字符串

 1 # coding:utf-8
 2 
 3 #導入WISG(Web Server Gateway Interface)
 4 from wsgiref.simple_server import make_server
 5 
 6 #application()函數是Python中符合WSGI標准的一個HTTP處理函數,返回是一個字符串
 7 def application(environ,start_response):
 8      #start_response如下調用就會發送HTTP響應的Header,注意只能調用一次start_response()函數發送Header。
 9      #start_response()函數兩個參數,一是HTTP響應碼,一是一組list表示的HTTP Header,每個Header用一個包含兩個str的數組表示
10      status='200 OK'
11      response_headers = [('Content-type', 'text/plain')]
12      start_response(status,response_headers)
13      return ['Hello world!\n']
14 
15 ip='0.0.0.0'
16 port=8089
17 httpd =make_server(ip,port,application)
18 print("server is started, port is 8089....")
19 httpd.serve_forever()
20 
21  
View Code

運行結果:

 

 

實例2:啟動一個簡單web,訪問接口,返回解析URL的值

 

# coding:utf-8

#導入WISG(Web Server Gateway Interface)
from wsgiref.simple_server import make_server
import urlparse

#application()函數是Python中符合WSGI標准的一個HTTP處理函數,返回是一個字符串
def application(environ,start_response):
     #start_response如下調用就會發送HTTP響應的Header,注意只能調用一次start_response()函數發送Header。
     #start_response()函數兩個參數,一是HTTP響應碼,一是一組list表示的HTTP Header,每個Header用一個包含兩個str的數組表示
     status='200 OK'
     response_headers = [('Content-type', 'text/html')]
     start_response(status,response_headers)

     #調用urlparse的parse_qs解析URL參數,並返回字典
     query_args=environ['QUERY_STRING']
     params = urlparse.parse_qs(environ['QUERY_STRING'])

     print(str(params))
     return [str(params)]

ip='0.0.0.0'
port=8089
httpd =make_server(ip,port,application)
print("server is started, port is 8089....")
httpd.serve_forever()

 運行結果:

 

 

 

 實例3:啟動一個簡單web,訪問接口,返回解析URL的值(n個變量),JSON格式

# coding:utf-8

#導入WISG(Web Server Gateway Interface)
from wsgiref.simple_server import make_server
import urlparse
import json

#application()函數是Python中符合WSGI標准的一個HTTP處理函數,返回是一個字符串
def application(environ,start_response):
      #start_response如下調用就會發送HTTP響應的Header,注意只能調用一次start_response()函數發送Header。
     #start_response()函數兩個參數,一是HTTP響應碼,一是一組list表示的HTTP Header,每個Header用一個包含兩個str的數組表示
     status='200 OK'
     response_headers = [('Content-type', 'text/html')]
     start_response(status,response_headers)

     #調用urlparse的parse_qs解析URL參數,並返回字典
     query_args=environ['QUERY_STRING']
     params = urlparse.parse_qs(environ['QUERY_STRING'])
     #返回的字段,需要轉換為字符串作為函數的輸出
     print(str(params))
     #json.dumps()函數是將字典轉化為字符串
     result=json.dumps(params)
     return [result]

ip='0.0.0.0'
port=8089
httpd =make_server(ip,port,application)
print("server is started, port is 8089....")
httpd.serve_forever()

返回結果:

 實例4:啟動一個簡單web,get方法訪問接口,根據輸入的值返回判斷結果(JSON格式)

# coding:utf-8

#導入WISG(Web Server Gateway Interface)
from wsgiref.simple_server import make_server
import urlparse
import json

#application()函數是Python中符合WSGI標准的一個HTTP處理函數,返回是一個字符串
def application(environ,start_response):
 #start_response如下調用就會發送HTTP響應的Header,注意只能調用一次start_response()函數發送Header。
 #start_response()函數兩個參數,一是HTTP響應碼,一是一組list表示的HTTP Header,每個Header用一個包含兩個str的數組表示
 status='200 OK'
 response_headers = [('Content-type', 'text/html')]
 start_response(status,response_headers)

 #調用urlparse的parse_qs解析URL參數,並返回字典
 query_args=environ['QUERY_STRING']
 params = urlparse.parse_qs(query_args)
 # 獲取get中key為name的值
 name = params.get('name', [''])[0]
 # 獲取get中key為passwd的值
 passwd = params.get('passwd', [''])[0]
 # 獲取get中key為tel的值
 tel = params.get('tel', [''])[0]

 if name=='admin' and passwd=='123456' and tel=='139':
  result={'code':200,'message':"You get the flag"}
  return json.dumps(result)
 elif passwd!='123456':
  result={'code':404,'message':"oh, passwd is wrong!"}
  return json.dumps(result)
 elif name!='admin':
  result={'code':404,'message':"oh, name  is wrong!"}
  return json.dumps(result)
 else:
  result={'code':404,'message':"oh,what are you doing???"}
  return json.dumps(result)
 #返回的字段,需要轉換為字符串作為函數的輸出
 print(str(params))
 #json.dumps()函數是將字典轉化為字符串
 #result=json.dumps(params)
 return [result]

ip='0.0.0.0'
port=8089
httpd =make_server(ip,port,application)
print("server is started, port is 8089....")
httpd.serve_forever()

返回結果:

 

 實例5:啟動一個簡單web,post方法訪問接口,根據輸入的值返回結果(JSON格式)

 

# coding:utf-8

#導入WISG(Web Server Gateway Interface)
from wsgiref.simple_server import make_server
import json
from cgi import parse_qs, escape

#application()函數是Python中符合WSGI標准的一個HTTP處理函數,返回是一個字符串
def application(environ,start_response):
 #start_response如下調用就會發送HTTP響應的Header,注意只能調用一次start_response()函數發送Header。
 #start_response()函數兩個參數,一是HTTP響應碼,一是一組list表示的HTTP Header,每個Header用一個包含兩個str的數組表示
 status='200 OK'
 response_headers = [('Content-type', 'application/json')]
 start_response(status,response_headers)

 #environ是當前請求的所有數據,包括Header和URL,body #當請求方法是POST的時候,查詢字符串將從HTTP請求體中傳遞而不是通過URL。
 #請求體是WSGI服務器提供的類似於環境變量的wsgi.input文件 #有必要知道應答體的大小,以便從wsgi.input中讀出它。WSGI明細規定,CONTENT_LENGTH變量來存儲大小,它可以為空或者被忽略,所以讀它的時候把它放到一個try/except塊中。
 try:
  request_body_size = int(environ.get('CONTENT_LENGTH', 0))
 except (ValueError):
  request_body_size = 0
 print("request_body_size is:"+str(request_body_size))
 request_body = environ["wsgi.input"].read(request_body_size)

 print("request_body is:"+request_body)
 # 獲取get中key為name的值
 name=parse_qs(request_body).get("name", [""])[0]
 # 獲取get中key為passwd的值
 passwd = parse_qs(request_body).get('passwd', [''])[0]
 print(name,passwd)

 #返回的字段,需要轉換為字符串作為函數的輸出
 #json.dumps()函數是將字典轉化為字符串
 #result=json.dumps(params)
 return [request_body]

ip='0.0.0.0'
port=8089
httpd =make_server(ip,port,application)
print("server is started, port is 8089....")
httpd.serve_forever()

請求與應答:

Jmeter發送post請求,並查看結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM