コード例 #1
0
def upload_file(folder):
    file = request.files.get('file')
    if file is None:
        application.logger.info('no file provided')
        return json_response({'message': 'No file provided.'}, status_code=400)
    elif file.filename == '' or not allowed_file(file.filename):
        application.logger.info('File not allowed "{}"'.format(file.filename))
        return json_response({'message': 'File not allowed.'}, status_code=400)

    path, filename = os.path.split(file.filename)

    if os.sep == '\\':
        path = path.replace('/', '\\')
    else:
        path = path.replace('\\', '/')

    secured_path = secure_path(path)

    fullpath = os.path.join(application.config['tmp_dir'], secured_path)

    os.makedirs(fullpath, exist_ok=True)

    filepath = os.path.join(fullpath, filename)

    file.save(filepath)
    application.logger.info('file saved "{}"'.format(filepath))
    return json.dumps({'success': request.json}), 200, {
        'ContentType': 'application/json'
    }
コード例 #2
0
def get_place_by_id():

    # print(request.form)
    if not (request.is_json and 'place_id' in request.json):
        return json_response(
            "fail",
            "Request contains no JSON body or required field",
            400
        )


    try:
        res = db.place_collection.find_one({'_id': ObjectId(request.json["place_id"])})
        ids2posts = {}

        res["_id"] = str(res["_id"])
        cur_id = res["_id"]
        post_res = db.post_collection.find({"place_id": cur_id})
        ids2posts[cur_id] = []
        for post in post_res:
            post["_id"] = str(post["_id"])
            ids2posts[cur_id].append(post)
    except:
        return json_response(
            "fail",
            "Database error",
            500
        )

    res = [res]
    return return_complex_json(res, ids2posts, message='Retrieved all places info')
コード例 #3
0
def boats_post():
    owner = verify()
    if not owner:
        return json_response(401, error_msg='Invalid JWT')
    if 'application/json' in request.content_type:
        content = request.get_json()
        try:
            validate(instance=content, schema=constants.boats_schema)
        except:
            return resource_not_found_400(
                "The request object is missing at least one of the required attributes"
            )
        if 'application/json' not in request.accept_mimetypes:
            return json_response(
                406, error_msg='Content must be returned in JSON format')
        error_msg = name_validator(client, content, constants.boats)
        if not error_msg:
            new_boat = datastore.entity.Entity(key=client.key(constants.boats))
            content['owner'] = owner
            payload = Boat(content)
            new_boat.update(payload.update_data())
            client.put(new_boat)
            return jsonify(payload.api_return(new_boat.id)), 201
        elif 'unique' in error_msg:
            return json_response(403, error_msg=f'{error_msg}')
        else:
            return json_response(400, error_msg=f'{error_msg}')

    return json_response(400, error_msg='Body must be in JSON format')
コード例 #4
0
ファイル: server.py プロジェクト: jeffhou/aMuseMeBackend
def get_artist():
    artist_name = request.args.get('artist')
    if artist_name:
        artist = cache.get('artist:%s' % artist_name)
        if artist is None:
            artist = lastfm.get_artist(artist_name)
            cache.set('artist:%s' % artist_name, artist, timeout=5*60)
        return json_response(artist)
    else:
        return json_response({})
コード例 #5
0
def boats_get_boat(boat_id):
    if 'application/json' in request.accept_mimetypes:
        boat_data = id_validator(client, boat_id, constants.boats)
        if boat_data:
            boat = Boat(boat_data)
            if 'application/json' in request.accept_mimetypes:
                return jsonify(boat.api_return(boat_id))
            else:
                return json_response(
                    406, error_msg='Content must be in JSON or HTML format')
        return json_response(404, error_msg='No boat with this boat_id exists')
    return json_response(406, error_msg='Content must be in JSON format')
