示例#1
0
def get_volumes():
    current_app.authz.perform_authorization(('/volumes/*', Action.READ))
    q = request.args.get('q', "*:*")
    try:
        from_ = int(request.args.get('from', 0))
    except ValueError:
        raise ApiError("Bad Request",
                       400,
                       details="could not covert 'from' parameter to number")
    try:
        size = int(request.args.get('size', 10))
    except ValueError:
        raise ApiError("Bad Request",
                       400,
                       details="could not covert 'size' parameter to number")
    if size > current_app.config['MAX_RESULTS_PER_PAGE']:
        raise ApiError("Request Entity Too Large",
                       413,
                       details="'size' parameter is too high")

    q_res = current_app.archivant._db.get_books_querystring(query=q,
                                                            from_=from_,
                                                            size=size)
    volumes = map(Archivant.normalize_volume, q_res['hits']['hits'])
    next_args = "?q={}&from={}&size={}".format(q, from_ + size, size)
    prev_args = "?q={}&from={}&size={}".format(
        q, from_ - size if ((from_ - size) > -1) else 0, size)
    base_url = url_for('.get_volumes', _external=True)
    res = {
        'link_prev': base_url + prev_args,
        'link_next': base_url + next_args,
        'total': q_res['hits']['total'],
        'data': volumes
    }
    return jsonify(res)
示例#2
0
def receive_metadata(optional=False):
    if optional and 'metdata' not in request.values:
        return {}
    try:
        metadata = json.loads(request.values['metadata'])
    except KeyError:
        raise ApiError("malformed request",
                       400,
                       details="missing 'metadata' in request")
    except Exception, e:
        raise ApiError("malformed metadata", 400, details=str(e))
示例#3
0
def update_volume(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}'.format(volumeID), Action.UPDATE))
    request.on_json_loading_failed = on_json_load_error
    metadata = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not metadata:
        raise ApiError("Unsupported media type", 415)
    try:
        current_app.archivant.update_volume(volumeID, metadata)
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
示例#4
0
def update_user(userID):
    current_app.authz.perform_authorization(
        ('/users/{}'.format(userID), Action.UPDATE))
    request.on_json_loading_failed = on_json_load_error
    userData = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not userData:
        raise ApiError("Unsupported media type", 415)
    try:
        users.api.update_user(userID, userData)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#5
0
def update_capability(capID):
    current_app.authz.perform_authorization(
        ('/capabilities/{}'.format(capID), Action.UPDATE))
    request.on_json_loading_failed = on_json_load_error
    capData = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not capData:
        raise ApiError("Unsupported media type", 415)
    if 'actions' in capData:
        capData['action'] = Action.from_list(capData.pop('actions'))
    try:
        users.api.update_capability(capID, capData)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#6
0
def add_group():
    current_app.authz.perform_authorization(('/groups/*', Action.CREATE))
    request.on_json_loading_failed = on_json_load_error
    groupData = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not groupData:
        raise ApiError("Unsupported media type", 415)
    name = groupData.get('name', None)
    if not name:
        raise ApiError("Bad Request", 400, details="missing 'name' parameter")
    try:
        group = users.api.add_group(name=name)
    except users.api.ConflictException, e:
        raise ApiError("Conflict", 409, details=str(e))
示例#7
0
def delete_volume(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}'.format(volumeID), Action.DELETE))
    try:
        current_app.archivant.delete_volume(volumeID)
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
示例#8
0
def add_user_to_group(groupID, userID):
    current_app.authz.perform_authorization(
        ('/groups/{}/users/{}'.format(groupID, userID), Action.CREATE))
    try:
        users.api.add_user_to_group(userID, groupID)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#9
