Ejemplo n.º 1
0
def login() -> Json:
    """
    request:
        name: str,
        pwhash: str
    """
    post_data = request.get_json()
    response: ApiResponse = {}

    if is_ApiRequest(post_data):
        stored = {}
        login_req = post_data.get('request')
        name: str = login_req.get("name")
        pwhash: str = login_req.get("pwhash")

        with open('dataGetter/static/pw.json', 'r') as f:
            stored = json.loads(f.read())

        if name == stored['name'] \
                and pwhash == stored['pwhash']:
            response = ApiResponse(status=ReturnCode.OK.value,
                                   message="logined")
            return jsonify(response)

        response = ApiResponse(
            status=ReturnCode.BAD_REQUEST.value,
            message="login failed. invalid name or password.")
        return jsonify(response)

    response = ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                           message="bad request format")
    return jsonify(response)
Ejemplo n.º 2
0
def spot_paged(pid: Optional[int] = None):
    """
    Either return paged spot data or paged spot data under
    a given project.
    """
    post_data = request.get_json()
    if is_ApiRequest(post_data):
        paging_request: PagingRequest = post_data['request']
        size, pageNo = itemgetter('size', 'pageNo')(paging_request)

        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.OK.value, message=f"get spot page {pageNo}"))

        if pid is None:
            spots_page = Spot.query.paginate(pageNo, size)
        else:
            spots_page = (Spot.query.filter_by(project_id=pid).paginate(
                pageNo, size))

        response_object['data'] = {
            'data': [item.to_json() for item in spots_page.items if item],
            'totalElementCount': spots_page.total,
            'currentPage': pageNo,
            'pageSize': size
        }

    else:
        response_object = (ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                                       message="bad request format"))

    return jsonify(response_object)
Ejemplo n.º 3
0
def device_paged(sid: Optional[int] = None):
    """ Return a specific page of data"""
    post_data = request.get_json()

    if is_ApiRequest(post_data):
        paging_request: PagingRequest = post_data['request']
        size, pageNo = itemgetter('size', 'pageNo')(paging_request)

        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.OK.value, message=f"get device page {pageNo}"))

        if sid is None:
            devices_page = Device.query.paginate(pageNo, size)
        else:
            devices_page = Device.query.filter_by(spot_id=sid).paginate(
                pageNo, size)

        response_object['data'] = {
            'data': [item.to_json() for item in devices_page.items if item],
            'totalElementCount': devices_page.total,
            'currentPage': pageNo,
            'pageSize': size
        }

    else:
        response_object = (ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                                       message="bad request format"))
    return jsonify(response_object)
Ejemplo n.º 4
0
def spot_record_paged(did: int):
    """ Return a specific page of data"""
    post_data = request.get_json()
    if is_ApiRequest(post_data):
        paging_request: PagingRequest = post_data['request']
        size, pageNo = itemgetter('size', 'pageNo')(paging_request)

        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.OK.value,
            message=f"get spot_record page {pageNo}"))

        # never send all records
        if pageNo * size > SpotRecord.query.filter_by(device_id=did).count():
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = f"query out of range for device {did}"
        else:
            spot_records_page = (SpotRecord.query.filter_by(
                device_id=did).order_by(desc(
                    SpotRecord.spot_record_time)).paginate(pageNo, size))
            response_object['data'] = {
                'data':
                [item.to_json() for item in spot_records_page.items if item],
                'totalElementCount':
                spot_records_page.total,
                'currentPage':
                pageNo,
                'pageSize':
                size
            }

    else:
        response_object = (ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                                       message="bad request format"))

    return jsonify(response_object)
Ejemplo n.º 5
0
def sport_record_filtered(did: Optional[int]) -> Json:
    post_data = request.get_json()

    if is_ApiRequest(post_data) and did is not None:
        filter_request = post_data['request']
        start, end = map(str_to_datetime,
                         itemgetter("startTime", "endTime")(filter_request))

        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.OK.value, message=f"filted sport record {did}"))

        filtered_res = (SpotRecord.query.filter(
            SpotRecord.device_id == did).filter(
                SpotRecord.spot_record_time >= start).filter(
                    SpotRecord.spot_record_time <= end))

        response_object['data'] = {
            'data': [item.to_json() for item in filtered_res if item],
            'totalElementCount': filtered_res.count(),
        }

    else:
        response_object = (ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                                       message="bad request format"))
    return jsonify(response_object)