コード例 #6
0
def gar_col_place():


    if not (request.is_json
            and 'address' in request.json
            and 'coordinates' in request.json
            and 'type' in request.json
            and 'garbage_type' in request.json):
        return json_response(
            "fail",
            "Request contains no JSON body or required field",
            400
        )

    place_item = {

        "address": request.json["address"],
        "coordinates": {"lat": request.json["coordinates"]["lat"], "lon": request.json["coordinates"]["lon"]},
         "type": request.json["type"],
        "garbage_type": request.json["garbage_type"],
        "feedback_ids": []
                        }

    if "additional_info" in request.json:
        material_info = request.json["additional_info"].get("material_info", None)
        contacts = request.json["additional_info"].get("contacts", None)
        pics = request.json["additional_info"].get("pictures", None)
        text = request.json["additional_info"].get("text", None)
        place_item["additional_info"] = {"material_info": material_info,
                                         "contacts": contacts,
                                         "pictures": pics,
                                         "text": text}

    else:
        place_item["additional_info"] = None

    try:
        db.place_collection.insert_one(place_item)
        return json_response(
            "success",
            "Place is added",
            200
        )

    except:
        return json_response(
            "fail",
            "Database error",
            500
        )
コード例 #7
0
def gDisconnect():
    access_token = login_session.get('access_token')
    if not access_token:
        return h.json_response('Current user is not connected.', 401)

    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' %access_token
    http = httplib2.Http()
    result = http.request(url, 'GET')[0]

    if result['status'] == '200':
        h.clear_login_session()
        return h.redirect_books()

    else:
        h.clear_login_session()
        return h.json_response('Failed to revoke token for given user.', 400)
コード例 #8
0
def get_all_places():


    try:
        res_1 = []
        res = db.place_collection.find()
        ids2posts = {}
        for elem in res:
            elem["_id"] = str(elem["_id"])
            res_1.append(elem)
            cur_id = elem["_id"]
            post_res = db.post_collection.find({ "place_id": cur_id } )
            ids2posts[cur_id] = []
            for post in post_res:
                post["_id"] = str(post["_id"])
                if cur_id in ids2posts:

                    ids2posts[cur_id].append(post)

                else:
                    ids2posts[cur_id] = [post]
    except:
        return json_response(
            "fail",
            "Database error",
            500
        )

    # print(ids2posts)
    # print(res_1)
    return return_complex_json(res_1, ids2posts, message='Retrieved all places info')
コード例 #9
0
def boats_get_loads(boat_id):
    if 'application/json' in request.accept_mimetypes:
        boat_data = id_validator(client, boat_id, constants.boats)
        if boat_data:
            boat = Boat(boat_data)
            return jsonify(boat.display_loads(client))
        return resource_not_found_404("No boat with this boat_id exists")
    return json_response(406, error_msg='Content must be in JSON format')
コード例 #10
0
ファイル: loads.py プロジェクト: ericarmstr0ng/MarinaApi
def loads_unload(load_id):
    owner = verify()
    if not owner:
        return json_response(401, error_msg='Invalid JWT')
    load = id_validator(client, load_id, constants.loads)
    if load:
        unload_load(client, load_id)
        return '', 204
    return resource_not_found_404("No load with this load_id exists")
コード例 #11
0
def boats_delete(boat_id):
    owner = verify()
    if not owner:
        return json_response(401, error_msg='Invalid JWT')
    boat = id_validator(client, boat_id, constants.boats)
    if boat:
        key = client.key(constants.boats, int(boat_id))
        client.delete(key)
        return '', 204
    return resource_not_found_404("No boat with this boat_id exists")
