python搭建简易服务器分析与实现

yipeiwu_com6年前服务器
需求分析
省油宝用户数 已经破了6000,原有的静态报表 已经变得臃肿不堪,
每次打开都要缓上半天,甚至浏览器直接挂掉
采用python搭建一个最最简易的 web 服务 请求一个nick
就返回 对应的 报表数据 参数用GET方式传送

调研与实现
园里没找到靠谱的,google了半天,最终还是成功了。
以下是源码,里面记录了 其中的 一些问题
复制代码 代码如下:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: zhoujiebin
@contact: zhoujiebing@maimiaotech.com
@date: 2012-12-14 15:25
@version: 0.0.0
@license: Copyright maimiaotech.com
@copyright: Copyright maimiaotech.com
"""
import os
import sys
import urllib
import SimpleHTTPServer
import SocketServer
PORT = 8080
WEBDIR = "/home/zhoujiebing/report_web_service"
from syb_report_html import get_html
class Handler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def translate_path(self, path):
#用于设定根目录
os.chdir(WEBDIR)
SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path)
def do_GET(self):
#服务器端响应GET请求的方法
#问题1 如何拿到客户端的GET参数
#我找半天没找到,最后__dict__看到path里有路径,只能从路径里 提取参数了
#从path中提取 GET参数
nick = self.path[1:]
#汉字url转码
nick = str(urllib.unquote(nick))
if nick != 1:
report_html = get_html(nick)
else:
report_html = 'nick非法'
print '请求 ' + nick + ' 省油宝计划报表'
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-length", len(report_html))
self.end_headers()
self.wfile.write(report_html)
if __name__ == '__main__':
try:
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "dir %s serving at port %s"%(repr(WEBDIR), PORT)
#启动服务器 端进程
httpd.serve_forever()
except Exception,e:
print '异常',e

执行这个程序 web服务程序 就启动了
在浏览器中 输入 ip:8080/nick 就可以了

相关文章

浅析linux下apache服务器的配置和管理

一、两个重要目录:Apache有两个重要的目录:1、配置目录/etc/httpd/conf;2、文档目录/var/www: 二、两种配置模式:Apache在Fedora下的两种配置方式:...

使用Python来编写HTTP服务器的超级指南

使用Python来编写HTTP服务器的超级指南

首先,到底什么是网络服务器? 简而言之,它是在物理服务器上搭建的一个网络连接服务器(networking server),永久地等待客户端发送请求。当服务器收到请求之后,它会生成响应...

python登录pop3邮件服务器接收邮件的方法

本文实例讲述了python登录pop3邮件服务器接收邮件的方法。分享给大家供大家参考。具体实现方法如下: import poplib, string PopServerName =...

python 与服务器的共享文件夹交互方法

需求:从服务器拷贝照片到本地,然后再从本地照片筛选照片。 问题:从服务器拷贝到照片本地,太慢,速度只有20~30K,不能忍。 然后想到,利用python直接从服务器的共享文件夹筛选照片。...

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

环境搭建 软件: xampp   下载地址:https://www.apachefriends.org/zh_cn/index.html (建议使用迅雷下载,不然速度...