Python to build simple server analysis and implementation
- 2020-04-02 09:35:52
- OfStack
Demand analysis
:
The number of users of fuel-saving treasure has exceeded 6,000, and the original static report has become bloated.
Every time open have to slow up half a day, or even the browser directly hung
Using python to build the simplest web service to request a Nick
The corresponding report data parameters are returned by GET
Research and implementation :
The garden did not find a reliable, Google for a long time, and finally succeeded.
The following is the source code, which records some of these problems
Execute this program and the web service program starts
Enter IP :8080/ Nick in the browser
The number of users of fuel-saving treasure has exceeded 6,000, and the original static report has become bloated.
Every time open have to slow up half a day, or even the browser directly hung
Using python to build the simplest web service to request a Nick
The corresponding report data parameters are returned by GET
Research and implementation :
The garden did not find a reliable, Google for a long time, and finally succeeded.
The following is the source code, which records some of these problems
#! /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):
# Used to set the root directory
os.chdir(WEBDIR)
SimpleHTTPServer.SimpleHTTPRequestHandler.translate_path(self,path)
def do_GET(self):
# Server-side response GET Requested method
# The problem 1 How do I get to the client GET parameter
# I couldn't find it. Finally __dict__ see path There are paths in it, only from the path Extract the parameters
# from path To extract GET parameter
nick = self.path[1:]
# Chinese characters url transcoding
nick = str(urllib.unquote(nick))
if nick != 1:
report_html = get_html(nick)
else:
report_html = 'nick illegal '
print ' request ' + nick + ' Report of saving oil treasure plan '
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)
# Start the server The process of
httpd.serve_forever()
except Exception,e:
print ' abnormal ',e
Execute this program and the web service program starts
Enter IP :8080/ Nick in the browser