0
def get_attachments(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}/attachments/*'.format(volumeID), Action.READ))
    try:
        atts = current_app.archivant.get_volume(volumeID)['attachments']
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
示例#10
0
def delete_capability_from_group(groupID, capID):
    current_app.authz.perform_authorization(
        ('/groups/{}/capabilities/{}'.format(groupID, capID), Action.DELETE))
    try:
        users.api.remove_capability_from_group(capID, groupID)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#11
0
def get_groups_of_user(userID):
    current_app.authz.perform_authorization(
        ('/users/{}/groups/*'.format(userID), Action.READ))
    try:
        groups = [{'id': g.id} for g in users.api.get_groups_of_user(userID)]
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#12
0
def get_capability(capID):
    current_app.authz.perform_authorization(
        ('/capabilities/{}'.format(capID), Action.READ))
    try:
        cap = users.api.get_capability(capID)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#13
0
def delete_group(groupID):
    current_app.authz.perform_authorization(
        ('/groups/{}'.format(groupID), Action.DELETE))
    try:
        users.api.delete_group(id=groupID)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#14
0
def get_users_in_group(groupID):
    current_app.authz.perform_authorization(
        ('/groups/{}/users/*'.format(groupID), Action.READ))
    try:
        us = [{'id': u.id} for u in users.api.get_users_in_group(groupID)]
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#15
0
def get_user(userID):
    current_app.authz.perform_authorization(
        ('/users/{}'.format(userID), Action.READ))
    try:
        u = users.api.get_user(id=userID)
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#16
0
def add_volume():
    current_app.authz.perform_authorization(('/volumes/*', Action.CREATE))
    metadata = receive_volume_metadata()
    try:
        volumeID = current_app.archivant.insert_volume(metadata)
    except ValueError, e:
        raise ApiError("malformed metadata", 400, details=str(e))
示例#17
0
def get_file(volumeID, attachmentID):
    current_app.authz.perform_authorization(
        ('/volumes/{}/attachments/{}'.format(volumeID,
                                             attachmentID), Action.READ))
    try:
        return send_attachment_file(current_app.archivant, volumeID,
                                    attachmentID)
    except NotFoundException, e:
        raise ApiError("file not found", 404, details=str(e))
示例#18
0
def update_attachment(volumeID, attachmentID):
    current_app.authz.perform_authorization(
        ('/volumes/{}/attachments/{}'.format(volumeID,
                                             attachmentID), Action.UPDATE))
    metadata = receive_metadata()
    try:
        current_app.archivant.update_attachment(volumeID, attachmentID,
                                                metadata)
    except ValueError, e:
        raise ApiError("malformed request", 400, details=str(e))
示例#19
0
def get_capabilities_of_group(groupID):
    current_app.authz.perform_authorization(
        ('/groups/{}/capabilities/*'.format(groupID), Action.READ))
    try:
        caps = [
            cap.to_dict()
            for cap in users.api.get_capabilities_of_group(groupID)
        ]
    except users.api.NotFoundException, e:
        raise ApiError("Not found", 404, details=str(e))
示例#20
0
def receive_volume_metadata():
    metadata = receive_metadata()
    # TODO check also for preset consistency?
    requiredFields = ['_language']
    for requiredField in requiredFields:
        if requiredField not in metadata:
            raise ApiError(
                "malformed metadata",
                400,
                details="Required field '{}' is missing in metadata".format(
                    requiredField))
    return metadata
示例#21
0
def add_attachments(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}/attachments/*'.format(volumeID), Action.CREATE))
    metadata = receive_metadata(optional=True)
    if 'file' not in request.files:
        raise ApiError("malformed request",
                       400,
                       details="file not found under 'file' key")
    upFile = request.files['file']
    tmpFileFd, tmpFilePath = tempfile.mkstemp()
    upFile.save(tmpFilePath)
    fileInfo = {}
    fileInfo['file'] = tmpFilePath
    fileInfo['name'] = secure_filename(upFile.filename)
    fileInfo['mime'] = upFile.mimetype
    fileInfo['notes'] = metadata.get('notes', '')
    # close fileDescriptor
    os.close(tmpFileFd)
    try:
        attachmentID = current_app.archivant.insert_attachments(
            volumeID, attachments=[fileInfo])[0]
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
示例#22
0
def add_capability():
    current_app.authz.perform_authorization(('/capabilities/*', Action.CREATE))
    request.on_json_loading_failed = on_json_load_error
    capData = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not capData:
        raise ApiError("Unsupported media type", 415)
    domain = capData.get('domain', None)
    if not domain:
        raise ApiError("Bad Request",
                       400,
                       details="missing 'domain' parameter")
    actions = capData.get('actions', None)
    if not actions:
        raise ApiError("Bad Request",
                       400,
                       details="missing 'actions' parameter")
    cap = users.api.add_capability(domain=domain,
                                   action=Action.from_list(actions))
    link_self = url_for('.get_capability', capID=cap.id, _external=True)
    response = jsonify({'data': {'id': cap.id, 'link_self': link_self}})
    response.status_code = 201
    response.headers['Location'] = link_self
    return response
示例#23
0
@route('/volumes/<volumeID>', methods=['PUT'])
def update_volume(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}'.format(volumeID), Action.UPDATE))
    request.on_json_loading_failed = on_json_load_error
    metadata = request.get_json()
    # the next two lines should be removed when Flask version is >= 1.0
    if not metadata:
        raise ApiError("Unsupported media type", 415)
    try:
        current_app.archivant.update_volume(volumeID, metadata)
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
    except ValueError, e:
        raise ApiError("malformed metadata", 400, details=str(e))
    return make_success_response("volume successfully updated", 201)


@route('/volumes/<volumeID>', methods=['GET'])
def get_volume(volumeID):
    current_app.authz.perform_authorization(
        ('/volumes/{}'.format(volumeID), Action.READ))
    try:
        volume = current_app.archivant.get_volume(volumeID)
    except NotFoundException, e:
        raise ApiError("volume not found", 404, details=str(e))
    return jsonify({'data': volume})


@route('/volumes/<volumeID>', methods=['DELETE'])
示例#24
0
 def not_authorized_handler(error):
     return apiErrorHandler(ApiError('Unauthorized Request', 403))
示例#25
0
 def exceptionHandler(e):
     current_app.logger.exception(e)
     return apiErrorHandler(ApiError("internal server error", 500))
示例#26
0
def getJson(url):
    response = requests.get(url)
    if response.status_code != 200:
        raise ApiError(response.status_code, url)
    return response.json()
示例#27
0
 def apiNotFound(invalid_path):
     raise ApiError("invalid URI", 404)