Ejemplo n.º 6
0
def device_filtered() -> Json:
    post_data = request.get_json()

    if is_ApiRequest(post_data):
        filter_request = post_data['request']
        start, end = map(
            str_to_datetime,
            itemgetter(
                "startTime",
                "endTime",
                "keyword",
            )(filter_request))

        response_object: ApiResponse = (ApiResponse(status=ReturnCode.OK.value,
                                                    message="filted device"))

        filtered_res = (SpotRecord.query.filter(
            Device.create_time >= start).filter(
                Device.modify_time <= end).filter(
                    Device.device_name == "keyword"))

        response_object['data'] = {
            'data': [item.to_json() for item in filtered_res if item],
            'totalElementCount': filtered_res.count(),
        }

    else:
        response_object = (ApiResponse(status=ReturnCode.BAD_REQUEST.value,
                                       message="bad request format"))
    return jsonify(response_object)
Ejemplo n.º 7
0
    def handle_put(post_data: Optional[ApiRequest]) -> ApiResponse:

        response_object: ApiResponse = (
            ApiResponse(status=ReturnCode.OK.value))

        if post_data is None \
                or not is_ApiRequest(cast(Optional[Dict], post_data)):
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = "post failed "
            return response_object

        try:
            updated = update(cast(Dict, post_data["request"]))
            if updated:
                commit()
                response_object['message'] = "update succeeded!"
                response_object["data"] = updated.to_json()
            else:
                response_object['status'] = ReturnCode.NO_DATA.value
                response_object['message'] = "update failed"

        except IntegrityError:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object["message"] = (
                "update failed!, integrity error. might be missing a field")

        except Exception as e:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = f"update failed {e}"

        finally:
            return response_object
Ejemplo n.º 8
0
def project_view():
    """ project, companies, and climate_area """

    response_object = (ApiResponse(status=ReturnCode.OK.value,
                                   message='project added successfully'))

    # post successful or get. resend the updated reponse.
    projects = [p.to_json() for p in Project.query.all() if p]
    response_object["data"] = projects

    return jsonify(response_object)
Ejemplo n.º 9
0
def project_pic_view(pid):
    """send project picture for given project"""
    response_object: ApiResponse = (ApiResponse(
        status=ReturnCode.OK.value,
        message="project pictures are sent successfully"))

    project_images = ProjectDetail.query.filter_by(project_id=pid).all()
    project_images_json = [p.to_json() for p in project_images if p]
    response_object['data'] = project_images_json

    return jsonify(response_object)
Ejemplo n.º 10
0
def project_paged():
    """ Return a specific page of data"""
    post_data = request.get_json()
    if is_ApiRequest(post_data):
        paging_request: PagingRequest = post_data['request']
        size, pageNo = itemgetter('size', 'pageNo')(paging_request)

        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.OK.value, message=f"get project page {pageNo}"))

        projects_page = Project.query.paginate(pageNo, size)
        response_object['data'] = {
            'data': [item.to_json() for item in projects_page.items if item],
            'totalElementCount': projects_page.total,
            'currentPage': pageNo,
            'pageSize': size
        }

    else:
        response_object: ApiResponse = (ApiResponse(
            status=ReturnCode.BAD_REQUEST.value, message="bad request format"))

    return jsonify(response_object)
Ejemplo n.º 11
0
def realtime_device() -> Json:
    """
    return list of device that are online.
    """
    online_devices = (
        Device
        .query
        .filter(Device.online))

    response_object = (
        ApiResponse(status=ReturnCode.OK.value,
                    message="data fetched",
                    data=[device.to_json() for device in online_devices]))

    return jsonify(response_object)
Ejemplo n.º 12
0
    def handle_delete() -> ApiResponse:
        response_object: ApiResponse = (
            ApiResponse(status=ReturnCode.OK.value))

        try:
            if some_id is None:
                raise Exception("Error when deleting, id is None")
            delete(some_id)
            commit()
            response_object["message"] = "remvoe succeeded"
        except Exception as e:
            response_object["status"] = ReturnCode.BAD_REQUEST.value
            response_object["message"] = f"failed to remove: {e}"
        finally:
            return response_object
