Python實現簡單的API接口


get方法

代碼實現

  1.  
    # coding:utf-8
  2.  
     
  3.  
    import json
  4.  
    from urlparse import parse_qs
  5.  
    from wsgiref.simple_server import make_server
  6.  
     
  7.  
     
  8.  
    # 定義函數,參數是函數的兩個參數,都是python本身定義的,默認就行了。
  9.  
    def application(environ, start_response):
  10.  
    # 定義文件請求的類型和當前請求成功的code
  11.  
    start_response( '200 OK', [('Content-Type', 'text/html')])
  12.  
    # environ是當前請求的所有數據,包括Header和URL,body,這里只涉及到get
  13.  
    # 獲取當前get請求的所有數據,返回是string類型
  14.  
    params = parse_qs(environ[ 'QUERY_STRING'])
  15.  
    # 獲取get中key為name的值
  16.  
    name = params.get( 'name', [''])[0]
  17.  
    no = params.get( 'no', [''])[0]
  18.  
     
  19.  
    # 組成一個數組,數組中只有一個字典
  20.  
    dic = { 'name': name, 'no': no}
  21.  
     
  22.  
    return [json.dumps(dic)]
  23.  
     
  24.  
     
  25.  
    if __name__ == "__main__":
  26.  
    port = 5088
  27.  
    httpd = make_server( "0.0.0.0", port, application)
  28.  
    print "serving http on port {0}...".format(str(port))
  29.  
    httpd.serve_forever()

 

請求實例

這里寫圖片描述

post方法

代碼實現

  1.  
    # coding:utf-8
  2.  
     
  3.  
    import json
  4.  
    from wsgiref.simple_server import make_server
  5.  
     
  6.  
     
  7.  
    # 定義函數,參數是函數的兩個參數,都是python本身定義的,默認就行了。
  8.  
    def application(environ, start_response):
  9.  
    # 定義文件請求的類型和當前請求成功的code
  10.  
    start_response( '200 OK', [('Content-Type', 'application/json')])
  11.  
    # environ是當前請求的所有數據,包括Header和URL,body
  12.  
     
  13.  
    request_body = environ[ "wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
  14.  
    request_body = json.loads(request_body)
  15.  
     
  16.  
    name = request_body[ "name"]
  17.  
    no = request_body[ "no"]
  18.  
     
  19.  
    # input your method here
  20.  
    # for instance:
  21.  
    # 增刪改查
  22.  
     
  23.  
    dic = { 'myNameIs': name, 'myNoIs': no}
  24.  
     
  25.  
    return [json.dumps(dic)]
  26.  
     
  27.  
     
  28.  
    if __name__ == "__main__":
  29.  
    port = 6088
  30.  
    httpd = make_server( "0.0.0.0", port, application)
  31.  
    print "serving http on port {0}...".format(str(port))
  32.  
    httpd.serve_forever()

 


請求實例

這里寫圖片描述


免責聲明!

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



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