def finish(self): Request.finish(self) host = self.getHost() if self.hydrus_response_context is not None: status_text = HydrusData.ToUnicode( self.hydrus_response_context.GetStatusCode()) elif hasattr(self, 'code'): status_text = str(self.code) else: status_text = '200' message = str(host.port) + ' ' + HydrusData.ToUnicode( self.method ) + ' ' + HydrusData.ToUnicode( self.path ) + ' ' + status_text + ' in ' + HydrusData.ConvertTimeDeltaToPrettyString( time.clock() - self.start_time) HydrusData.Print(message)
def putDone( cls, result: None, # pylint: disable=unused-argument request: TwistedRequest) -> None: request.setResponseCode(201) request.setHeader(b'Content-Type', b'text/plain; charset=UTF-8') request.write(b'Artifact stored\n') request.finish()
def putFailed(cls, fail: Failure, request: TwistedRequest) -> None: ex = fail.value if isinstance(ex, ValueError): request.setResponseCode(415) request.setHeader(b'Content-Type', b'text/plain; charset=UTF-8') request.write((f'{ex}\n').encode()) request.finish() else: request.processingFailed(fail)
def finish(self): """Called when all response data has been written to this Request. Overrides twisted.web.server.Request.finish to record the finish time and do logging. """ self.finish_time = time.time() Request.finish(self) if not self._is_processing: with PreserveLoggingContext(self.logcontext): self._finished_processing()
def finish(self): """ Event received when the request is finished, for WebsocketTransport only. Pass that event to the transport, for processing extensions. """ if self.transport.__class__ == WebsocketTransport: self.transport.finish() if not self._disconnected: ## FIXME: use notifyFinished? Request.finish(self)
def _return_html_error(code: int, msg: str, request: Request): """Sends an HTML error page""" body = HTML_ERROR_TEMPLATE.format(code=code, msg=html.escape(msg)).encode("utf-8") request.setResponseCode(code) request.setHeader(b"Content-Type", b"text/html; charset=utf-8") request.setHeader(b"Content-Length", b"%i" % (len(body), )) request.write(body) try: request.finish() except RuntimeError as e: logger.info("Connection disconnected before response was written: %r", e)
def finish(self) -> None: """Called when all response data has been written to this Request. Overrides twisted.web.server.Request.finish to record the finish time and do logging. """ self.finish_time = time.time() Request.finish(self) if self._opentracing_span: self._opentracing_span.log_kv({"event": "response sent"}) if not self._is_processing: assert self.logcontext is not None with PreserveLoggingContext(self.logcontext): self._finished_processing()
def render_GET(self, request: TwistedRequest) -> object: presenter = self.presenter depth = len(request.prepath) - 1 styleURL = '../' * depth + styleRoot.relativeURL request.write(b'<!DOCTYPE html>\n') request.write(xhtml.html[ xhtml.head[fixedHeadItems, presenter.headItems(), xhtml.title[f'Report: {self.fileName}']].present( styleURL=styleURL), xhtml.body[xhtml.div(class_='body')[presenter.presentBody()]]]. flattenXML().encode()) request.finish() return NOT_DONE_YET
def finish( self ): Request.finish( self ) host = self.getHost() status_text = '200' if self.hydrus_response_context is not None: status_text = HydrusData.ToUnicode( self.hydrus_response_context.GetStatusCode() ) message = str( host.port ) + ' ' + HydrusData.ToUnicode( self.method ) + ' ' + HydrusData.ToUnicode( self.path ) + ' ' + status_text + ' in ' + HydrusData.ConvertTimeDeltaToPrettyString( time.clock() - self.start_time ) HydrusData.Print( message )
def finish_request(request: Request) -> None: """Finish writing the response to the request. Twisted throws a RuntimeException if the connection closed before the response was written but doesn't provide a convenient or reliable way to determine if the connection was closed. So we catch and log the RuntimeException You might think that ``request.notifyFinish`` could be used to tell if the request was finished. However the deferred it returns won't fire if the connection was already closed, meaning we'd have to have called the method right at the start of the request. By the time we want to write the response it will already be too late. """ try: request.finish() except RuntimeError as e: logger.info("Connection disconnected before response was written: %r", e)
def _return_json(json_obj: Any, request: Request): json_bytes = json.dumps(json_obj).encode("utf-8") request.setHeader(b"Content-Type", b"application/json") request.setHeader(b"Content-Length", b"%d" % (len(json_bytes), )) request.setHeader(b"Cache-Control", b"no-cache, no-store, must-revalidate") request.setHeader(b"Access-Control-Allow-Origin", b"*") request.setHeader(b"Access-Control-Allow-Methods", b"GET, POST, PUT, DELETE, OPTIONS") request.setHeader( b"Access-Control-Allow-Headers", b"Origin, X-Requested-With, Content-Type, Accept, Authorization", ) request.write(json_bytes) try: request.finish() except RuntimeError as e: logger.info("Connection disconnected before response was written: %r", e)
async def render(f: AsyncRenderer[Res], self: Res, request: Request) -> None: request.setHeader("Content-Type", "application/json") try: result = await f(self, request) request.write(dict_to_json_bytes(result)) except MatrixRestError as e: request.setResponseCode(e.httpStatus) request.write( dict_to_json_bytes({ "errcode": e.errcode, "error": e.error })) except Exception: logger.exception("Request processing failed") request.setResponseCode(500) request.write( dict_to_json_bytes({ "errcode": "M_UNKNOWN", "error": "Internal Server Error" })) request.finish()
def finish(self): """Called when all response data has been written to this Request. Overrides twisted.web.server.Request.finish to record the finish time and do logging. """ from skywalking.trace.carrier import Carrier from skywalking.trace.context import get_context from skywalking.trace import tags from skywalking.trace.tags import Tag from skywalking import Layer, Component context = get_context() carrier = Carrier() for item in carrier: val = self.getAllHeaders().get(item.key.encode()) if val is not None: item.val = val.decode() with context.new_entry_span(op=self.path.decode(), carrier=carrier) as span: span.layer = Layer.Http span.component = Component.General span.tag(Tag(key=tags.HttpMethod, val=self.method.decode())) span.tag(Tag(key=tags.HttpUrl, val=self.uri.decode())) span.tag(Tag(key=tags.HttpStatus, val=self.code, overridable=True)) if self.code >= 400: span.error_occurred = True logger.info(self.code) logger.info(self.getClientAddress()) self.finish_time = time.time() Request.finish(self) if not self._is_processing: assert self.logcontext is not None with PreserveLoggingContext(self.logcontext): self._finished_processing()
def finish(self): rv = Request.finish(self) # Some requests, like those for static files, don't have store store = getattr(self, 'store', None) if store: # Roll back and then commit, so that no transaction # is left open between requests. store.rollback() store.commit() # Some use cases involve setting store.request in # getRequestStore, so remove request.store here to # avoid a circular reference GC. del self.store return rv
async def _async_render_POST(self, request: Request) -> None: try: try: # TODO: we should really validate that this gives us a dict, and # not some other json value like str, list, int etc # json.loads doesn't allow bytes in Python 3.5 body: JsonDict = json_decoder.decode( request.content.read().decode("UTF-8")) except ValueError: request.setResponseCode(HTTPStatus.BAD_REQUEST) request.write( dict_to_json_bytes({ "errcode": "M_BAD_JSON", "error": "Malformed JSON" })) request.finish() return missing = [k for k in ("threepid", "mxid") if k not in body] if len(missing) > 0: request.setResponseCode(HTTPStatus.BAD_REQUEST) msg = "Missing parameters: " + (",".join(missing)) request.write( dict_to_json_bytes({ "errcode": "M_MISSING_PARAMS", "error": msg })) request.finish() return threepid = body["threepid"] mxid = body["mxid"] if "medium" not in threepid or "address" not in threepid: request.setResponseCode(HTTPStatus.BAD_REQUEST) request.write( dict_to_json_bytes({ "errcode": "M_MISSING_PARAMS", "error": "Threepid lacks medium / address", })) request.finish() return # We now check for authentication in two different ways, depending # on the contents of the request. If the user has supplied "sid" # (the Session ID returned by Sydent during the original binding) # and "client_secret" fields, they are trying to prove that they # were the original author of the bind. We then check that what # they supply matches and if it does, allow the unbind. # # However if these fields are not supplied, we instead check # whether the request originated from a homeserver, and if so the # same homeserver that originally created the bind. We do this by # checking the signature of the request. If it all matches up, we # allow the unbind. # # Only one method of authentication is required. if "sid" in body and "client_secret" in body: sid = body["sid"] client_secret = body["client_secret"] if not is_valid_client_secret(client_secret): request.setResponseCode(HTTPStatus.BAD_REQUEST) request.write( dict_to_json_bytes({ "errcode": "M_INVALID_PARAM", "error": "Invalid client_secret provided", })) request.finish() return valSessionStore = ThreePidValSessionStore(self.sydent) try: s = valSessionStore.getValidatedSession(sid, client_secret) except (IncorrectClientSecretException, InvalidSessionIdException): request.setResponseCode(HTTPStatus.UNAUTHORIZED) request.write( dict_to_json_bytes({ "errcode": "M_NO_VALID_SESSION", "error": "No valid session was found matching that sid and client secret", })) request.finish() return except SessionNotValidatedException: request.setResponseCode(HTTPStatus.FORBIDDEN) request.write( dict_to_json_bytes({ "errcode": "M_SESSION_NOT_VALIDATED", "error": "This validation session has not yet been completed", })) return if s.medium != threepid["medium"] or s.address != threepid[ "address"]: request.setResponseCode(HTTPStatus.FORBIDDEN) request.write( dict_to_json_bytes({ "errcode": "M_FORBIDDEN", "error": "Provided session information does not match medium/address combo", })) request.finish() return else: try: origin_server_name = ( await self.sydent.sig_verifier.authenticate_request( request, body)) except SignatureVerifyException as ex: request.setResponseCode(HTTPStatus.UNAUTHORIZED) request.write( dict_to_json_bytes({ "errcode": "M_FORBIDDEN", "error": str(ex) })) request.finish() return except NoAuthenticationError as ex: request.setResponseCode(HTTPStatus.UNAUTHORIZED) request.write( dict_to_json_bytes({ "errcode": "M_FORBIDDEN", "error": str(ex) })) request.finish() return except InvalidServerName as ex: request.setResponseCode(HTTPStatus.BAD_REQUEST) request.write( dict_to_json_bytes({ "errcode": "M_INVALID_PARAM", "error": str(ex) })) request.finish() return except (DNSLookupError, ConnectError, ResponseFailed) as e: msg = (f"Unable to contact the Matrix homeserver to " f"authenticate request ({type(e).__name__})") logger.warning(msg) request.setResponseCode(HTTPStatus.INTERNAL_SERVER_ERROR) request.write( dict_to_json_bytes({ "errcode": "M_UNKNOWN", "error": msg, })) request.finish() return except Exception: logger.exception( "Exception whilst authenticating unbind request") request.setResponseCode(HTTPStatus.INTERNAL_SERVER_ERROR) request.write( dict_to_json_bytes({ "errcode": "M_UNKNOWN", "error": "Internal Server Error" })) request.finish() return if not mxid.endswith(":" + origin_server_name): request.setResponseCode(HTTPStatus.FORBIDDEN) request.write( dict_to_json_bytes({ "errcode": "M_FORBIDDEN", "error": "Origin server name does not match mxid", })) request.finish() return self.sydent.threepidBinder.removeBinding(threepid, mxid) request.write(dict_to_json_bytes({})) request.finish() except Exception as ex: logger.exception("Exception whilst handling unbind") request.setResponseCode(HTTPStatus.INTERNAL_SERVER_ERROR) request.write( dict_to_json_bytes({ "errcode": "M_UNKNOWN", "error": str(ex) })) request.finish()
def process_later(request: Request): print("process_later called") request.write(b"later") # $ MISSING: responseBody=b"later" request.finish()
def finish(self): rv = Request.finish(self) store.rollback() store.commit() return rv