Browse Source

converting JSONErrors to exceptions

master
Julio Biason 11 years ago
parent
commit
df0263d337
  1. 12
      luncho/blueprints/users.py
  2. 55
      luncho/exceptions.py
  3. 13
      luncho/helpers.py
  4. 11
      luncho/server.py

12
luncho/blueprints/users.py

@ -17,11 +17,21 @@ from luncho.helpers import JSONError
from luncho.server import User from luncho.server import User
from luncho.server import db from luncho.server import db
from luncho.exceptions import LunchoException
LOG = logging.getLogger('luncho.blueprints.users') LOG = logging.getLogger('luncho.blueprints.users')
users = Blueprint('users', __name__) users = Blueprint('users', __name__)
class UsernameAlreadyExistsException(LunchoException):
"""The username is already taken."""
def __init__(self):
super(UsernameAlreadyExistsException, self).__init__()
self.status = 409
self.message = 'Username already exists'
@users.route('', methods=['PUT']) @users.route('', methods=['PUT'])
@ForceJSON(required=['username', 'full_name', 'password']) @ForceJSON(required=['username', 'full_name', 'password'])
def create_user(): def create_user():
@ -38,7 +48,7 @@ def create_user():
db.session.add(new_user) db.session.add(new_user)
db.session.commit() db.session.commit()
except IntegrityError: except IntegrityError:
return JSONError(409, 'Username already exists') raise UsernameAlreadyExistsException()
return jsonify(status='OK') return jsonify(status='OK')

55
luncho/exceptions.py

@ -0,0 +1,55 @@
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from flask import jsonify
class LunchoException(Exception):
"""Generic exception."""
def __init__(self):
self.status = 500
self.message = 'Unknown error'
self.extra_fields = None
def response(self):
"""Return a JSON representation of the exception."""
json = {'status': 'ERROR',
'message': self.message}
if self.extra_fields:
json.update(self.extra_fields)
response = jsonify(json)
response.status_code = self.status
return response
class RequestMustBeJSONException(LunchoException):
"""The request is not a valid JSON."""
def __init__(self):
super(RequestMustBeJSONException, self).__init__()
self.status = 400
self.message = 'Request MUST be in JSON format'
class MissingFieldsException(LunchoException):
"""There are missing fields in the request."""
def __init__(self, fields):
super(MissingFieldsException, self).__init__()
self.status = 400
self.message = 'Missing fields'
self.extra_fields = {'fields': fields}
class InvalidTokenException(LunchoException):
"""The passed token is invalid."""
def __init__(self):
super(InvalidTokenException, self).__init__()
self.status = 400
self.message = 'Invalid token'
class UserNotFoundException(LunchoException):
"""There is no user with the token."""
def __init__(self):
super(UserNotFoundException, self).__init__()
self.status = 404
self.message = 'User not found (via token)'

13
luncho/helpers.py

@ -10,6 +10,11 @@ from flask import jsonify
from luncho.server import User from luncho.server import User
from luncho.exceptions import RequestMustBeJSONException
from luncho.exceptions import InvalidTokenException
from luncho.exceptions import MissingFieldsException
from luncho.exceptions import UserNotFoundException
class ForceJSON(object): class ForceJSON(object):
def __init__(self, required=None): def __init__(self, required=None):
@ -20,7 +25,7 @@ class ForceJSON(object):
def check_json(*args, **kwargs): def check_json(*args, **kwargs):
json = request.get_json(force=True, silent=True) json = request.get_json(force=True, silent=True)
if not json: if not json:
return JSONError(400, 'Request MUST be in JSON format') raise RequestMustBeJSONException()
# now we have the JSON, let's check if all the fields are here. # now we have the JSON, let's check if all the fields are here.
missing = [] missing = []
@ -29,7 +34,7 @@ class ForceJSON(object):
missing.append(field) missing.append(field)
if missing: if missing:
return JSONError(400, 'Missing fields', fields=missing) raise MissingFieldsException(missing)
return func(*args, **kwargs) return func(*args, **kwargs)
return check_json return check_json
@ -66,9 +71,9 @@ def user_or_error(token):
:return: Tuple with the user and the error.""" :return: Tuple with the user and the error."""
user = User.query.filter_by(token=token).first() user = User.query.filter_by(token=token).first()
if not user: if not user:
return (None, JSONError(404, 'User not found (via token)')) raise UserNotFoundException()
if not user.valid_token(token): if not user.valid_token(token):
return (None, JSONError(400, 'Invalid token')) raise InvalidTokenException()
return (user, None) return (user, None)

11
luncho/server.py

@ -8,6 +8,8 @@ import datetime
from flask import Flask from flask import Flask
from luncho.exceptions import LunchoException
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Config # Config
@ -105,3 +107,12 @@ app.register_blueprint(index, url_prefix='/')
app.register_blueprint(token, url_prefix='/token/') app.register_blueprint(token, url_prefix='/token/')
app.register_blueprint(users, url_prefix='/user/') app.register_blueprint(users, url_prefix='/user/')
app.register_blueprint(groups, url_prefix='/group/') app.register_blueprint(groups, url_prefix='/group/')
# ----------------------------------------------------------------------
# Error management
# ----------------------------------------------------------------------
@app.errorhandler(LunchoException)
def handle_luncho_exception(error):
"""Normal luncho error."""
return error.response()

Loading…
Cancel
Save