コード例 #12
0
def gConnect():

    # Validate state token
    if request.args.get('state') != login_session['state']:
        return h.json_response('Invalid state parameter.', 401)

    # Obtain authorization code
    code = request.data

    # Upgrade the authorization code into a credentials object
    try:
        oaht_flow = flow_from_clientsecrets('client_secrets.json', scope='')
        oaht_flow.redirect_uri = 'postmessage'
        credentials = oaht_flow.step2_exchange(code)

    except FlowExchangeError:
        return h.json_response('Failed to upgrade the authorization code.', 401)

    # Check that the access token is valid
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
           %access_token)
    http = httplib2.Http()
    result = json.loads(http.request(url, 'GET')[1].decode())

    # If there was an error in the access token info, abort.
    error = result.get('error')
    if error:
        return h.json_response(error, 500)

    gplus_id = credentials.id_token['sub']

    # Verify that the access token is used for the intended user.
    if result['user_id'] != gplus_id:
        return h.json_response("Token's user ID doesn't match given user ID.", 401)

    # Verify that the access token is valid for this app.
    if result['issued_to'] != CLIENT_ID:
        return h.json_response("Token's client ID does not match app's.", 401)

    stored_access_token = login_session.get('access_token')
    stored_gplus_id = login_session.get('gplus_id')

    if stored_access_token is not None and gplus_id == stored_gplus_id:
        return h.json_response('Current user is already connected.', 200)

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    # Store the access token and user data in the session for later use.
    h.save_current_user_info(credentials, data)

    user = dbh.create_or_update_current_user_from_login_session()
    if user:
        return h.redirect_books()
コード例 #13
0
def load_cargo(boat_id):
    owner = verify()
    if not owner:
        return json_response(401, error_msg='Invalid JWT')
    if 'application/json' in request.accept_mimetypes:
        content = request.get_json()
        try:
            validate(instance=content, schema=constants.load_boat_schema)
        except:
            return resource_not_found_400(
                "The request object is missing at least one of the required attributes"
            )
        load_id = content["id"]
        boat_data = id_validator(client, boat_id, kind=constants.boats)
        load_data = id_validator(client, load_id, kind=constants.loads)
        if boat_data and load_data:
            if not load_data["carrier"]:
                boat = Boat(boat_data)
                load_carrier = {
                    "id": load_id,
                    "self": f"{request.url_root}loads/{load_id}"
                }
                load = Load(load_data)
                boat_carrier = {
                    "id": boat_id,
                    "name": boat_data["name"],
                    "self": f"{request.url_root}/boats/{boat_id}"
                }
                load.add_carrier(boat_carrier)
                boat.loads.append(load_carrier)
                update_entity(client, boat_id, constants.boats, boat)
                update_entity(client, load_id, constants.loads, load)
                return json_response(204, error_msg='OK')
            return resource_not_found_400("Load already assigned to a boat")
        return resource_not_found_404(
            "The specified boat and/or load don’t exist")
    return json_response(406, error_msg='Content must be in JSON format')
コード例 #14
0
def boats_patch(boat_id):
    owner = verify()
    if not owner:
        return json_response(401, error_msg='Invalid JWT')
    if 'application/json' in request.accept_mimetypes:
        boat_data = id_validator(client, boat_id, constants.boats)
        if boat_data:
            content = request.get_json()
            try:
                validate(instance=content, schema=constants.patch_schema)
            except:
                return resource_not_found_400(
                    "The request object has incorrect attributes")
            boat = Boat(boat_data)
            boat.patch_data(content)
            error_msg = name_validator(client, content, constants.boats,
                                       boat_id)
            if error_msg:
                return json_response(403, error_msg=f'{error_msg}')
            update_entity(client, boat_id, constants.boats, boat)
            return jsonify(boat.api_return(boat_id))

        return resource_not_found_404("No boat with this boat_id exists")
    return json_response(406, error_msg='Content must be in JSON format')
コード例 #15
0
ファイル: server.py プロジェクト: jeffhou/aMuseMeBackend
def get_random():
    genre = request.args.get('genre')
    if genre:
        song = query_db(
            'select * from popularities where genre=? order by random() limit 1',
            args=[genre], one=True)
    else:
        song = query_db(
            'select * from popularities order by random() limit 1',
            one=True)

    lookup = itunes.lookup(song['atom_id'])
    fields = ['trackName', 'previewUrl', 'artworkUrl100', 'collectionName',
              'artistName']
    for field in fields:
        if field in lookup:
            song[field] = lookup[field]
    return json_response(song)
