天天看點

python快速實作一個接口服務

在我們的業務中,需要啟動一個daemon程序,提供相關的資料給遠端來通路擷取。這個例子中是用python來啟動一個web服務,擷取某個檔案下的資料,然後提供遠端實時調用,代碼如下:

#!/usr/bin/env python
 
import json,os,time
##這幾個子產品都是python自帶的,不需要重新安裝
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'])
    ccu = params.get('get_ccu', [''])[0]  ##api傳參可以保持不變
    with open('/data/test01.log', 'r') as f:
        data01 = f.read().strip()
    with open('/data/test02.log', 'r') as f:
        data02 = f.read().strip()
    timenow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    ##這裡的字典值根據不同的需求傳不同的資料
    dic = {'region': "ttt", 'data01': data01, 'data02': data02, 'time': timenow}
    return [json.dumps(dic)]
 
if __name__ == "__main__":
    port = 6666 #本機監聽的端口
    httpd = make_server("0.0.0.0", port, application)
    print "serving http on port {0}...".format(str(port))
    httpd.serve_forever()

           

腳本寫好之後,因為是需要以daemon方式常駐背景,是以有以下兩種方式:

1.使用nohup python script.py & 運作起來

2.安裝supervisor,配置為daemon運作,并且挂掉自動拉起

程序運作之後,可以使用curl -s http://localhost:6666/?get_ccu通路接口,得到想要後去的資料。

這個小腳本還是友善好用,在日常的工作中經常會使用到。