Python http.server.handle_request() Examples

The following are 13 code examples of http.server.handle_request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module http.server , or try the search function .
Example #1
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def serve_ready(self):
		server = self.server()  # server is a weakref
		if not server:
			return False

		try:
			self.socket.do_handshake()
		except ssl.SSLWantReadError:
			return False
		except (socket.error, OSError, ValueError):
			self.socket.close()
			server.request_embryos.remove(self)
			return False

		self.socket.settimeout(None)
		server.request_embryos.remove(self)
		server.request_queue.put((self.socket, self.address))
		server.handle_request()
		return True 
Example #2
Source File: server.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def handle_request(self, request_text=None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)


# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server. 
Example #3
Source File: server.py    From Imogen with MIT License 6 votes vote down vote up
def handle_request(self, request_text=None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)


# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server. 
Example #4
Source File: server.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def handle_request(self, request_text=None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)


# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server. 
Example #5
Source File: server.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def handle_request(self, request_text=None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)


# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server. 
Example #6
Source File: test_xmlrpc.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_cgi_get(self):
        with support.EnvironmentVarGuard() as env:
            env['REQUEST_METHOD'] = 'GET'
            # if the method is GET and no request_text is given, it runs handle_get
            # get sysout output
            with captured_stdout(encoding=self.cgi.encoding) as data_out:
                self.cgi.handle_request()

            # parse Status header
            data_out.seek(0)
            handle = data_out.read()
            status = handle.split()[1]
            message = ' '.join(handle.split()[2:4])

            self.assertEqual(status, '400')
            self.assertEqual(message, 'Bad Request') 
Example #7
Source File: plugin_listener.py    From deen with Apache License 2.0 6 votes vote down vote up
def _http_python2(self, listen_ssl=False):
        """Listen for HTTP connections with Python 2."""
        class ThreadingSimpleServer(SocketServer.ThreadingMixIn,
                                    BaseHTTPServer.HTTPServer):
            pass
        server = ThreadingSimpleServer(self.listen_socket,
                                       DeenHTTPRequestHandler)
        os.chdir(self.serving_directory)
        message = 'Serving HTTP at port ' + str(self.listen_port)
        if listen_ssl:
            message += ' (SSL)'
        print(message)
        try:
            while 1:
                sys.stdout.flush()
                server.handle_request()
        except KeyboardInterrupt:
            server.socket.close() 
Example #8
Source File: server.py    From android_universal with MIT License 6 votes vote down vote up
def handle_request(self, request_text=None):
        """Handle a single XML-RPC request passed through a CGI post method.

        If no XML data is given then it is read from stdin. The resulting
        XML-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        if request_text is None and \
            os.environ.get('REQUEST_METHOD', None) == 'GET':
            self.handle_get()
        else:
            # POST data is normally available through stdin
            try:
                length = int(os.environ.get('CONTENT_LENGTH', None))
            except (ValueError, TypeError):
                length = -1
            if request_text is None:
                request_text = sys.stdin.read(length)

            self.handle_xmlrpc(request_text)


# -----------------------------------------------------------------------------
# Self documenting XML-RPC Server. 
Example #9
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_request(self):
		timeout = self.socket.gettimeout()
		if timeout is None:
			timeout = self.timeout
		elif self.timeout is not None:
			timeout = min(timeout, self.timeout)

		try:
			request, client_address = self.request_queue.get(block=True, timeout=timeout)
		except queue.Empty:
			return self.handle_timeout()
		except OSError:
			return None

		if self.verify_request(request, client_address):
			try:
				self.process_request(request, client_address)
			except Exception:
				self.handle_error(request, client_address)
				self.shutdown_request(request)
			except:
				self.shutdown_request(request)
				raise
		else:
			self.shutdown_request(request)
		return None 
Example #10
Source File: advancedhttpserver.py    From AdvancedHTTPServer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_ready(self):
		client_socket, address = self.socket.accept()
		if self.using_ssl:
			client_socket.settimeout(0)
			embryo = _RequestEmbryo(self, client_socket, address)
			embryo.serve_ready()
		else:
			client_socket.settimeout(None)
			self.request_queue.put((client_socket, address))
			self.handle_request() 
Example #11
Source File: spotify-restore.py    From spotify-playlists-2-deezer with MIT License 5 votes vote down vote up
def authorize():
	webbrowser.open('https://connect.deezer.com/oauth/auth.php?' + urllib.parse.urlencode({
		'app_id': APPID,
		'redirect_uri': 'http://127.0.0.1:{}/authfinish'.format(PORT),
		'perms': 'basic_access,manage_library'
	}))

	# Start a simple, local HTTP server to listen for the authorization token... (i.e. a hack).
	server = _AuthorizationServer('127.0.0.1', PORT)
	try:
		while True:
			server.handle_request()
	except _Authorization as auth:
		get_actual_token(auth.access_token) 
Example #12
Source File: test_xmlrpc.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_keepalive_disconnect(self):
        class RequestHandler(http.server.BaseHTTPRequestHandler):
            protocol_version = "HTTP/1.1"
            handled = False

            def do_POST(self):
                length = int(self.headers.get("Content-Length"))
                self.rfile.read(length)
                if self.handled:
                    self.close_connection = True
                    return
                response = xmlrpclib.dumps((5,), methodresponse=True)
                response = response.encode()
                self.send_response(http.HTTPStatus.OK)
                self.send_header("Content-Length", len(response))
                self.end_headers()
                self.wfile.write(response)
                self.handled = True
                self.close_connection = False

        def run_server():
            server.socket.settimeout(float(1))  # Don't hang if client fails
            server.handle_request()  # First request and attempt at second
            server.handle_request()  # Retried second request

        server = http.server.HTTPServer((support.HOST, 0), RequestHandler)
        self.addCleanup(server.server_close)
        thread = threading.Thread(target=run_server)
        thread.start()
        self.addCleanup(thread.join)
        url = "http://{}:{}/".format(*server.server_address)
        with xmlrpclib.ServerProxy(url) as p:
            self.assertEqual(p.method(), 5)
            self.assertEqual(p.method(), 5) 
Example #13
Source File: test_xmlrpc.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_cgi_xmlrpc_response(self):
        data = """<?xml version='1.0'?>
        <methodCall>
            <methodName>test_method</methodName>
            <params>
                <param>
                    <value><string>foo</string></value>
                </param>
                <param>
                    <value><string>bar</string></value>
                </param>
            </params>
        </methodCall>
        """

        with support.EnvironmentVarGuard() as env, \
             captured_stdout(encoding=self.cgi.encoding) as data_out, \
             support.captured_stdin() as data_in:
            data_in.write(data)
            data_in.seek(0)
            env['CONTENT_LENGTH'] = str(len(data))
            self.cgi.handle_request()
        data_out.seek(0)

        # will respond exception, if so, our goal is achieved ;)
        handle = data_out.read()

        # start with 44th char so as not to get http header, we just
        # need only xml
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])

        # Also test the content-length returned  by handle_request
        # Using the same test method inorder to avoid all the datapassing
        # boilerplate code.
        # Test for bug: http://bugs.python.org/issue5040

        content = handle[handle.find("<?xml"):]

        self.assertEqual(
            int(re.search('Content-Length: (\d+)', handle).group(1)),
            len(content))