def __call__(self, request): data = {} response = [] def start_response(status, response_headers, exc_info=None): data["status"] = status data["headers"] = response_headers return response.append app_response = self.wsgi_application( WSGIContainer.environ(request), start_response) response.extend(app_response) body = b("").join(response) if hasattr(app_response, "close"): app_response.close() if not data: raise Exception("WSGI app did not call start_response") status_code = int(data["status"].split()[0]) headers = data["headers"] header_set = set(k.lower() for (k,v) in headers) body = escape.utf8(body) if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "content-type" not in header_set: headers.append(("Content-Type", "text/html; charset=UTF-8")) if "server" not in header_set: headers.append(("Server", "TornadoServer/%s" % tornado.version)) parts = [escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] for key, value in headers: parts.append(escape.utf8(key) + b(": ") + escape.utf8(value) + b("\r\n")) parts.append(b("\r\n")) parts.append(body) request.write(b("").join(parts)) request.finish() self._log(status_code, request)
def deferred_result_available(result, key, ret, request): logger.info('got result for key {key} of {result}', key=key, result=result) ret[key] = result ret = resolve_all_functions(ret, request) if twserver.NOT_DONE_YET != ret: # ok, finally done, let's return it logger.info('writing HTTP result of {ret}', ret=ret) request.write(json.dumps(ret).encode()) request.finish() return
def render_GET(self, request): self.info(f'render GET {request}') request.setResponseCode(200) if self.contentType is not None: request.setHeader(b'Content-Type', self.contentType) request.write(b'') headers = request.getAllHeaders() if ('connection' in headers and headers['connection'] == 'close'): pass self.start(request) return server.NOT_DONE_YET
def render_GET(self, request): self.info('render GET %r', request) request.setResponseCode(200) if hasattr(self, 'contentType'): request.setHeader('Content-Type', self.contentType) request.write('') headers = request.getAllHeaders() if ('connection' in headers and headers['connection'] == 'close'): pass self.start(request) return server.NOT_DONE_YET
def got_streams(streams): if self.stream_id not in streams: self.warning("stream not found for %s@%s", self.url, self.stream_id) request.setResponseCode(http.NOT_FOUND) request.write('') return request.setHeader('Content-Type', self.content_type) request.setResponseCode(http.OK) if request.method == 'HEAD': request.write('') return d_open_stream = threads.deferToThread(streams[self.stream_id].open) d_open_stream.addCallback(stream_opened)
def got_streams(streams): if self.stream_id not in streams: self.warning(f'stream not found for ' f'{self.url}@{self.stream_id}') request.setResponseCode(http.NOT_FOUND) request.write(b'') return request.setHeader(b'Content-Type', self.content_type.encode('ascii')) request.setResponseCode(http.OK) if request.method == b'HEAD': request.write(b'') return d_open_stream = threads.deferToThread(streams[self.stream_id].open) d_open_stream.addCallback(stream_opened)
def render_GET(self, request): self.info(f'render GET {request}') request.setResponseCode(200) if hasattr(self, 'contentType'): request.setHeader(b'Content-Type', self.contentType) request.write(b'') headers = request.getAllHeaders() if ('connection' in headers and headers['connection'] == 'close'): pass if self.requests: if self.streamheader: self.debug('writing streamheader') for h in self.streamheader: request.write(h.data) self.requests.append(request) else: self.parse_pipeline() self.start(request) return server.NOT_DONE_YET
def __call__(self, request): data = {} def start_response(status, response_headers): data["status"] = status data["headers"] = HTTPHeaders(response_headers) body = "".join(self.wsgi_application( WSGIContainer.environ(request), start_response)) if not data: raise Exception("WSGI app did not call start_response") status_code = int(data["status"].split()[0]) headers = data["headers"] body = escape.utf8(body) headers["Content-Length"] = str(len(body)) headers.setdefault("Content-Type", "text/html; charset=UTF-8") headers.setdefault("Server", "TornadoServer/0.1") parts = ["HTTP/1.1 " + data["status"] + "\r\n"] for key, value in headers.items(): parts.append(escape.utf8(key) + ": " + escape.utf8(value) + "\r\n") parts.append("\r\n") parts.append(body) request.write("".join(parts)) request.finish() self._log(status_code, request)
def deferred_result_error(failure, request): logger.failure("Logging an uncaught exception", failure=failure) request.setResponseCode(400) request.write(json.dumps({'error': 'internal error'}).encode()) request.finish() return
def render_HEAD(self, request): self.info(f'render HEAD {request}') request.setResponseCode(200) request.setHeader(b'Content-Type', self.contentType) request.write(b'')
def render_HEAD(self, request): self.info('render HEAD %r', request) request.setResponseCode(200) request.setHeader('Content-Type', self.contentType) request.write('')
def handle(self): self.close_connection = 0 timeout = DEFAULT_TIMEOUT while not self.close_connection: if timeout == 0: break cancel = api.exc_after(timeout, Timeout) try: self.raw_requestline = self.rfile.readline(MAX_REQUEST_LINE) if self.raw_requestline is not None: if len(self.raw_requestline) == MAX_REQUEST_LINE: # Someone sent a request line which is too # large. Be helpful and tell them. self.write_bad_request(414, 'Request-URI Too Long') self.close_connection = True continue except socket.error as e: if e[0] in CONNECTION_CLOSED: self.close_connection = True cancel.cancel() continue except Timeout: self.close_connection = True continue except Exception as e: try: if e[0][0][0].startswith('SSL'): print("SSL Error:", e[0][0]) self.close_connection = True cancel.cancel() continue except Exception as f: print("Exception in ssl test:", f) pass raise e cancel.cancel() if not self.raw_requestline or not self.parse_request(): self.close_connection = True continue self.set_response_code(None, 200, None) request = Request(self, self.command, self.path, self.headers) request.set_header('Server', self.version_string()) request.set_header('Date', self.date_time_string()) try: timeout = int(request.get_header('keep-alive', timeout)) except TypeError as ValueError: pass try: try: try: self.server.site.handle_request(request) except ErrorResponse as err: request.response(code=err.code, reason_phrase=err.reason, headers=err.headers, body=err.body) finally: # clean up any timers that might have been left around by the handling code #api.get_hub().cancel_timers(api.getcurrent()) pass # throw an exception if it failed to write a body if not request.response_written(): raise NotImplementedError( "Handler failed to write response to request: %s" % request) if not hasattr(self, '_cached_body'): try: request.read_body() ## read & discard body except: pass except socket.error as e: # Broken pipe, connection reset by peer if e[0] in CONNECTION_CLOSED: #print "Remote host closed connection before response could be sent" pass else: raise except Exception as e: self.server.log_message( "Exception caught in HttpRequest.handle():\n") self.server.log_exception(*sys.exc_info()) if not request.response_written(): request.response(500) request.write('Internal Server Error') self.close() raise e # can't do a plain raise since exc_info might have been cleared self.close()