Ejemplo n.º 13
0
def spot_record_view(did: int):
    """ combine spot record and outdoor records """
    response_object: ApiResponse = (ApiResponse(
        status=ReturnCode.OK.value,
        message="successfully get spot records",
        data=[]))

    records = []

    for spot_rec in SpotRecord.query.filter_by(device_id=did):

        # fetch relevent objects.
        od_spot = Device.query.filter_by(
            device_id=did).first().spot.project.outdoor_spot

        spot_rec_hour: datetime = (spot_rec.spot_record_time.replace(
            minute=0, second=0, microsecond=0))

        dhour = timedelta(hours=1)

        od_rec = (OutdoorRecord.query.filter(
            and_(OutdoorRecord.outdoor_record_time >= spot_rec_hour,
                 OutdoorRecord.outdoor_record_time <
                 spot_rec_hour + dhour)).first())

        spot_rec_json = spot_rec.to_json()
        od_spot_json = od_spot.to_json() if od_spot else None

        try:
            od_rec_json = od_rec.to_json()
        except AttributeError:
            od_rec_json = {}

        spot_rec_json.update({
            "outdoor_spot": od_spot_json,
            "outdoor_record": od_rec_json,
        })

        records.append(spot_rec_json)

        response_object['data'] = records
    return jsonify(response_object)
Ejemplo n.º 14
0
def add_update_delete_template(
        some_id: Optional[int],
        model_operations: Tuple[
            AddOperation,
            UpdateOperation,
            DeleteOperation]) -> Json:
    add, update, delete = model_operations

    def handle_post(post_data: Optional[ApiRequest]) -> ApiResponse:

        response_object: ApiResponse = (
            ApiResponse(status=ReturnCode.OK.value))

        if post_data is None \
                or not is_ApiRequest(cast(Optional[Dict], post_data)):
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = "post failed "
            return response_object

        try:
            posted = add(cast(Dict, post_data["request"]))
            if posted:
                commit()
                response_object["message"] = "post succeeded!"
                response_object["data"] = posted.to_json()
            else:
                response_object['status'] = ReturnCode.NO_DATA.value
                response_object['message'] = "post failed"

        except IntegrityError:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object["message"] = (
                "post failed!, integrity error. might be missing a field")
        except Exception as e:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object["message"] = f"post failed! {e}"

        finally:
            return response_object

    def handle_put(post_data: Optional[ApiRequest]) -> ApiResponse:

        response_object: ApiResponse = (
            ApiResponse(status=ReturnCode.OK.value))

        if post_data is None \
                or not is_ApiRequest(cast(Optional[Dict], post_data)):
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = "post failed "
            return response_object

        try:
            updated = update(cast(Dict, post_data["request"]))
            if updated:
                commit()
                response_object['message'] = "update succeeded!"
                response_object["data"] = updated.to_json()
            else:
                response_object['status'] = ReturnCode.NO_DATA.value
                response_object['message'] = "update failed"

        except IntegrityError:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object["message"] = (
                "update failed!, integrity error. might be missing a field")

        except Exception as e:
            response_object['status'] = ReturnCode.NO_DATA.value
            response_object['message'] = f"update failed {e}"

        finally:
            return response_object

    def handle_delete() -> ApiResponse:
        response_object: ApiResponse = (
            ApiResponse(status=ReturnCode.OK.value))

        try:
            if some_id is None:
                raise Exception("Error when deleting, id is None")
            delete(some_id)
            commit()
            response_object["message"] = "remvoe succeeded"
        except Exception as e:
            response_object["status"] = ReturnCode.BAD_REQUEST.value
            response_object["message"] = f"failed to remove: {e}"
        finally:
            return response_object

    response_object: ApiResponse = ApiResponse()
    if request.method == 'POST':  # add new project.
        response_object = handle_post(post_data=request.get_json())

    if request.method == 'PUT':
        response_object = handle_put(post_data=request.get_json())

    if request.method == 'DELETE':
        response_object = handle_delete()

    return jsonify(response_object)
Ejemplo n.º 15
0
def logout():
    response = ApiResponse(
        status=ReturnCode.OK.value,
        message="logout")
    return jsonify(response)
Ejemplo n.º 16
0
def test():
    return jsonify(ApiResponse(status=ReturnCode.OK.value, message="test!"))