需求分析:
省油寶用戶數 已經破了6000,原有的靜態報表 已經變得臃腫不堪,
每次打開都要緩上半天,甚至瀏覽器直接掛掉
采用python搭建一個最最簡易的 web 服務 請求一個nick
就返回 對應的 報表數據 參數用GET方式傳送
調研與實現:
園里沒找到靠譜的,google了半天,最終還是成功了。
以下是源碼,里面記錄了 其中的 一些問題
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 @author: zhoujiebin 5 @contact: zhoujiebing@maimiaotech.com 6 @date: 2012-12-14 15:25 7 @version: 0.0.0 8 @license: Copyright maimiaotech.com 9 @copyright: Copyright maimiaotech.com 10 11 """ 12 13 import os 14 import sys 15 import urllib 16 import SimpleHTTPServer 17 import SocketServer 18 19 PORT = 8080 20 WEBDIR = "/home/zhoujiebing/report_web_service" 21 from syb_report_html import get_html 22 23 class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler): 24 def translate_path(self, path): 25 #用於設定根目錄 26 os.chdir(WEBDIR) 27 SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path) 28 29 def do_GET(self): 30 #服務器端響應GET請求的方法 31 #問題1 如何拿到客戶端的GET參數 32 #我找半天沒找到,最后__dict__看到path里有路徑,只能從路徑里 提取參數了 33 #從path中提取 GET參數 34 nick = self.path[1:] 35 #漢字url轉碼 36 nick = str(urllib.unquote(nick)) 37 if nick != 1: 38 report_html = get_html(nick) 39 else: 40 report_html = 'nick非法' 41 print '請求 ' + nick + ' 省油寶計划報表' 42 self.send_response(200) 43 self.send_header("Content-type", "text/html") 44 self.send_header("Content-length", len(report_html)) 45 self.end_headers() 46 self.wfile.write(report_html) 47 48 if __name__ == '__main__': 49 try: 50 httpd = SocketServer.TCPServer(("", PORT), Handler) 51 print "dir %s serving at port %s"%(repr(WEBDIR), PORT) 52 #啟動服務器 端進程 53 httpd.serve_forever() 54 except Exception,e: 55 print '異常',e
執行這個程序 web服務程序 就啟動了
在瀏覽器中 輸入 ip:8080/nick 就可以了