コード例 #16
0
def get_state(request):
    logger.info('Incoming {} request'.format(request.path))

    session = yield from get_session(request)
    user_id = get_user_id(session)

    logger.debug('Wait for free redis connection from pool')
    with (yield from request.app.redis_pool) as redis:
        logger.debug('Redis connection waiting finished')

        logger.debug('Get field from redis')
        field = yield from redis.lrange(field_db_key.format(user_id), 0, -1, encoding='utf-8')

        if not field:
            logger.debug('User does not have a field. Creating...')
            field = create_empty_field()
            logger.debug('Write user field to Redis...')
            yield from redis.lpush(field_db_key.format(user_id), *field)

        return json_response({
            'field': field,
            'field_size': settings.FIELD_SIZE
        })
コード例 #17
0
def boats_get():
    if 'application/json' in request.accept_mimetypes:
        payload = []
        query = client.query(kind=constants.boats)
        q_limit = int(request.args.get('limit', '5'))
        q_offset = int(request.args.get('offset', '0'))
        l_iterator = query.fetch(limit=q_limit, offset=q_offset)
        pages = l_iterator.pages
        results = list(next(pages))
        if l_iterator.next_page_token:
            next_offset = q_offset + q_limit
            next_url = request.base_url + "?limit=" + str(
                q_limit) + "&offset=" + str(next_offset)
        else:
            next_url = None
        for e in results:
            boat_data = id_validator(client, e.key.id, constants.boats)
            boat = Boat(boat_data)
            payload.append(boat.api_return(e.key.id))
            output = {constants.boats: payload}
        if next_url:
            output["next"] = next_url
        return jsonify(output)
    return json_response(406, error_msg='Content must be in JSON format')
コード例 #18
0
 async def put(self):
     async with self.aquire_db() as conn:
         await self.update_note(conn)
         return json_response(data=await self.get_note(conn))
コード例 #19
0
ファイル: server.py プロジェクト: jeffhou/aMuseMeBackend
def get_genres():
    genres = [item['genre']
              for item in query_db('select distinct genre from popularities')]
    return json_response(genres)
コード例 #20
0
 async def post(self):
     params = await self.get_request_params()
     async with self.aquire_db() as conn:
         cursor = await conn.execute(db.note.insert(params))
     return json_response(data="ok")
コード例 #21
0
def gar_col_place_feedback():


    if not (request.is_json
            and 'address' in request.json
            and 'coordinates' in request.json
            and 'type' in request.json
            and 'garbage_type' in request.json
            and 'feedback' in request.json):
        return json_response(
            "fail",
            "Request contains no JSON body or required field",
            400
        )

    if not('place_info_rating' in request.json["feedback"]):
        return json_response(
            "fail",
            "Request contains no JSON body or required field",
            400
        )

    place_item = {

        "address": request.json["address"],
        "coordinates": {"lat": request.json["coordinates"]["lat"], "lon": request.json["coordinates"]["lon"]},
         "type": request.json["type"],
        "garbage_type": request.json["garbage_type"],
        "feedback_ids": []
                        }

    if "additional_info" in request.json:
        material_info = request.json["additional_info"].get("material_info", None)
        contacts = request.json["additional_info"].get("contacts", None)
        pics = request.json["additional_info"].get("pictures", None)
        text = request.json["additional_info"].get("text", None)
        place_item["additional_info"] = {"material_info": material_info,
                                         "contacts": contacts,
                                         "pictures": pics,
                                         "text": text}

    post_item = {
        "place_id": None,
        "place_info_rating": request.json["feedback"]["place_info_rating"]
    }
    if "all_correct" in request.json["feedback"]:
        all_correct = request.json["feedback"].get("all_correct", None)
        post_item["all_correct"]= all_correct
    else:
        post_item["all_correct"] = None

    if "feedback" in request.json["feedback"]:
        wrong = request.json["feedback"]["feedback"].get("wrong", None)
        correct = request.json["feedback"]["feedback"].get("correct", None)
        additional_info = request.json["feedback"]["feedback"].get("additional_info", None)
        post_item["feedback"] = {
                                         "wrong": wrong,
                                        "correct": correct,
                                         "additional_info": additional_info}
    else:
        post_item["feedback"] = None

    # try:

    id = db.place_collection.insert_one(place_item)
    post_item["place_id"] = str(id.inserted_id)

    id1 = db.post_collection.insert_one(post_item)
    res = db.place_collection.find_one({'_id': ObjectId(id.inserted_id)})
    existing = res["feedback_ids"]
    if existing is None or len(existing) == 0:
        existing = [str(id1.inserted_id)]
    else:
        existing.append(str(id1.inserted_id))
    print(existing)

    db.place_collection.update_one({
        '_id': res['_id']
    }, {
        '$set': {
            'feedback_ids': existing
        }
    }, upsert=False)

    return json_response(
        "success",
        "Post is added",
        200
    )
