Esempio n. 1
0
def post():
    """Creates a new user"""

    data = flask.request.get_json()

    if not 'username' in data or not 'password' in data:
        return flask.Response('Username and password are required', 400)

    epass = hashlib.sha256(data['password'].encode('utf-8')).hexdigest()

    user = User(username=data['username'],
                password=epass,
                email='email' in data and data['email'] or None)

    try:
        user.save()
    except mongoengine.NotUniqueError:
        return flask.Response('That user already exists', 409)

    # need to find a cleaner way to serialize an object as json excluding a
    # property...
    clean = json.loads(user.to_json())
    del clean['password']
    clean = json.dumps(clean)

    return JSONResponse(clean)
Esempio n. 2
0
def put(id):
    """Updates the given beer by it's id"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('Not found', 404)

    data = flask.request.get_json()

    # update an of our simple fields
    props = ['name', 'ibu', 'calories', 'abv', 'style']
    for item in props:
        if item in data:
            setattr(beer, item, data[item])

    # check if we got a brewery update
    if 'brewery' in data:
        brewery = Brewery.objects.get(id=data['brewery'])
        if brewery is not None:
            beer.brewery = brewery

    # check if we got a glass update
    if 'glass' in data:
        glass = Glass.objectsget(id=data['glass'])
        if glass is not None:
            beer.glass = glass

    beer.save()

    return JSONResponse(beer.to_json())
Esempio n. 3
0
def put(id, fid):
    """Updates the given favorite for the logged in user by ids"""

    if id != str(flask.request.user.id):
        return flask.Response(
            'You can not update a favorite that does not belong to you', 400)

    try:
        favorite = Favorite.objects.get(id=fid, user=flask.request.user)
    except mongoengine.DoesNotExist:
        return flask.Response('No favorite with id {} found'.format(fid), 404)
    except:
        return flask.Response('Invalid favorite id {}'.format(fid), 400)

    data = flask.request.get_json()

    # update an of our simple fields
    if 'beer' in data:
        try:
            beer = Beer.objects.get(id=data['beer'])
        except mongoengine.DoesNotExist:
            return flask.Response(
                'No beer with id {} found'.format(data['beer']), 404)
        except:
            return flask.Response('Invalid beer id {}'.format(data['beer']),
                                  400)

        favorite.beer = beer

    try:
        favorite.save()
    except mongoengine.ValidationError as exp:
        return flask.Response('{}'.format(exp), 400)

    return JSONResponse(favorite.to_json())
Esempio n. 4
0
def delete(id):
    """Deletes the given beer by id"""

    try:
        Beer.objects.get(id=id).delete()
    except mongoengine.DoesNotExist:
        return flask.Response('No beer with id {} found'.format(id), 404)

    return JSONResponse()
Esempio n. 5
0
def get(id):
    """Gets a specific user"""

    try:
        user = User.objects.exclude('password').get(id=id).to_json()
    except mongoengine.DoesNotExist:
        return flask.Response('No user with id {} found'.format(id), 400)
    except mongoengine.errors.ValidationError:
        return flask.Response('Invalid id {}'.format(id), 400)

    return JSONResponse(user.to_json())
Esempio n. 6
0
def delete(id):
    """Deletes a specific user"""

    try:
        User.objects.get(id=id).delete()
    except mongoengine.DoesNotExist:
        return flask.Response('No user with id {} found'.format(id), 400)
    except:
        return flask.Response('Invalid id {}'.format(id), 400)

    return JSONResponse()
Esempio n. 7
0
def list(id):
    """Returns a list of all favorites for the given user"""

    try:
        user = User.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No user with id {} found'.format(id), 404)
    except:
        return flask.Resposne('Invalid id {}'.format(id), 400)

    return JSONResponse(Favorite.objects.all().filter(user=user).to_json())
Esempio n. 8
0
def list():
    """Returns a list of all breweries"""

    breweries = Brewery.objects.all()

    if 'sort' in flask.request.values:
        props = ['name', 'city', 'state']

        keys = get_sort_keys(flask.request.values['sort'].split(','), props)

        breweries = breweries.order_by(*keys)

    return JSONResponse(breweries.to_json())
Esempio n. 9
0
def list():
    """Returns a list of all beers"""

    beers = Beer.objects.all()

    if 'sort' in flask.request.values:
        props = ['name', 'ibu', 'calories', 'abv', 'style', 'rating']

        keys = get_sort_keys(flask.request.values['sort'].split(','), props)

        if len(keys) > 0:
            beers = beers.order_by(*keys)

    return JSONResponse(beers.to_json())
Esempio n. 10
0
def post():
    data = flask.request.get_json()

    if not 'name' in data:
        return flask.Response('No name specified', 400)

    glass = Glass(name=data['name'])

    try:
        glass.save()
    except mongoengine.NotUniqueError as exp:
        glass = Glass.objects.get(name=data['name'])

    return JSONResponse(glass.to_json())
Esempio n. 11
0
def put(id):
    try:
        glass = Glass.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.response('Not found', 404)

    data = flask.request.get_json()

    if 'name' in data:
        glass.name = data['name']

    glass.save()

    return JSONResponse(glass.to_json())
Esempio n. 12
0
def list():
    """Returns a list of all users"""

    users = User.objects.all().exclude('password')

    if 'sort' in flask.request.values:
        props = ['username', 'email']

        keys = get_sort_keys(flask.request.values['sort'].split(','), props)

        if len(keys) > 0:
            users = users.order_by(*keys)

    return JSONResponse(users.to_json())
Esempio n. 13
0
def list():
    """ returns a list of all glasses """

    glasses = Glass.objects.all()

    if 'sort' in flask.request.values:
        props = ['name']

        keys = get_sort_keys(flask.request.values['sort'].split(','), props)

        if len(keys) > 0:
            glasses = glasses.order_by(*keys)

    return JSONResponse(glasses.to_json())
Esempio n. 14
0
def post():
    """Creates a new beer"""

    # figure out who's adding this beer, and if they've added one within the
    # last 24 hours
    if flask.request.user.last_beer_added is not None:
        wait = flask.request.user.last_beer_added + relativedelta(hours=+24)

        if wait > datetime.now():
            return flask.Response('You can only add one beer every 24 hours. ' \
                                  'You can add another beer on {}'.format(wait),
                                  400)

    data = flask.request.get_json()

    if not 'name' in data:
        return flask.Response('No name specified', 400)

    # create the beer
    beer = Beer(name=data['name'],
                ibu='ibu' in data and data['ibu'] or None,
                calories='calories' in data and data['calories'] or None,
                abv='abv' in data and data['abv'] or None,
                style='style' in data and data['style'] or None)

    # now look for the brewery by id
    if 'brewery' in data:
        brewery = Brewery.objects.get(id=data['brewery'])
        if brewery is not None:
            beer.brewery = brewery

    # now look for the glass by id
    if 'glass' in data:
        glass = Glass.objects.get(id=data['glass'])
        if glass is not None:
            beer.glass = glass

    try:
        beer.save()
    except mongoengine.NotUniqueError as exp:
        return flask.Response('A beer with the name "{}" already exists' \
                              .format(data['name']), 409)

    flask.request.user.last_beer_added = datetime.now()
    flask.request.user.save()

    return JSONResponse(beer.to_json())
Esempio n. 15
0
def delete(id, fid):
    """Deletes the given favorite for the given logged in user by ids"""

    if id != str(flask.request.user.id):
        return flask.Response(
            'You can not remove a favorite that does not belong to you', 400)

    try:
        favorite = Favorite.objects.get(id=fid, user=flask.request.user)
    except mongoengine.DoesNotExist:
        return flask.Response('No favorite with id {} found'.format(fid), 404)
    except:
        return flask.Response('Invalid favorite id {}'.format(fid), 400)

    favorite.delete()

    return JSONResponse()
Esempio n. 16
0
def post():
    """Creates a new brewery"""

    data = flask.request.get_json()

    if not 'name' in data:
        return flask.Response('No name specified', 400)

    brewery = Brewery(name=data['name'],
                      city='city' in data and data['city'] or None,
                      state='state' in data and data['state'] or None)

    try:
        brewery.save()
    except mongoengine.NotUniqueError as exp:
        brewery = Brewery.objects.get(name=data['name'])

    return JSONResponse(brewery.to_json())
Esempio n. 17
0
def put(id):
    """Updates a brewery by id"""

    try:
        brewery = Brewery.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.response('Not found', 404)

    data = flask.request.get_json()

    props = ['name', 'city', 'state']

    for item in props:
        if item in data:
            setattr(brewery, item, data[item])

    brewery.save()

    return JSONResponse(brewery.to_json())
Esempio n. 18
0
def delete(id, rid):
    """Deletes the given review for the given beer by ids"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No beer with id {} found'.format(id), 404)
    except:
        return flask.Response('Invalid beer id {}'.format(id), 400)

    try:
        review = Review.objects.get(id=rid, beer=beer)
    except mongoengine.DoesNotExist:
        return flask.Response('No review with id {} found'.format(rid), 404)
    except:
        return flask.Response('Invalid review id {}'.format(id), 400)

    review.delete()

    return JSONResponse()
