python搭建简易服务器
python搭建简易服务器<div id="cnblogs_post_body">需求分析:
省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪,
每次打开都要缓上半天,甚至浏览器直接挂掉
采用python搭建一个最最简易的 web 服务 请求一个nick
就返回 对应的 报表数据 参数用GET方式传送
调研与实现:
园里没找到靠谱的,google了半天,最终还是成功了。
以下是源码,里面记录了 其中的 一些问题
<div class="cnblogs_code"> 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.com10 11 """12 13 import os14 import sys15 import urllib16 import SimpleHTTPServer 17 import SocketServer18 19 PORT = 808020 WEBDIR = "/home/zhoujiebing/report_web_service"21 from syb_report_html import get_html22 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:]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
页:
[1]