Ejemplo n.º 1
0
def fetch_es_poi(id, es) -> dict:
    """Returns the raw POI data
    @deprecated by fetch_es_place()

    This function gets from Elasticsearch the
    entry corresponding to the given id.
    """
    es_pois = es.search(index='munin_poi',
                        body={"filter": {
                            "term": {
                                "_id": id
                            }
                        }})

    es_poi = es_pois.get('hits', {}).get('hits', [])
    if len(es_poi) == 0:
        raise NotFound(detail={'message': f"poi '{id}' not found"})
    result = es_poi[0]['_source']

    # Flatten properties into result
    properties = {
        p.get('key'): p.get('value')
        for p in result.get('properties')
    }
    result['properties'] = properties
    return result
Ejemplo n.º 2
0
def fetch_es_place(id, es, indices, type) -> dict:
    """Returns the raw Place data

    This function gets from Elasticsearch the
    entry corresponding to the given id.
    """
    if type is None:
        index_name = PLACE_DEFAULT_INDEX
    elif type not in indices:
        raise BadRequest(
            status_code=400,
            detail={"message": f"Wrong type parameter: type={type}"}
        )
    else:
        index_name = indices.get(type)

    try:
        es_places = es.search(index=index_name,
            body={
                "filter": {
                    "term": {"_id": id}
                }
            })
    except ElasticsearchException as error:
        logger.warning(f"error with database: {error}")
        raise HTTPException(detail='database issue', status_code=503)

    es_place = es_places.get('hits', {}).get('hits', [])
    if len(es_place) == 0:
        raise NotFound(detail={'message': f"place {id} not found with type={type}"})
    if len(es_place) > 1:
        logger.warning("Got multiple places with id %s", id)

    return es_place[0]
Ejemplo n.º 3
0
def fetch_es_place(id, es, indices, type) -> list:
    """Returns the raw Place data

    This function gets from Elasticsearch the
    entry corresponding to the given id.
    """
    if type is None:
        index_name = "munin"
    elif type not in indices:
        raise BadRequest(
            status_code=400,
            detail={"message": f"Wrong type parameter: type={type}"}
        )
    else:
        index_name = indices.get(type)

    es_places = es.search(index=index_name,
        body={
            "filter": {
                "term": {"_id": id}
            }
        })

    es_place = es_places.get('hits', {}).get('hits', [])
    if len(es_place) == 0:
        raise NotFound(detail={'message': f"place {id} not found with type={type}"})

    return es_place
Ejemplo n.º 4
0
def patients_detail(session: Session, patient_id: int) -> PatientSchema:
    """
    Get patient details
    """
    try:
        pat = get_object_or_404(session.Patient, id=patient_id)
    except Http404 as e:
        raise NotFound(str(e))
    return PatientSchema(pat)
Ejemplo n.º 5
0
def patients_update(session: Session, patient_id: int,
                    patient: PatientUpdateSchema) -> PatientSchema:
    """
    modify patients
    """
    a = session.Patient.objects.filter(id=patient_id).update(**patient)
    if not a:
        raise NotFound('Patient id not found')
    updated_patient = session.Patient.objects.get(id=patient_id)
    return PatientSchema(updated_patient)
Ejemplo n.º 6
0
 async def func(id: int, data: model._scheme, session: Session):
     if data:
         data.pop('id')
     obj = session.query(model).filter(model.id == id).first()
     if not obj:
         raise NotFound()
     for key, value in data.items():
         setattr(obj, key, value)
     session.commit()
     return obj.render()
Ejemplo n.º 7
0
    def get_place(self, id):
        internal_id = id.replace(self.PLACE_ID_PREFIX, '', 1)

        es_places = self.es.search(
            index=self.es_index,
            body={"filter": {
                "term": {
                    "_id": internal_id
                }
            }})

        es_place = es_places.get('hits', {}).get('hits', [])
        if len(es_place) == 0:
            raise NotFound(detail={'message': f"place {id} not found"})
        if len(es_place) > 1:
            logger.warning("Got multiple places with id %s", id)
        return PjPOI(es_place[0]['_source'])
Ejemplo n.º 8
0
def delete_note(session: Session, note: int, auth: Auth):
    """
    This endpoint deletes note
    """
    instance = session.query(Note).filter(
        Note.id == note,
        Note.user_id == auth.user.id
    ).first()

    if not instance:
        raise NotFound({'message': 'Note not found'})

    session.delete(instance)
    session.commit()
    return Response(
        status=200,
        content={'message': 'Note Deleted'}
    )