Esempio n. 19
0
def get(id, rid):
    """Returns the given review for the given beer by ids"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('Failed to find a beer with id {}'.format(id),
                              404)
    except:
        return flask.Response('Invalid beer id {}'.format(id), 400)

    try:
        review = Review.objects.get(id=rid, beer=beer)
    except mongoengine.DoesNotExist:
        return flask.Resposne('Failed to find a review with id {}'.format(id),
                              404)
    except:
        return flask.Response('Invalid review id {}'.format(rid), 400)

    return JSONResponse(review.to_json())
Esempio n. 20
0
def get(id, fid):
    """Returns the given favorite for the given user by ids"""

    try:
        user = User.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('Failed to find a user with id {}'.format(id),
                              404)
    except:
        return flask.Response('Invalid user id {}'.format(id), 400)

    try:
        favorite = Favorite.objects.get(id=fid, user=user)
    except mongoengine.DoesNotExist:
        return flask.Resposne(
            'Failed to find a favorite with id {}'.format(fid), 404)
    except:
        return flask.Response('Invalid favorite id {}'.format(fid), 400)

    return JSONResponse(favorite.to_json())
Esempio n. 21
0
def post(id):
    """Creates a new review for the given beer"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No beer with id {} found'.format(id), 404)
    except:
        return flask.Response('Invalid id {}'.format(id), 400)

    data = flask.request.get_json()

    # check to see if a review was already created for this beer from this
    # user
    try:
        Review.objects.get(beer=beer, user=flask.request.user)
    except mongoengine.DoesNotExist:
        pass
    else:
        return flask.Response(
            'You\'ve already created a review for beer {}'.format(id), 400)

    review = Review(beer=beer, user=flask.request.user)

    props = ['aroma', 'appearance', 'taste', 'palate', 'bottle_style']
    for item in props:
        if item in data:
            setattr(review, item, data[item])

    review.calculate()

    try:
        review.save()
    except mongoengine.ValidationError as exp:
        return flask.Response('{}'.format(exp), 400)

    beer.rating = Review.objects.all().filter(beer=beer).average('overall')
    beer.save()

    return JSONResponse(review.to_json())
