コード例 #1
0
def restaurants():
    #""" Get All Restaurants. """
    if request.method == 'GET':
        restaurants = Restaurant.query.all()
        response = jsonify({
            'restaurants':
            [restaurant.to_dict() for restaurant in restaurants],
            '_link':
            url_for('api.restaurants')
        })
        response.headers['Location'] = url_for('api.restaurants')
        return response

    #""" Create a restaurant. """
    elif request.method == 'POST':
        data = request.get_json() or {}

        if 'name' not in data and 'email' not in data and 'contact' not in data:
            return bad_request(
                'Restaurant name, email and contact was missing from the request.'
            )
        if 'name' not in data:
            return bad_request('Restaurant name was missing from the request.')
        if 'email' not in data:
            return bad_request('Email was missing from the request.')
        if 'contact' not in data:
            return bad_request('Contact was missing from the request.')
        if Restaurant.query.filter_by(name=data['name']).first():
            return bad_request('This Restaurant name is already registered.')
        if Restaurant.query.filter_by(email=data['email']).first():
            return bad_request(
                'This email is already in use by another restuarant. Please use a different email.'
            )

        restaurant = Restaurant()
        restaurant.from_dict(data)

        db.session.add(restaurant)
        db.session.commit()
        response = jsonify(restaurant.to_dict())
        response.status_code = 201
        response.headers['Location'] = url_for('api.restaurant',
                                               id=restaurant.id)
        return response

    #""" PUT method not allowed on this endpoint. """
    elif request.method == 'PUT':
        return bad_request(
            "You cannot update a restaurant on this end point. Use this for a PUT request with an id: "
            + url_for('api.restaurant') + "/<id>")

    #""" DELETE method not allowed on this endpoint. """
    elif request.method == 'DELETE':
        return bad_request(
            "You cannot delete a restaurant on this end point. Use this for a DELETE request with an id: "
            + url_for('api.restaurant') + "/<id>")

    else:
        return bad_request("That's a bad request.")