def serve_file(client, request): if request.path == '/' and FileStorage.BASE_FILE is not None: request.path = '/' + str(FileStorage.BASE_FILE) filepath = FileStorage.get_file_path(request.path) # File not found if not os.path.exists(filepath): client.send(Response(code=404, content='<h1>Page not found</h1>')._compile()) client.flush() Log.error('File not found {}'.format(filepath)) return # Create response response = Response(code=200, headers=FileStorage.create_headers(request.path)) # Serve directory if os.path.isdir(filepath): response.set_content(FileStorage.serve_directory(filepath, request.path)) response.headers['Content-Type'] = 'text/html; charset=utf-8' else: response.set_content(file(filepath, 'rb').read()) # Send file client.send(response._compile()) client.flush()
def client_handler(self, client): """ Handle client and trigger http_request handler """ # Prepare request request = Request.parse(client.message) Log.info('Request: {}'.format(request)) # Handle and process HttpServer.HTTP_REQUEST_HANDLER(client=client, request=request)
def client_handler(self, client): """ Handle client and trigger http_request handler """ # Prepare request request = Request.parse(client.message) Log.info('Request: {}'.format(request)) # Handle and process HttpServer.HTTP_REQUEST_HANDLER( client=client, request=request )
def _connection(self, *args, **kwargs): """ Creation socket :param args: :param kwargs: :return: """ try: # Create socket self.conn = socket.socket(*args, **kwargs) self.conn.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind address self.conn.bind(self.addr) # Listen clients self.conn.listen(self.clients) except socket.error as e: Log.critical(e) sys.exit()
def serve(args=None): arguments = args or argv path = os.getcwd() srv_conf = { 'host': '127.0.0.1', 'port': '8008' } if len(arguments) > 1 and os.path.exists(os.path.abspath(arguments[1])): path = os.path.abspath(arguments[1]) if not os.path.isdir(os.path.abspath(arguments[1])): FileStorage.BASE_FILE = os.path.basename(arguments[1]) path = os.path.dirname(os.path.abspath(arguments[1])) if len(arguments) > 2: srv_data = arguments[2].strip().split(':') srv_host = srv_data[0] or srv_conf['host'] srv_port = srv_conf['port'] if len(srv_data) > 1: srv_port = srv_data[1] if srv_host == '0': srv_host = srv_conf['host'] srv_conf['host'] = srv_host srv_conf['port'] = srv_port Log.debug('Selected folder: {}'.format(path)) Log.debug('Should be available on http://{}:{}/'.format(srv_conf['host'], srv_conf['port'])) # Setup filestorage FileStorage.BASE_DIR = path FileStorage.set_request_callback('serve_file') # Setup Http server HttpServer.set_request_handler(FileStorage) HttpServer( host=srv_conf['host'], port=int(srv_conf['port']), clients=99 )
def _loop(self): """ Main loop :return: """ if self.conn is None: Log.critical('Server is not initialized') sys.exit() Log.info('Server listen {}:{}'.format(self.addr[0], self.addr[1])) Log.debug('Waiting maximum {} clients'.format(self.clients)) try: # Wait for a new clients while True: # New client accepted conn, addr = self.conn.accept() if self.LOG_CLIENTS: Log.info('New client connected {}:{}'.format(addr[0], addr[1])) # Read message message = self._read(conn) # Dump request if self.DUMP_REQUEST and self.LOG_CLIENTS: Log.info('Request received:\n{}\n'.format(message)) # Handle client client = self.CLIENT_OBJECT(conn, addr, message) try: self.client_handler(client) except Exception as e: Log.warning('Client error: {}'.format(e.message)) self.client_error_handler(e) # Dump response if self.DUMP_RESPONSE: Log.info('Response will send:\n{}\n'.format(''.join(client.buffer))) if self.AUTOFLUSH_RESPONSE is True: client.flush() continue # Dump response if self.DUMP_RESPONSE: Log.info('Response will send:\n{}\n'.format(''.join(client.buffer))) # Flush response if self.AUTOFLUSH_RESPONSE is True: client.flush() except KeyboardInterrupt: # Shutting down server self._shutdown() Log.info('Server is down!') sys.exit() except Exception as e: # Shutting down server Log.error(e) # Exit or restart if self.RESTART_ON_ERROR is False: Log.warning('Server is down!') sys.exit() else: Log.info('Server is now restarting') self._shutdown(e)
def _loop(self): """ Main loop :return: """ if self.conn is None: Log.critical('Server is not initialized') sys.exit() Log.info('Server listen {}:{}'.format(self.addr[0], self.addr[1])) Log.debug('Waiting maximum {} clients'.format(self.clients)) try: # Wait for a new clients while True: # New client accepted conn, addr = self.conn.accept() if self.LOG_CLIENTS: Log.info('New client connected {}:{}'.format( addr[0], addr[1])) # Read message message = self._read(conn) # Dump request if self.DUMP_REQUEST and self.LOG_CLIENTS: Log.info('Request received:\n{}\n'.format(message)) # Handle client client = self.CLIENT_OBJECT(conn, addr, message) try: self.client_handler(client) except Exception as e: Log.warning('Client error: {}'.format(e.message)) self.client_error_handler(e) # Dump response if self.DUMP_RESPONSE: Log.info('Response will send:\n{}\n'.format(''.join( client.buffer))) if self.AUTOFLUSH_RESPONSE is True: client.flush() continue # Dump response if self.DUMP_RESPONSE: Log.info('Response will send:\n{}\n'.format(''.join( client.buffer))) # Flush response if self.AUTOFLUSH_RESPONSE is True: client.flush() except KeyboardInterrupt: # Shutting down server self._shutdown() Log.info('Server is down!') sys.exit() except Exception as e: # Shutting down server Log.error(e) # Exit or restart if self.RESTART_ON_ERROR is False: Log.warning('Server is down!') sys.exit() else: Log.info('Server is now restarting') self._shutdown(e)