Ejemplo n.º 9
0
def fetch_es_poi(id, es) -> dict:
    """Returns the raw POI data
    @deprecated by fetch_es_place()

    This function gets from Elasticsearch the
    entry corresponding to the given id.
    """
    es_pois = es.search(index=PLACE_POI_INDEX,
                        body={
                            "filter": {
                                "term": {"_id": id}
                            }
                        })

    es_poi = es_pois.get('hits', {}).get('hits', [])
    if len(es_poi) == 0:
        raise NotFound(detail={'message': f"poi '{id}' not found"})
    return es_poi[0]['_source']
Ejemplo n.º 10
0
def delete_category(session: Session, category: int, auth: Auth):
    """
    This endpoint deletes category
    """
    instance = session.query(Category).filter(
        Category.id == category,
        Category.user_id == auth.user.id
    ).first()

    if not instance:
        raise NotFound({'message': 'Category not found'})

    session.delete(instance)
    session.commit()
    return Response(
        status=200,
        content={'message': 'Category Deleted'}
    )
Ejemplo n.º 11
0
def fetch_closest(lat, lon, max_distance, es):
    es_addrs = es.search(index=','.join([PLACE_ADDRESS_INDEX,PLACE_STREET_INDEX]),
        body={
            "query": {
                "function_score": {
                    "query": {
                        "match_all": {}
                    },
                    "boost_mode": "replace", 
                    "functions": [
                        {
                            "gauss": {
                                "coord": {
                                    "origin": {
                                        "lat": lat,
                                        "lon": lon
                                    },
                                    "scale": "{}m".format(max_distance)
                                }
                            }
                        }
                    ]
                }
            },
            "filter": {
                "geo_distance": {
                    "distance": "{}m".format(max_distance),
                    "coord": {
                        "lat": lat,
                        "lon": lon
                    },
                    "distance_type": "plane"
                }
            },
            "from": 0,
            "size": 1
        }
    )
    es_addrs = es_addrs.get('hits', {}).get('hits', [])
    if len(es_addrs) == 0:
        raise NotFound(detail={'message': f"nothing around {lat}:{lon} within {max_distance}m..."})
    return es_addrs[0]
Ejemplo n.º 12
0
def update_category(session: Session, category: int, auth: Auth,
                    data: CategoryCreate):
    """
    This endpoint updated category
    """
    instance = session.query(Category).filter(
        Category.id == category,
        Category.user_id == auth.user.id
    ).first()

    if not instance:
        raise NotFound({'message': 'Category not found'})

    instance.name = data['name']
    session.commit()
    return CategoryList(
        session.query(Category).filter(
            Category.id == instance.id
        ).first()
    )
Ejemplo n.º 13
0
def generate_api_key(player_slug: str, login_payload: Login) -> dict:
    """
    Generate a new API Key for the player.
    If an old key already exist, it will be deleted.
    """
    player = Player.objects(slug=player_slug).first()
    if not player:
        raise NotFound(f"Player {player_slug} not found.")

    if (not bcrypt.hashpw(login_payload.password.encode("utf-8"),
                          player.password.encode("utf-8")).decode("utf-8")
            == player.password):
        raise Forbidden("Wrong password")

    old_api_key = ApiKey.objects(player=player)
    if old_api_key:
        for key in old_api_key:
            key.delete()

    new_api_key = ApiKey(player=player)
    new_api_key.save()
    return mongo_to_dict(new_api_key)
Ejemplo n.º 14
0
def update_note(session: Session, note: int, auth: Auth, data: NoteCreate):
    """
    This endpoint updates note
    """
    instance = session.query(Note).filter(
        Note.id == note,
        Note.user_id == auth.user.id
    ).first()

    if not instance:
        raise NotFound({'message': 'Note not found'})

    instance.title = data['title']
    instance.text = data['text']
    instance.device_token = data['device_token']

    if data.get('reminder_date'):
        try:
            instance.reminder_date = datetime.strptime(
                data['reminder_date'], '%Y/%m/%d %H:%M'
            )
        except ValueError:
            raise ValidationError({
                'message': 'invalid reminder date'
            })

    if data.get('category'):
        category = session.query(Category).filter(
            Category.id == data['category'],
            Note.user_id == auth.user.id
        ).first()

        if not category:
            raise ValidationError({'message': 'Invalid category'})

        instance.category_id = category.id

    session.commit()
    return NoteList(session.query(Note).filter(Note.id == note).first())
Ejemplo n.º 15
0
 async def func(id: int, session: Session):
     deleted = session.query(model).filter(model.id == id).delete()
     if not deleted:
         raise NotFound()
     session.commit()
     return http.Response(status=204)
Ejemplo n.º 16
0
def get_or_404(model: models, id: [str, int]):
    try:
        item = get_object_or_404(model, id=id)
    except Http404 as e:
        raise NotFound(str(e))
    return item
Ejemplo n.º 17
0
 async def func(id: int, session: Session):
     obj = session.query(model).filter(model.id == id).first()
     if not obj:
         raise NotFound()
     return obj.render()