Esempio n. 22
0
def post(id):
    """Creates a new favorite for the logged in user for the given beer"""

    if id != str(flask.request.user.id):
        return flask.Response(
            'You can not add a favorite beer for another user', 400)

    data = flask.request.get_json()

    if not 'beer' in data:
        return flask.Response('No beer was specified', 400)

    # find the beer
    try:
        beer = Beer.objects.get(id=data['beer'])
    except mongoengine.DoesNotExist:
        return flask.Resposne('No beer with id {} found'.format(data['beer']),
                              404)
    except:
        return flask.Resposne('Invalid beer id {}'.format(data['beer']), 400)

    # check to see if a favorite was already created for this beer from this
    # user
    try:
        Favorite.objects.get(beer=beer, user=flask.request.user)
    except mongoengine.DoesNotExist:
        pass
    else:
        return flask.Response(
            'You\'ve already favorited beer {}'.format(data['beer']), 400)

    favorite = Favorite(user=flask.request.user, beer=beer)
    try:
        favorite.save()
    except mongoengine.ValidationError as exp:
        return flask.Response('{}'.format(exp), 400)

    return JSONResponse(favorite.to_json())
Esempio n. 23
0
def list(id):
    """Returns a list of all reviews for the given beer"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No beer with id {} found'.format(id), 404)
    except:
        return flask.Resposne('Invalid id {}'.format(id), 400)

    reviews = Review.objects.all().filter(beer=beer)

    if 'sort' in flask.request.values:
        props = [
            'aroma', 'appearance', 'taste', 'palate', 'bottle_style', 'overall'
        ]

        keys = get_sort_keys(flask.request.values['sort'].split(','), props)

        if len(keys) > 0:
            reviews = reviews.order_by(*keys)

    return JSONResponse(reviews.to_json())
Esempio n. 24
0
def put(id):
    """Updates a specific user"""

    try:
        user = User.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No user with id {} found'.format(id), 404)
    except:
        return flask.Response('Invalid id {}'.format(id), 400)

    data = flask.request.get_json()

    # update the email if it's in the data
    if 'email' in data:
        user.email = data['email']

    # if the password is in here, hash it and store it
    if 'password' in data:
        user.password = hashlib.sha256(data['password'].encode('utf-8')).hexdigest()

    user.save()

    return JSONResponse(user.to_json())
Esempio n. 25
0
def put(id, rid):
    """Updates the given review for a beer by ids"""

    try:
        beer = Beer.objects.get(id=id)
    except mongoengine.DoesNotExist:
        return flask.Response('No beer with id {} found'.format(id), 404)
    except:
        return flask.Resposne('Invalid beer id {}'.format(id), 400)

    try:
        review = Review.objects.get(id=rid, beer=beer)
    except mongoengine.DoesNotExist:
        return flask.Response('No review with id {} found'.format(rid), 404)
    except:
        return flask.Response('Invalid review id {}'.format(id), 400)

    data = flask.request.get_json()

    # update an of our simple fields
    props = ['aroma', 'appearance', 'taste', 'palate', 'bottle_style']
    for item in props:
        if item in data:
            setattr(review, item, data[item])

    review.calculate()

    try:
        review.save()
    except mongoengine.ValidationError as exp:
        return flask.Response('{}'.format(exp), 400)

    beer.rating = Review.objects.all().filter(beer=beer).average('overall')
    beer.save()

    return JSONResponse(review.to_json())
Esempio n. 26
0
def get(id):
    """Gets a brewery by id"""

    brewery = Brewery.objects.get(id=id)

    return JSONResponse(brewery.to_json())
Esempio n. 27
0
def delete(id):
    """Deletes the given brewery if no beers are associated with it."""

    brewery = Brewery.objects.get(id=id).delete()

    return JSONResponse()
Esempio n. 28
0
def delete(id):
    Glass.objects.get(id=id).delete()

    return JSONResponse()
Esempio n. 29
0
def get(id):
    glass = Glass.objects.get(id=id)

    return JSONResponse(glass.to_json())
Esempio n. 30
0
def get(id):
    """Returns the given beer by id"""

    beer = Beer.objects.get(id=id)

    return JSONResponse(beer.to_json())