[t:/]$ 지식_

귀찮아 웹서버

2019/01/07

자세한 설명은 생략한다.

1. was.py

#-*- coding: utf-8 -*-
import sys

from Queue import Queue
from SocketServer import ThreadingMixIn, TCPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

import threading, socket

from log import log, WARN, INFO

reload(sys)
sys.setdefaultencoding('utf-8')

class ThreadPoolMixIn(ThreadingMixIn):
    allow_reuse_address = True

    def __init__(self, numThread):
        self.numThreads = numThread

        self.requests = Queue(self.numThreads)

        for x in range(self.numThreads):
            t = threading.Thread(target = self.process_request_thread, args=((x,)))
            t.setDaemon(1)
            t.start()

    def process_request(self, request, client_address):
        self.requests.put((request, client_address))

    def process_request_thread(self, x):
    log(INFO, "쓰레드 시작 = " + str(x))
        while True:
            ThreadingMixIn.process_request_thread(self, *self.requests.get())

    def handle_request(self):
        try:
            request, client_address = self.get_request()
        except socket.error:
            return
        if self.verify_request(request, client_address):
            self.requests.put((request, client_address))

class ThreadingSimpleServer(ThreadPoolMixIn, TCPServer):
    def __init__(self, server_address, RequestHandlerClass, numThread, bind_and_activate=True):
        ThreadPoolMixIn.__init__(self, numThread)
        TCPServer.__init__(self, server_address, RequestHandlerClass)

class GET_handler(BaseHTTPRequestHandler):

    api_map = {}

    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json; charset=utf-8')
        self.end_headers()

    def log_request(self, ret_code):
        return

    def _proc_404(self, self2):
    headers = [ ('Content-type', 'application/json; charset=utf-8') ]
    body = '{ "ret" : 1004, "msg" : "페이지가 없어요", "path" : %s}' % (self.path)
    return 404, headers, body

    def do_GET(self):

        args = {}
        args_str = self.path.split('?', 1)

        proc = GET_handler.api_map.get(args_str[0], self._proc_404)

    if len(args_str) == 2:
        args_arr = args_str[1].split('&')
        for arg in args_arr:
        arg_one = arg.split('=')
        if len(arg_one) == 2:
            args[arg_one[0]] = arg_one[1]

    self.args = args
    ret, headers, body = proc(self)

        self.send_response(ret)
    for k, v in headers:
            self.send_header(k, v)

        self.end_headers()
        self.wfile.write(body)
        self.wfile.flush()

    log(INFO, '%s - %s - %d' % (self.client_address[0], self.path, ret))

# was 시작
# api_map = { path : 함수 }
def run_httpd(HandlerClass = GET_handler,
            ServerClass = ThreadingSimpleServer,
            protocol="HTTP/1.0", port = 8009, numThread = 30, api_map = {}):

        server_address = ('', port)

        HandlerClass.protocol_version = protocol
    HandlerClass.api_map = api_map
        httpd = ServerClass(server_address, HandlerClass, numThread)

        sa = httpd.socket.getsockname()
        log(INFO, 'HTTP 시작 ' + sa[0] + ' port ' + str(sa[1]))
        httpd.serve_forever()

def main():
    def _r1(req):
        print req.args
        return 200, [], 'ee'
    def _r2(req):
        print req.args
        return 200, [], 'qq'

    run_httpd(api_map = {'/a' : _r1, '/b' : _r2 })

if __name__ == '__main__':
    main()

2. log.py


#-*- coding: utf-8 -*-
import os
import sys
import datetime
from threading import Lock

lock = Lock()

INFO = 0
WARN = 1

lev = {}
lev[INFO] = 'INFO'
lev[WARN] = 'WARN'

print_log_level = WARN 

def log(log_level, msg):

    if print_log_level >= log_level:
    with lock:
            sys.stderr.write('[%s] %s::%s\n' % (lev.get(log_level, '----'), datetime.datetime.now().strftime('%Y%m%d-%H%M%S'), msg))

def main():
    log(WARN, '워닝 테스트')
    log(INFO, '인포 테스트')

if __name__ == '__main__':
    main()








[t:/] is not "technology - root". dawnsea, rss