def test_aborter(): """Exception aborter""" assert_raises(exceptions.BadRequest, abort, 400) assert_raises(exceptions.Unauthorized, abort, 401) assert_raises(exceptions.Forbidden, abort, 403) assert_raises(exceptions.NotFound, abort, 404) assert_raises(exceptions.MethodNotAllowed, abort, 405, ['GET', 'HEAD']) assert_raises(exceptions.NotAcceptable, abort, 406) assert_raises(exceptions.RequestTimeout, abort, 408) assert_raises(exceptions.Gone, abort, 410) assert_raises(exceptions.LengthRequired, abort, 411) assert_raises(exceptions.PreconditionFailed, abort, 412) assert_raises(exceptions.RequestEntityTooLarge, abort, 413) assert_raises(exceptions.RequestURITooLarge, abort, 414) assert_raises(exceptions.UnsupportedMediaType, abort, 415) assert_raises(exceptions.InternalServerError, abort, 500) assert_raises(exceptions.NotImplemented, abort, 501) assert_raises(exceptions.BadGateway, abort, 502) assert_raises(exceptions.ServiceUnavailable, abort, 503) myabort = Aborter({1: exceptions.NotFound}) assert_raises(LookupError, myabort, 404) assert_raises(exceptions.NotFound, myabort, 1) myabort = Aborter(extra={1: exceptions.NotFound}) assert_raises(exceptions.NotFound, myabort, 404) assert_raises(exceptions.NotFound, myabort, 1)
def test_exception_header_forwarded(self, app, client): '''Ensure that HTTPException's headers are extended properly''' api = restplus.Api(app) class NotModified(HTTPException): code = 304 def __init__(self, etag, *args, **kwargs): super(NotModified, self).__init__(*args, **kwargs) self.etag = quote_etag(etag) def get_headers(self, *args, **kwargs): return [('ETag', self.etag)] custom_abort = Aborter(mapping={304: NotModified}) @api.route('/foo') class Foo1(restplus.Resource): def get(self): custom_abort(304, etag='myETag') foo = client.get('/foo') assert foo.get_etag() == unquote_etag(quote_etag('myETag'))
def play(vid): video = Video.get(video_id=vid) if not video: abort = Aborter() return abort(404) user = cur_user() usr = User.get(login=video.user.login) if user and user not in video.viewers: video.add_viewer(user) likened = 0 if user in video.likes: likened = 1 if user in video.dislikes: likened = -1 return render_template('video_page.html', user=user, vid=vid, video=video, lkd=likened, usr=usr, subscribed=(user in usr.subscribers))
get_token() class Unauthorized(HTTPException): code = 401 description = 'Invalid X-Auth-Token.' class PreconditionFailed(HTTPException): code = 412 description = 'Missing X-Auth-Token header. Token is available in src/data/token.' default_exceptions[401] = Unauthorized default_exceptions[412] = PreconditionFailed abort = Aborter() def need_authentication(f): @wraps(f) def wrap(*args, **kwargs): user_token = get_token() # Fetch authentication token token = request.headers.get('X-Auth-Token', '') # Missing or empty authentication token if token == '': abort(412) # Invalid user token
class Payme(HTTPException): # HTTPException 클래스를 상속받아 클래스를 하나 만든다 code = 500 # code 필드는 필수 description = 'I am sorry' # description 필드는 옵션이다. Status message에 보내지는 게 아니라, <p> 태그에 들어가는 설명이다 default_exceptions[Payme.code] = Payme # -> ???? # 기본 exception에 직접 만든 오류 코드를 심는다 HTTP_STATUS_CODES[ Payme. code] = Payme.description # -> (web title과 text가 Payme.status_code & Payme.description 값으로 뜸) # 이건 status message를 관리하기 위해 사용한다 _aborter = Aborter() # -> ???? app = Flask(__name__) @app.route('/') def index(): abort(Payme.code) # -> Payme.code 값으로 status_code가 뜨도록 함 if __name__ == '__main__': app.run(debug=True)
def raise_404_exception(): r = requests.get("https://httpbin.org/nope") if r.status_code != 200: Aborter()(code=r.status_code) print("this won't print")
def dont_raise_404_exception(): r = requests.get("https://httpbin.org/get") if r.status_code != 200: Aborter()(code=r.status_code) print("this will print")
def get_or_404(self, **keys): rv = self.session.query(self.model).filter_by(**keys).one() if rv is None: Aborter.abort(404) return rv
class Authentication_token(HTTPException): code = 4015 description = 'Unable to parse authentication token' class Unable_appropriate_key(HTTPException): code = 4016 description = 'Unable to find the appropriate key' class Add_authorization_header(HTTPException): code = 4017 description = 'Add authorization header to the request.' class Authorization_must_bear(HTTPException): code = 4018 description = 'The authorization header must be bearer' default_exceptions[4011] = Permission_check_fail default_exceptions[4012] = Invalid_header_malformed default_exceptions[4013] = Token_expired default_exceptions[4014] = Audience_issuer default_exceptions[4015] = Authentication_token default_exceptions[4016] = Unable_appropriate_key default_exceptions[4017] = Add_authorization_header default_exceptions[4018] = Authorization_must_bear abort = Aborter() # don't from flask import abort
# code 필드는 필수 description = 'Hello?' # description 필드는 옵션이다. Status message에 보내지는 게 아니라, <p> 태그에 들어가는 설명이다 default_exceptions[777] = Payme # 기본 exception에 직접 만든 오류 코드를 심는다 # werkzeug.exceptions.abort()는 내부적으로 _aborter 객체를 호출(__call__())한다 # > return _aborter(status, *args, **kwargs) # 해당 _aborter 객체는 아래처럼 초기화된다 # > _aborter = Aborter() # 따라서 werkzeug.exceptions._aborter 객체를 다시 초기화해 주어야 한다 _aborter = Aborter() HTTP_STATUS_CODES[777] = 'Hello' # 이건 없어도 되지만, status message를 관리하기 위해 사용한다 # werkzeug.http.HTTP_STATUS_CODE는 status code와 message로 이루어진 딕셔너리다 app = Flask(__name__) @app.route('/') def index(): abort(777) if __name__ == '__main__': app.run(debug=True)
result_ttl=REDIS_TTL, job_timeout=REDIS_JOB_TIMEOUT) task_types_desc = ', '.join('{0.value} - {0.name}'.format(x) for x in TaskType) results_types_desc = ', '.join('{0.value} - {0.name}'.format(x) for x in ResultType) additives_types_desc = ', '.join('{0.value} - {0.name}'.format(x) for x in AdditiveType) class Abort512(HTTPException): code = 512 description = 'task not ready' original_flask_abort = Aborter(extra={512: Abort512}) def abort(http_status_code, **kwargs): """ copy-paste from flask-restful """ try: original_flask_abort(http_status_code) except HTTPException as e: if len(kwargs): e.data = kwargs raise def fetch_task(task, status): job = redis.fetch_job(task)
from werkzeug.exceptions import HTTPException from werkzeug.exceptions import Aborter class NoContentException(HTTPException): code = 204 description = 'No content' abort = Aborter(extra={204: NoContentException})
from flask import Flask, Response, jsonify from werkzeug.exceptions import HTTPException from werkzeug.exceptions import Aborter _mapping = Aborter().mapping def asJson(error): return { "code": error.code, "name": error.name, "description": error.description, }, error.code class ApiResponse(Response): """the ApiResponse class is the default response class for the ApiFlask class. Its mimetype is application/json. Lists and dicts are converted to json. """ charset = "utf-8" default_mimetype = "application/json" default_status = 200 @classmethod def force_type(cls, rv, environ=None): if isinstance(rv, list) or isinstance(rv, dict): rv = jsonify(rv) return super(ApiResponse, cls).force_type(rv, environ)