コード例 #22
0
def give_feedback():


    if not (request.is_json
            and 'place_id' in request.json
            and 'place_info_rating' in request.json):
        return json_response(
            "fail",
            "Request contains no JSON body or required field",
            400
        )

    post_item = {

        "place_id": request.json["place_id"],
        "place_info_rating": request.json["place_info_rating"]
                        }
    if "all_correct" in request.json:
        all_correct = request.json.get("all_correct", None)
        post_item["all_correct"]= all_correct
    else:
        post_item["all_correct"] = None

    if "feedback" in request.json:
        wrong = request.json["feedback"].get("wrong", None)
        correct = request.json["feedback"].get("correct", None)
        additional = request.json["feedback"].get("additional_info", None)
        post_item["feedback"] = {
                                         "wrong": wrong,
                                         "correct": correct,
                                            "additional_info": additional}

    else:
        post_item["feedback"] = None
    #
    try:
        id = db.post_collection.insert_one(post_item)
        res = db.place_collection.find_one({'_id': ObjectId(request.json["place_id"])})
        existing = res["feedback_ids"]
        if existing is None or len(existing) == 0:
            existing = [str(id.inserted_id)]
        else:
            existing.append(str(id.inserted_id))
        print(existing)

        db.place_collection.update_one({
              '_id': res['_id']
            },{
              '$set': {
                'feedback_ids': existing
              }
            }, upsert=False)

        return json_response(
            "success",
            "Post is added",
            200
        )

    except Exception as e:
        print(e)
        return json_response(
            "fail",
            "Database error",
            500
        )
コード例 #23
0
def userJSON(user_id):
    user = dbh.get_user_by_id(user_id)
    if not user:
        return h.json_response("User doesn't exist", 404)
    return jsonify(user.serialize)
コード例 #24
0
def genreJSON(genre_id):
    genre = dbh.get_genre_by_id(genre_id)
    if not genre:
        return h.json_response("Genre doesn't exist", 404)
    return jsonify(genre.serialize)
コード例 #25
0
def bookJSON(book_id):
    book = dbh.get_book_by_id(book_id)
    if not book:
        return h.json_response("Book doesn't exist", 404)
    return jsonify(dbh.get_book_by_id(book_id).serialize)
コード例 #26
0
def boats_405():
    return json_response(
        405, error_msg='Edit or delete of all boats is not allowed')
コード例 #27
0
 async def get(self):
     async with self.aquire_db() as conn:
         cursor = await conn.execute(db.note.select())
         records = await cursor.fetchall()
         notes = [dict(n) for n in records]
         return json_response(data={'notes': notes})