def wrapper(request, response): req = yield request.read() datas = yield application(WSGIContainer.environ(req), functools.partial(start_response, response)) for data in datas: response.write(data) response.close()
def __init__(self, tornado_req, site_conf): super(TornadoRequest, self).__init__( WSGIContainer.environ(tornado_req) ) self._native_request = tornado_req self.site = site_conf
def get(self): from tornado.wsgi import WSGIContainer from django.core.handlers.wsgi import WSGIRequest, get_script_name import urllib environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
def get(self): from tornado.wsgi import WSGIContainer from django.core.handlers.wsgi import WSGIRequest, get_script_name import urllib environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
def get(self, *args, **kwargs): # type: (*Any, **Any) -> None environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] # type: List[http.cookie.SimpleCookie] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
def get(self, *args, **kwargs): # type: (*Any, **Any) -> None environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return finally: signals.request_finished.send(sender=self.__class__) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] # type: List[http.cookie.SimpleCookie] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
async def convert_tornado_request_to_django_request(self) -> HttpRequest: # This takes the WSGI environment that Tornado received (which # fully describes the HTTP request that was sent to Tornado) # and pass it to Django's WSGIRequest to generate a Django # HttpRequest object with the original Tornado request's HTTP # headers, parameters, etc. environ = WSGIContainer.environ(self.request) environ["PATH_INFO"] = urllib.parse.unquote(environ["PATH_INFO"]) # Django WSGIRequest setup code that should match logic from # Django's WSGIHandler.__call__ before the call to # `get_response()`. set_script_prefix(get_script_name(environ)) await sync_to_async( lambda: signals.request_started.send(sender=self.__class__), thread_sensitive=True)() self._request = WSGIRequest(environ) # We do the import during runtime to avoid cyclic dependency from zerver.lib.request import RequestNotes # Provide a way for application code to access this handler # given the HttpRequest object. RequestNotes.get_notes( self._request).tornado_handler_id = self.handler_id return self._request
def add_tornado_request_to_notification(self, event: bugsnag.Event): if not hasattr(self, "request"): return event.request = self.request request_tab = { 'method': self.request.method, 'path': self.request.path, 'GET': parse_qs(self.request.query), 'POST': {}, 'url': self.request.full_url(), } # type: Dict[str, Any] try: if (len(self.request.body) > 0): headers = self.request.headers body = self.request.body.decode('utf-8', 'replace') is_json = is_json_content_type(headers.get('Content-Type', '')) if is_json and request_tab["method"] == "POST": request_tab["POST"] = json.loads(body) else: request_tab["POST"] = self.request.body_arguments except Exception: pass event.add_tab("request", request_tab) if bugsnag.configure().send_environment: env = WSGIContainer.environ(self.request) event.add_tab("environment", env)
def get(self): # based on wsgi.WSGIContainer # TODO: handle iterator response data = {} response = [] def start_response(status, response_headers, exc_info=None): data["status"] = status data["headers"] = response_headers return response.append app_response = yield self.executor.submit( self.wsgi_application, WSGIContainer.environ(self.request), start_response) response.extend(app_response) body = b"".join(response) if hasattr(app_response, "close"): yield self.executor.submit(app_response.close) if not data: raise Exception("WSGI app did not call start_response") status_code, reason = data["status"].split(None, 1) status_code = int(status_code) headers = data["headers"] body = escape.utf8(body) self.set_status(status_code, reason) for key, value in headers: self.set_header(key, value) self.write(body)
def get_django_request(self): request = \ WSGIRequest(WSGIContainer.environ(self.request)) request.session = self.get_django_session() if self.current_user: request.user = self.current_user else: request.user = auth.models.AnonymousUser() return request
def get_django_request(self): request = \ WSGIRequest(WSGIContainer.environ(self.request)) request.session = self.get_django_session() if self.current_user: request.user = self.current_user else: request.user = auth.models.AnonymousUser() return request
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_app( WSGIContainer.environ(request), start_response) try: response.extend(app_response) body = b"".join(response) finally: if hasattr(app_response, "close"): app_response.close() if not data: raise Exception("WSGI app did not call start_response") status_code, reason = data["status"].split(' ', 1) status_code = int(status_code) headers = data["headers"] header_set = set(k.lower() for (k, v) in headers) body = escape.utf8(body) if HEAD_END in body: body = body.replace(HEAD_END, self.script + HEAD_END) if status_code != 304: if "content-type" not in header_set: headers.append(( "Content-Type", "application/octet-stream; charset=UTF-8" )) if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "server" not in header_set: headers.append(("Server", "LiveServer")) start_line = httputil.ResponseStartLine( "HTTP/1.1", status_code, reason ) header_obj = httputil.HTTPHeaders() for key, value in headers: if key.lower() == 'content-length': value = str(len(body)) header_obj.add(key, value) request.connection.write_headers(start_line, header_obj, chunk=body) request.connection.finish() self._log(status_code, request)
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_app( WSGIContainer.environ(request), start_response) try: response.extend(app_response) body = b"".join(response) finally: if hasattr(app_response, "close"): app_response.close() if not data: raise Exception("WSGI app did not call start_response") status_code, reason = data["status"].split(' ', 1) status_code = int(status_code) headers = data["headers"] header_set = set(k.lower() for (k, v) in headers) body = escape.utf8(body) if HEAD_END in body: body = body.replace(HEAD_END, self.script + HEAD_END) if status_code != 304: if "content-type" not in header_set: headers.append(( "Content-Type", "application/octet-stream; charset=UTF-8" )) if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "server" not in header_set: headers.append(("Server", "LiveServer")) start_line = httputil.ResponseStartLine( "HTTP/1.1", status_code, reason ) header_obj = httputil.HTTPHeaders() for key, value in headers: if key.lower() == 'content-length': value = str(len(body)) header_obj.add(key, value) request.connection.write_headers(start_line, header_obj, chunk=body) request.connection.finish() self._log(status_code, request)
def get(self): from tornado.wsgi import HTTPRequest, WSGIContainer from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT import urllib environ = WSGIContainer.environ(self.request) environ["PATH_INFO"] = urllib.unquote(environ["PATH_INFO"]) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(base.get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response: return # Apply response middleware for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) finally: signals.request_finished.send(sender=self.__class__) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = "UNKNOWN STATUS CODE" status = "%s %s" % (response.status_code, status_text) self.set_status(response.status_code) for h in response.items(): self.set_header(h[0], h[1]) """ if not hasattr(self, "_new_cookies"): self._new_cookies = [] self._new_cookies.append(response.cookies) """ # Tornado 2.3 has changed the _new_cookies methods. Its not an array. # revert back to old method for c in response.cookies.values(): self.set_header("Set-Cookie", str(c.output(header=""))) self.write(response.content) self.finish()
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) try: response.extend(app_response) body = b"".join(response) finally: 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) body = body.replace( b'</head>', b'<script src="/livereload.js"></script></head>' ) if status_code != 304: 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", "livereload-tornado")) parts = [escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] for key, value in headers: if key.lower() == 'content-length': value = str(len(body)) 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 __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) try: response.extend(app_response) body = b"".join(response) finally: 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) body = body.replace( b'</head>', b'<script src="/livereload.js"></script></head>' ) if status_code != 304: 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", "livereload-tornado")) parts = [escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] for key, value in headers: if key.lower() == 'content-length': value = str(len(body)) 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 get(self) : from tornado.wsgi import HTTPRequest, WSGIContainer from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT import urllib environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(base.get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response : return # Apply response middleware for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) finally: signals.request_finished.send(sender=self.__class__) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' % (response.status_code, status_text) self.set_status(response.status_code) for h in response.items() : self.set_header(h[0], h[1]) for c in response.cookies.values(): self.set_header('Set-Cookie', str(c.output(header=''))) """ if hasattr(self, "_new_cookies"): print self._new_cookies self._new_cookies = response.cookies """ self.write(response.content) self.finish()
def __call__(self, request): parts = [] parts_append = parts.append base_header = strftime('\r\nDate: %a, %d %b %Y %H:%M:%S GMT', gmtime()) + '\r\nServer: tornado\r\n' if not request.supports_http_1_1(): if request.headers.get('Connection', '').lower() == 'keep-alive': base_header += 'Connection: Keep-Alive\r\n' def start_response(status, response_headers, exc_info=None): parts_append(utf8('HTTP/1.1 ' + status + base_header)) for key, value in response_headers: parts_append(utf8(key + ': ' + value + '\r\n')) parts_append(self.new_line) return None environ = WSGIContainer.environ(request) environ['wsgi.multiprocess'] = False # Some EvalException middleware fails if set to True app_response = self.wsgi_application(environ, start_response) if not parts: raise Exception('WSGI app did not call start_response') if request.method != 'HEAD': parts.extend(app_response) if hasattr(app_response, 'close'): app_response.close() app_response = None if hasattr(request, "connection"): # Now that the request is finished, clear the callback we # set on the IOStream (which would otherwise prevent the # garbage collection of the RequestHandler when there # are keepalive connections) request.connection.stream.set_close_callback(None) request.write(self.empty_string.join(parts)) try: request.finish() except IOError as e: self.logger.error('Exception when writing response: %s', str(e))
def get(self) : from tornado.wsgi import HTTPRequest, WSGIContainer from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT import urllib environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO']) request = WSGIRequest(environ) request._tornado_handler = self set_script_prefix(base.get_script_name(environ)) signals.request_started.send(sender=self.__class__) try: response = self.get_response(request) if not response : return # Apply response middleware for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) finally: signals.request_finished.send(sender=self.__class__) try: status_text = STATUS_CODE_TEXT[response.status_code] except KeyError: status_text = 'UNKNOWN STATUS CODE' status = '%s %s' % (response.status_code, status_text) self.set_status(response.status_code) for h in response.items() : self.set_header(h[0], h[1]) if not hasattr(self, "_new_cookies"): self._new_cookies = [] self._new_cookies.append(response.cookies) self.write(response.content) self.finish()
def convert_tornado_request_to_django_request(self) -> HttpRequest: # This takes the WSGI environment that Tornado received (which # fully describes the HTTP request that was sent to Tornado) # and pass it to Django's WSGIRequest to generate a Django # HttpRequest object with the original Tornado request's HTTP # headers, parameters, etc. environ = WSGIContainer.environ(self.request) environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO']) # Django WSGIRequest setup code that should match logic from # Django's WSGIHandler.__call__ before the call to # `get_response()`. set_script_prefix(get_script_name(environ)) signals.request_started.send(sender=self.__class__) request = WSGIRequest(environ) # Provide a way for application code to access this handler # given the HttpRequest object. request._tornado_handler = self return request
def __init__(self, *args, **kwargs): _RequestHandler.__init__(self, *args, **kwargs) self.environ = WSGIContainer.environ(self.request)
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) try: response.extend(app_response) body = b"".join(response) finally: 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 status_code != 304: 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)) # try: # if request.method.lower() != GET: # _cookies = Cookie.SimpleCookie() # Django session cookies are set at the django level, but # tornado-specific cookies are appended here. # token = request.cookies[djsettings.CSRF_COOKIE_NAME] # if token: # _cookies[settings.XSRF_TOKEN] = token.value # TODO Change when we add more contexts # _cookies[settings.CONTEXT_COOKIE] = settings.DEFAULT_CONTEXT # for c in _cookies.output(sep='\t').split('\t'): # k, v = c.split(': ') # headers.append((k, v + '; Path=/')) # except ValueError as e: # logging.getLogger("ef5").error("A Value is either missing or invalid: {0}".format(e)) # except Exception as e: # logging.getLogger("ef5").error("An unknown error occurred: {0} with stacktrace {1}".format(e, traceback.format_exc())) 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 environ(request: httputil.HTTPServerRequest) -> Dict[Text, Any]: environ = WSGIContainer.environ(request) environ['RAW_URI'] = request.path return environ
def __init__(self, tornado_request_type, cookies=None): self._tornado_request = tornado_request_type self._cookies = cookies environ = WSGIContainer.environ(tornado_request_type) super(DjangoRequest,self).__init__(environ) self.tornado_to_django()
def __init__(self, *args, **kwargs): _RequestHandler.__init__(self, *args, **kwargs) self.environ = WSGIContainer.environ(self.request)
def wrapper(request, response): req = yield request.read() datas = yield application(WSGIContainer.environ(req), partial(start_response, response)) for data in datas: response.write(data) response.close()
def wrapper(request, response): req = yield request.read() for data in application(WSGIContainer.environ(req), functools.partial(start_response, response)): response.write(data) response.close()
def use_scope() -> dict[str, Any]: """Get the current WSGI environment dictionary""" return WSGIContainer.environ(use_request())