Example #1
0
def get_state(id):
    try:
        numeric_id = url_string_to_number(id)
    except ValueError:
        something_fishy("Malformated id")

    state = State.query.get(numeric_id)
    if state is not None:
        return state.value
    else:
        return Response(status=404)
Example #2
0
def put_state(id):
    # HEPData Explore states can get only so big
    if request.content_length > 10000:
        something_fishy("Request too long.")
    value = request.get_data(as_text=True)

    # Only JSON is allowed (don't try to upload HTML pages, please)
    try:
        json.loads(value)
    except ValueError:
        something_fishy("Invalid JSON.")

    # The id must match the content on a hash function
    if custom_url_hash(value) != id:
        something_fishy("Invalid id.")

    # OK, everything fine so far, let's try saving
    try:
        state = State(url_string_to_number(id), value, request.remote_addr, datetime.now())
        db.session.add(state)
        db.session.commit()
        return Response(status=201)  # OK
    except IntegrityError:
        # The key already exists.
        db.session.rollback()
        return Response(status=204)  # No Content