• Python 多线程HTTP服务器


    import http.server as BaseHTTPServer
    import socketserver as SocketServer
    import urllib.parse as urlparse
    import threading
    import re
    import argparse
    import json
    
    
    class apiHandler(BaseHTTPServer.BaseHTTPRequestHandler):
        def do_GET(self):
            self.server.safe_print("Currently %s threads are active." % (threading.activeCount()))
            self.send_response(200)
            self.send_header('Content-type','text/plain')
            self.end_headers()
            # <scheme>://<netloc>/<path>?<query>#<fragment>
            (_, _, urlpath, urlparams, _) = urlparse.urlsplit(self.path)
            response_dict = {}
            response_dict['path'] = urlpath
            response_dict['params'] = urlparams
            response_str = json.dumps(
                response_dict,
                sort_keys=True, 
                indent=4, 
                separators=(',', ': ')
            )
            self.wfile.write(response_str.encode("UTF-8"))
    
    class ThreadedServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
        def __init__(self, *args,**kwargs):
            self.screen_lock = threading.Lock()
            BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)
    
        def safe_print(self,*args,**kwargs):
            try:
                self.screen_lock.acquire()
                print(*args,**kwargs)
            finally:
                self.screen_lock.release()
    
    
    
    if __name__=="__main__":
        parser=argparse.ArgumentParser()
        parser.add_argument('-ip','--address',required=False,help='IP Address for the server to listen on.  Default is 127.0.0.1',default='127.0.0.1')
        parser.add_argument('port',type=int,help='You must provide a TCP Port to bind to')
        args = parser.parse_args()
        
        #Setup the server.
        server = ThreadedServer((args.address, args.port), apiHandler)
     
        #start the server
        print('Server is Ready. http://%s:%s/<command>/<string>' % (args.address, args.port))
        print('[?] - Remember: If you are going to call the api with wget, curl or something else from the bash prompt you need to escape the & with \& \n\n')
        
        while True:
            try:
                server.handle_request()
            except KeyboardInterrupt:
                break
            
        server.safe_print("Control-C hit: Exiting server...")
        server.safe_print("Web API Disabled...")
        server.safe_print("Server has stopped.")
    
    
    • 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
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
  • 相关阅读:
    直方图学习
    Linux文件
    使用【Python+Appium】实现自动化测试
    【无标题】
    Java~大厂面试八股文~强烈推荐视频
    攻防世界-very-easy-sql
    重读经典论文: Mean Value Coordinates for Closed Triangular Meshes
    朵拉钓鱼,快来一起钓鱼
    使用Chrome 开发者工具提取对应的字符串
    【启扬方案】启扬多尺寸安卓屏一体机,助力仓储物料管理系统智能化管理
  • 原文地址:https://blog.csdn.net/itnerd/article/details/125471661