def write_error(self, status_code, **kwargs): """Render error page for uncaught errors""" # if it's a 404, just report it as such if status_code == 404: self.render('error.html', status_code=status_code, status_message="Not found", message="Not found") return status_message = responses.get(status_code, 'Unknown HTTP Error') message = "" # If this error was caused by an uncaught exception # log exception message and reference number as well exc_info = kwargs.get('exc_info') if exc_info: exception = exc_info[1] ref = self.log.issue(status_message, exception) reason = getattr(exception, 'reason', '') message = '{} Ref.: {}'.format(reason, ref) self.render('error.html', status_code=status_code, status_message=status_message, message=message)
def get(self, status_code_s): status_code = int(status_code_s) status_message = responses.get(status_code, 'Unknown HTTP Error') # build template namespace hub_home = url_path_join(self.hub.base_url, 'home') message_html = '' if status_code == 503: message_html = ' '.join([ "Your server appears to be down.", "Try restarting it <a href='%s'>from the hub</a>" % hub_home ]) ns = dict( status_code=status_code, status_message=status_message, message_html=message_html, logo_url=hub_home, ) self.set_header('Content-Type', 'text/html') # render the template try: html = self.render_template('%s.html' % status_code, **ns) except TemplateNotFound: self.log.debug("No template for %d", status_code) html = self.render_template('error.html', **ns) self.write(html)
def get_error_html(self, status_code, **kwargs): """render custom error pages""" exception = kwargs.get("exception") message = "" status_message = responses.get(status_code, "Unknown") if exception: # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, "reason", "") if reason: status_message = reason # build template namespace ns = dict(status_code=status_code, status_message=status_message, message=message, exception=exception) # render the template try: html = self.render_template("%d.html" % status_code, **ns) except Exception as e: app_log.warn("No template for %d", status_code) html = self.render_template("error.html", **ns) return html
def get_error_html(self, status_code, **kwargs): """render custom error pages""" exception = kwargs.get('exception') message = '' status_message = responses.get(status_code, 'Unknown HTTP Error') if exception: # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: status_message = reason # build template namespace ns = dict( status_code=status_code, status_message=status_message, message=message, exception=exception, ) # render the template try: html = self.render_template('%s.html' % status_code, **ns) except TemplateNotFound: self.log.debug("No template for %d", status_code) html = self.render_template('error.html', **ns) return html
def start_response(status, headers): response.status_code = int(status.split(' ')[0]) response.reason = responses.get(response.status_code, 'Unknown Status Code') response.headers = CaseInsensitiveDict(headers) response.encoding = get_encoding_from_headers(response.headers) response.elapsed = datetime.datetime.utcnow() - start self._log(response)
def write_error(self, status_code, **kwargs): """render custom error pages""" exc_info = kwargs.get("exc_info") message = "" status_message = responses.get(status_code, "Unknown HTTP Error") if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, "reason", "") if reason: status_message = reason # build template namespace ns = dict(status_code=status_code, status_message=status_message, message=message, exception=exception) self.set_header("Content-Type", "text/html") # render the template try: html = self.render_template("%s.html" % status_code, **ns) except TemplateNotFound: self.log.debug("No template for %d", status_code) html = self.render_template("error.html", **ns) self.write(html)
def write_error(self, status_code, **kwargs): """render custom error pages""" exc_info = kwargs.get('exc_info') message = '' status_message = responses.get(status_code, 'Unknown') if exc_info: # get the custom message, if defined exception = exc_info[1] try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: status_message = reason # build template namespace ns = dict( status_code=status_code, status_message=status_message, message=message, exception=exception, ) # render the template try: html = self.render_template('%d.html' % status_code, **ns) except Exception as e: app_log.warn("No template for %d", status_code) html = self.render_template('error.html', **ns) self.set_header('Content-Type', 'text/html') self.write(html)
def status_text(self): """ Returns reason text corresponding to our HTTP response status code. Provided for convenience. """ # TODO: Deprecate and use a template tag instead # TODO: Status code text for RFC 6585 status codes return responses.get(self.status_code, '')
def verify_header(self): """ Raise an exceptions on bad headers. """ code = int(self.c.getinfo(pycurl.RESPONSE_CODE)) if code in bad_headers: raise ResponseException( code, responses.get(code, "Unknown statuscode")) return code
def __init__(self, code, header=b"", content=b""): int_code = int(code) response = responses.get( int_code, PROPRIETARY_RESPONSES.get(int_code, "unknown error code") ) super().__init__(f"Bad server response: {code} {response}") self.code = int_code self.header = header self.content = content
def ok(self, T=None): self.start_res( "{} {}".format( self.status_code, self.status_text or resps.get(self.status_code, "Unknown") ), list(self.headers.items()) ) return Ok(self.body if T is None else T)
def write_error(self, status_code, **kwargs): """render custom error pages""" exc_info = kwargs.get('exc_info') message = '' exception = None status_message = responses.get(status_code, 'Unknown HTTP Error') if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: message = reasons.get(reason, reason) if exception and isinstance(exception, SQLAlchemyError): self.log.warning("Rolling back session due to database error %s", exception) self.db.rollback() # build template namespace ns = dict( status_code=status_code, status_message=status_message, message=message, extra_error_html=getattr(self, 'extra_error_html', ''), exception=exception, ) self.set_header('Content-Type', 'text/html') if isinstance(exception, web.HTTPError): # allow setting headers from exceptions # since exception handler clears headers headers = getattr(exception, 'headers', None) if headers: for key, value in headers.items(): self.set_header(key, value) # Content-Length must be recalculated. self.clear_header('Content-Length') # render the template try: html = self.render_template('%s.html' % status_code, **ns) except TemplateNotFound: self.log.debug("No template for %d", status_code) try: html = self.render_template('error.html', **ns) except: # In this case, any side effect must be avoided. ns['no_spawner_check'] = True html = self.render_template('error.html', **ns) self.write(html)
def _set_status(self, code): """ Set the status property, with code and message :param code: HTTP status code """ self.json['status'] = { 'code': code, 'message': http_code.get(code, None) }
def __init__(self, request, code, headers=None, buffer=None, effective_url=None, error=None, status=None): self.request = request self.code = code self.headers = headers if headers is not None else Headers() self.buffer = buffer self.effective_url = effective_url or request.url self._body = None self.status = status or responses.get(self.code, "Unknown") self.error = error if self.error is None and (self.code < 200 or self.code > 299): self.error = HttpError(self.code, self.status, self)
def write_error(self, status_code, **kwargs): exc_info = kwargs.get('exc_info') message = '' status_message = responses.get(status_code, 'Unknown HTTP Error') if exc_info: message = self.extract_message(exc_info) self.render_template( 'error.html', status_code=status_code, status_message=status_message, message=message, )
def write_error(self, status_code, **kwargs): """APIHandler errors are JSON, not human pages""" self.set_header('Content-Type', 'application/json') message = responses.get(status_code, 'Unknown HTTP Error') reply = { 'message': message, } exc_info = kwargs.get('exc_info') if exc_info: e = exc_info[1] if isinstance(e, HTTPError): reply['message'] = e.log_message or message else: reply['message'] = 'Unhandled error' reply['traceback'] = ''.join(traceback.format_exception(*exc_info)) self.log.warning(reply['message']) self.finish(json.dumps(reply))
def send_error(self, status_code, **kwargs): """event stream cannot set an error code, so send an error event""" exc_info = kwargs.get('exc_info') message = '' if exc_info: message = self.extract_message(exc_info) if not message: message = responses.get(status_code, 'Unknown HTTP Error') # this cannot be async evt = json.dumps({ 'phase': 'failed', 'status_code': status_code, 'message': message + '\n', }) self.write('data: {}\n\n'.format(evt)) self.finish()
def write_error(self, status_code, **kwargs): """Write JSON errors instead of HTML""" exc_info = kwargs.get('exc_info') message = '' exception = None status_message = responses.get(status_code, 'Unknown Error') if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: status_message = reason if exception and isinstance(exception, SQLAlchemyError): try: exception_str = str(exception) self.log.warning( "Rolling back session due to database error %s", exception_str ) except Exception: self.log.warning( "Rolling back session due to database error %s", type(exception) ) self.db.rollback() self.set_header('Content-Type', 'application/json') if isinstance(exception, web.HTTPError): # allow setting headers from exceptions # since exception handler clears headers headers = getattr(exception, 'headers', None) if headers: for key, value in headers.items(): self.set_header(key, value) # Content-Length must be recalculated. self.clear_header('Content-Length') self.write( json.dumps({'status': status_code, 'message': message or status_message}) )
def write_error(self, status_code, **kwargs): """Responds with an application/json error object. Overrides the HTML renderer in the notebook server to force all errors to JSON format. Outputs all errors as JSON in the same format as the notebook.base.handlers.json_errors decorator. Avoids having to (re-)decorate everything that the kernel gateway overrides. Also avoids rendering errors as a human readable HTML pages in cases where the decorator is not used in the notebook code base. Parameters ---------- status_code HTTP status code to set **kwargs Arbitrary keyword args. Only uses `exc_info[1]`, if it exists, to get a `log_message`, `args`, and `reason` from a raised exception that triggered this method Examples -------- {"401", reason="Unauthorized", message="Invalid auth token"} """ exc_info = kwargs.get('exc_info') message = '' reason = responses.get(status_code, 'Unknown HTTP Error') if exc_info: exception = exc_info[1] # Get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # Construct the custom reason, if defined custom_reason = getattr(exception, 'reason', '') if custom_reason: reason = custom_reason self.set_header('Content-Type', 'application/json') self.set_status(status_code) reply = dict(reason=reason, message=message) self.finish(json.dumps(reply))
def send(self, environ, start_response): """Send the headers and return the body of the response.""" status = "%d %s" % (self.status, HTTP_CODES.get(self.status)) body = (self.output if self.wrapped else [tobytes(self.output)]) if self.output else [] if not self.wrapped: self.headers['Content-Length'] = str(body and len(body[0]) or 0) if hasattr(self, "_new_cookie"): app = environ['fiole.app'] for cookie in self._new_cookie.values(): if cookie._signed is not None: self._new_cookie[cookie.key] = ( app.encode_signed(cookie.key, cookie._signed)) self.headers.add("Set-Cookie", cookie.OutputString(None)) start_response(status, self.headers.to_list()) if environ['REQUEST_METHOD'] != 'HEAD': return body if hasattr(body, 'close'): body.close() return []
def write_error(self, status_code, **kwargs): """Write JSON errors instead of HTML""" exc_info = kwargs.get('exc_info') message = '' status_message = responses.get(status_code, 'Unknown Error') if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: status_message = reason self.write(json.dumps({ 'status': status_code, 'message': message or status_message, }))
def write_error(self, status_code, **kwargs): exc_info = kwargs.get('exc_info') message = '' status_message = responses.get(status_code, 'Unknown HTTP Error') if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: status_message = reason self.set_header('Content-Type', 'text/html') self.render("error.html", status_code=status_code, status_message=status_message, message=message, )
def write_error(self, status_code, **kwargs): """render custom error pages""" exc_info = kwargs.get('exc_info') message = '' exception = None status_message = responses.get(status_code, 'Unknown HTTP Error') if exc_info: exception = exc_info[1] # get the custom message, if defined try: message = exception.log_message % exception.args except Exception: pass # construct the custom reason, if defined reason = getattr(exception, 'reason', '') if reason: message = reasons.get(reason, reason) # build template namespace ns = dict( status_code=status_code, status_message=status_message, message=message, extra_error_html=getattr(self, 'extra_error_html', ''), exception=exception, ) self.set_header('Content-Type', 'text/html') # render the template try: html = self.render_template('%s.html' % status_code, **ns) except TemplateNotFound: self.log.debug("No template for %d", status_code) html = self.render_template('error.html', **ns) self.write(html)
def __init__(self, status, message=None): self.status = status self.message = message or responses.get(status, "Unknown") super().__init__(status, message)
def get_code_name(status_code): return '%s %s' % ( status_code, responses.get(status_code, 'Default Code Message') )
def codestr(code): return HTTP_CODES.get(code, 'UNKNOWN')
def _wsgi_status(self): return str(self.status) + ' ' + STATUS_MESSAGES.get(self.status, '')
def _value_for_code(code): msg = STATUS_CODE_TEXT.get(code, "UNKNOWN STATUS CODE") return "HTTP/1.1 %d %s" % (code, msg)
def status_text(self): """ Returns reason text corresponding to our HTTP response status code. Provided for convenience. """ return responses.get(self.status_code, "")
def write_error(self, status_code, **kwargs): self.finish({ 'error': responses.get(status_code, 'Unknown error'), 'code': status_code, **kwargs })
def status(self) -> str: status_text: str = responses.get(self.status_code, '').title() return f"{self.status_code} {status_text}"
def __init__(self, code, message=None): self.code = code message = message or responses.get(code, "Unknown") Exception.__init__(self, "%d: %s" % (self.code, message))
async def find_anime(client: Client, message: Message): # TODO: Support video document? """ Find anime source by replying to a photo, <b>image</b> document, GIF or video. If successful, you will receive basic info about the found anime. Note, that <code>opencv-python</code> is required for GIF and video support. """ target_msg = message.reply_to_message if message.reply_to_message else message media = target_msg.photo or target_msg.video or target_msg.animation or target_msg.document if media is None or (isinstance(media, Document) and "image" not in media.mime_type): await message.edit_text( "A photo, video, GIF or <b>image</b> document is required.", ) else: with tempfile.TemporaryDirectory() as tempdir: await message.edit_text("<i>Processing...</i>", message_ttl=0) file_path = await client.download_media(target_msg, file_name=os.path.join( tempdir, media.file_id)) if isinstance(media, (Animation, Video)): if cv2 is not None: file_path = get_video_frame(file_path) else: return await message.edit_text( "This media type requires <code>opencv-python</code>.", ) try: async with await client.http_session.post( "https://api.trace.moe/search?cutBorders&anilistInfo", data={"file": open(file_path, "rb")}, ) as resp: resp.raise_for_status() resp_json = await resp.json() parsed_result = AnimeResult.parse_obj( resp_json["result"][0]) if message.reply_to_message: reply_to_id = message.reply_to_message.message_id else: reply_to_id = None await client.send_video( message.chat.id, parsed_result.big_video_link, caption=parsed_result.format_to_text(), reply_to_message_id=reply_to_id, message_ttl=35, ) await message.delete() except ServerTimeoutError: await message.edit_text( "Failed to get info about this anime:\n<code>Read Timeout</code>", ) except ClientResponseError as ex: description = responses.get(ex.status) await message.edit_text( f"Failed to get info about this anime:\n<code>{description}</code>", ) except ValidationError: await message.edit_text( "Seems that the API has changed.\n" "Please, update Telecharm or wait for new versions.", message_ttl=5, )
def get_status(self): code = self.status_code if code: return '%d %s' % (code, responses.get(code, 'Unknown'))
__all__ = ['Meta', 'html_choices', 'htmldoc', 'htmldefaultdoc', 'html_doc_stream', 'error_title'] htmldefaultdoc = 5 _Meta = WidgetMaker(tag='meta', inline=True, attributes=('content', 'http-equiv', 'name', 'charset')) error_title = lambda status : responses.get(\ status,'Unknown error {0}'.format(status)) def isiterable(elem): return isinstance(elem, (list,tuple)) or\ (hasattr(elem, '__iter__') and not hasattr(elem, '__len__')) def Meta(*args,**kwargs): return Widget(_Meta,*args,**kwargs) class HTMLdoc(UnicodeMixin): def __init__(self, typ, name, html, vimg = None, slash = ""): self.typ = typ self.name = name
def response(self): return responses.get(self.status_code)
def cur_location(): env = g["environ"] return env["HTTP_HOST"] + env["PATH_INFO"] + "?" + env["QUERY_STRING"] def Redirect_resp(path): resp = Response(status=301, content_type='text/html') env = g["environ"] ltion = "http://" + env["HTTP_HOST"] + \ "/" if path[0] is not "/" else "" + path resp.add_header("Location", ltion) return resp def file_resp(filename): with open(filename, "rb") as f: return Response(f.read()) if __name__ == '__main__': print(HTTPCODE.get(200)) print(HTTPCODE.get(500)) print(HTTPCODE.get(400)) print(HTTPCODE.get(300)) TEST1 = Response("<h1>Hello!</h1>") print(list(iter(TEST1))) print(TEST1.status) print(TEST1.headers)
def status(self): from http.client import responses status_string = responses.get(self._status, 'UNKNOWN STATUS') return f'{self._status} {status_string}'
def status_text(status_code): return responses.get(status_code, '')
def reason_phrase(self): if self._reason_phrase is not None: return self._reason_phrase # Leave self._reason_phrase unset in order to use the default # reason phrase for status code. return responses.get(self.status_code, 'Unknown Status Code')
def response_phrase(self): return responses.get(self.status_code, "")
def reason(self): return responses.get(self.status_code)
def reason_phrase(self): if self._reason_phrase is not None: return self._reason_phrase return responses.get(self.status_code, 'Unknown Status Code')
def _codestr(code): return http_codes.get(code, 'UNKNOWN')
def status(self): status_string = HTTPCODE.get(self._status, 'UNKOWN STATUS') return f"{self._status} {status_string}"
def status(self): return '%s %s' % (self.status_code, responses.get(self.status_code))
def status_text(self): """Copied from DRF Response class""" return responses.get(self.status_code, "")