aboutsummaryrefslogtreecommitdiff
blob: 51d49b70be913c0d161142599e8ad7672ba0cbb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
    server.py
    ~~~~~~~~~
    
    test server
    
    :copyright: (c) 2013 by Jauhien Piatlicki
    :license: GPL-2, see LICENSE for more details.
"""

import os
import threading

from g_sorcery.compatibility import py2k

if py2k:
    from SocketServer import TCPServer as HTTPServer 
    from SimpleHTTPServer import SimpleHTTPRequestHandler
else:
    from http.server import HTTPServer
    from http.server import SimpleHTTPRequestHandler

def HTTPRequestHandlerGenerator(direct):

    class HTTPRequestHandler(SimpleHTTPRequestHandler, object):
        directory = direct

        def __init__(self, request, client_address, server):
            super(HTTPRequestHandler, self).__init__(request, client_address, server)

        def translate_path(self, path):
            return os.path.join(self.directory, path[1:])

    return HTTPRequestHandler

    
class Server(threading.Thread):
    def __init__(self, directory, port=8080):
        super(Server, self).__init__()
        HTTPServer.allow_reuse_address = True
        server_address = ('127.0.0.1', port)
        self.httpd = HTTPServer(server_address, HTTPRequestHandlerGenerator(directory))
    
    def run(self):
        self.httpd.serve_forever()

    def shutdown(self):
        self.httpd.shutdown()