Exemplo n.º 1
0
async def create_student(student: StudentModel = Body(...)):
    student = jsonable_encoder(student)
    new_student = await db["students"].insert_one(student)
    created_student = await db["students"].find_one({"_id": new_student.inserted_id})
    return JSONResponse(status_code=status.HTTP_201_CREATED, content=created_student)
Exemplo n.º 2
0
 def response(self):
     return JSONResponse(content=self.data.dict(), status_code=self.code)
Exemplo n.º 3
0
async def server_error(request, exc):
    logger.exception(exc)
    return JSONResponse(status_code=500, content={'msg': 'Internal Server Error'})
Exemplo n.º 4
0
async def resource_dele(user_info: user_schema.resourcedele):
    #  获取传入的参数
    parames = {'id': user_info.id}
    result, user = curd_category.get_resource()
    resourcelist = user['id'].tolist()
    list = [int(x) for x in resourcelist]
    for r in parames['id']:
        if r in list:
            result_dele = curd_category.resourcedele(parames)
            if result_dele:
                return JSONResponse({
                    "code": 200,
                    "message": "操作成功",
                    "data": None
                })
            else:
                return JSONResponse({
                    "code": 500,
                    "message": "操作失败",
                    "data": None
                })
        else:
            return JSONResponse({
                "code": 409,
                "message": "删除的权限不存在",
                "data": None
            })


# @router.post("/login", summary="登录")
# async def login(user_info: user_schema.UserInfo):
#     increase_dict = {'username': user_info.username,
#                      'password': user_info.password}
#     password = hashlib.md5(increase_dict['password'].encode())
#     return_dict = {'code': 200, 'message': 'ok', 'data': None}
#     access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
#     if curd_category.login(increase_dict)==False:
#         return {"code": 500, "message": "操作失败", "data": None}
#     else:
#         df, sql_username_list=curd_category.login(increase_dict)
#         list=[]
#         for i in sql_username_list['username'].values.tolist():
#             list.append(str(i, encoding = "utf8"))
#         if increase_dict['username'] in list:
#             if password.hexdigest() == df[0][0]:
#                 return_dict['data']={'admin_id':df[0][1],
#                                      'img':df[0][2],
#                                      'key':df[0][3],
#                                      'username':str(df[0][4], encoding = "utf8")}
#                 return_dict['token']=create_access_token(increase_dict['username'], expires_delta=access_token_expires)
#                 return JSONResponse(return_dict)
#             else:
#                 return {"code": 403, "message": "密码错误", "data": None}
#         else:
#             return {"code": 403, "message": "用户名错误", "data": None}
#
#
# @router.get("/log/info", summary="获取登录日志")
# async def login_sele(request: Request,username:str=None,
#                      startingtime:str=None,
#                      endtime:str=None,
#                      curpage: int = Query(1, ge=1, title="当前页")):
#     parames={'username':username,
#              'startingtime':startingtime,
#              'endtime':endtime,
#              'curpage':curpage}
#     return_dict = {'code': 200, 'message': 'ok', 'data': {'page_count':None,'total_num':None,'list': None}}
#     ip = request.client.host
#     node = uuid.getnode()
#     macHex = uuid.UUID(int=node).hex[-12:]
#     mac = []
#     for i in range(len(macHex))[::2]:
#         mac.append(macHex[i:i + 2])
#     mac = ':'.join(mac)
#     print('MAC:', mac)
#     print(socket.getfqdn(socket.gethostname()))
#     print(socket.gethostbyname(socket.gethostname()))
#     print(ip)
#     print(request.headers['user-agent'])
#
#     print(request.url)
#     print(request.base_url)
#     print(request.url.path)
#
#
#
#     df,df_count=curd_category.get_log_list(parames)
#     return_dict['data']['total_num'] = df_count
#     return_dict['data']['list'] = df
#     return_dict['data']['page_count'] = math.floor(df_count / 30) + 1
#     if df_count == 0:
#         return_dict['data']['page_count'] = 0
#         return JSONResponse(return_dict)
#     elif df_count / 30 < 1:
#         return_dict['data']['page_count'] = 1
#         return JSONResponse(return_dict)
#     else:
#         return_dict['data']['page_count'] = math.floor(df_count / 30) + 1
#         return JSONResponse(return_dict)
#
# @router.get("/manager/selectlist", summary="管理员列表")
# async def admin_sele(tel:str=None,
#                      status:str=None,
#                      role_id:str=None,
#                      curpage: int = Query(1, ge=1, title="当前页数"),
#                      pagesize:int = Query(10, le=50, title="每页显示条数")):
#     parames={'tel':tel,
#              'status':status,
#              'role_id':role_id,
#              'curpage':curpage,
#              'pagesize':pagesize}
#     return_dict = {'code': 200, 'message': 'ok', 'data': {'page_count':None,'total_num':None,'list': None}}
#
#     df,df_count=curd_category.get_admin_list(parames)
#     return_dict['data']['total_num'] = df_count
#     return_dict['data']['list'] = df
#     if df_count == 0:
#         return_dict['data']['page_count'] = 0
#         return JSONResponse(return_dict)
#     elif df_count / 30 < 1:
#         return_dict['data']['page_count'] = 1
#         return JSONResponse(return_dict)
#     else:
#         return_dict['data']['page_count'] = math.floor(df_count / 30) + 1
#         return JSONResponse(return_dict)
#
# @router.get("/alter/password", summary="修改密码")
# async def admin_password(old_password:str,
#                      username:str,
#                      new_password:str):
#     m = hashlib.md5(old_password.encode())
#     n=hashlib.md5(new_password.encode())
#     parames={'old_password':m.hexdigest(),
#              'username':username,
#              'new_password':n.hexdigest()}
#     return_dict = {'code': 200, 'message': 'ok'}
#     result=curd_category.alter_password(parames)
#     if type(result) == str:
#         return_dict['message']=result
#         return JSONResponse(return_dict)
#     else:
#         return JSONResponse({'code': 200, 'message': 'ok', 'data': '修改成功'})
#
# @router.get("/alter/data", summary="修改资料")
# async def admin_data(img:str,admin_id:int):
#     parames={'img':img,
#              'admin_id':admin_id}
#     result=curd_category.alter_data(parames)
#     if result:
#         return JSONResponse({'code': 200, 'message': 'ok', 'data': '修改成功'})
#     else:
#         return JSONResponse({'code': 200, 'message': 'ok', 'data': '修改失败'})
Exemplo n.º 5
0
async def get_item(parameter: str):

    parameter = production_parameters.get(parameter, "Key does not exist")
    status_code = 400 if parameter == "Key does not exist" else 200

    return JSONResponse(parameter, status_code=status_code)
Exemplo n.º 6
0
 def response(message: dict, status_code: int):
     return JSONResponse(content=message, status_code=status_code)
Exemplo n.º 7
0
async def not_found(request, exc):
    return JSONResponse(
        status_code=status.HTTP_404_NOT_FOUND,
        content=jsonable_encoder({"message": "nope"}),
    )
Exemplo n.º 8
0
async def group_id(
    group_id: str = Query(
        None,
        title="Group ID",
        description="Get by the Group UUID",
        alias="groupId",
    ),
    group_name: str = Query(
        None,
        title="Group Name",
        description="Get by the Group Name",
        alias="groupName",
    ),
    delay: int = Query(
        None,
        title=title,
        description="Seconds to delay (max 121)",
        ge=1,
        le=121,
        alias="delay",
    ),
) -> dict:
    """[summary]
    Get individual group data, including users
    Args:
        group_id (str, optional): [description]. Defaults to Query( None,
         title="Group ID", description="Get by the Group UUID", alias="groupId", ).
        group_name (str, optional): [description]. Defaults to Query( None,
         title="Group Name", description="Get by the Group Name", alias="groupName", ).
        delay (int, optional): [description]. Defaults to Query( None,
         title=title, description="Seconds to delay (max 121)", ge=1, le=121, alias="delay", ).

    Returns:
        dict: [description]
        Group data and associated users
    """
    # sleep if delay option is used
    if delay is not None:
        await asyncio.sleep(delay)

    # if search by ID
    if group_id is not None:

        id_exists = await check_id_exists(group_id)
        if id_exists is False:
            error: dict = {"error": f"Group ID: '{group_id}' not found"}
            logger.warning(error)
            return JSONResponse(status_code=404, content=error)

    # elif search by name
    elif group_name is not None:

        name_exists = await check_unique_name(group_name)
        if name_exists is True:
            error: dict = {"error": f"Group Name: '{group_name}' not found"}
            logger.warning(error)
            return JSONResponse(status_code=404, content=error)

        query = groups.select().where(groups.c.name == group_name)
        name_result = await fetch_one_db(query=query)
        group_id = name_result["id"]
    # else at least one needs to be selected
    else:
        error: dict = {"error": "groupId or groupName must be used"}
        logger.warning(error)
        return JSONResponse(status_code=404, content=error)

    query = groups_item.select().where(groups_item.c.group_id == group_id)
    db_result = await fetch_all_db(query=query)

    users_list: list = []
    user_dict: dict = []
    for r in db_result:
        logger.debug(r)
        user_data: dict = {
            "id": r["id"],
            "user": r["user"],
            "date_created": str(r["date_create"]),
        }
        user_dict.append(user_data)
        users_list.append(r["user"])
    result = {
        "group_id": group_id,
        "count": len(users_list),
        "users": users_list,
        "user_info": user_dict,
    }
    return JSONResponse(status_code=200, content=result)
Exemplo n.º 9
0
async def create_group_user(
    *,
    group: GroupUser,
    delay: int = Query(
        None,
        title=title,
        description="Seconds to delay (max 121)",
        ge=1,
        le=121,
        alias="delay",
    ),
) -> dict:
    """[summary]
    Add a user to a group
    Args:
        group (GroupUser): [description]
        delay (int, optional): [description]. Defaults to Query( None,
         title=title, description="Seconds to delay (max 121)", ge=1, le=121, alias="delay", ).

    Returns:
        dict: [description]
        Confirmation of user being added
    """
    # sleep if delay option is used
    if delay is not None:
        logger.info(f"adding a delay of {delay} seconds")
        await asyncio.sleep(delay)

    check_id = str(group.group_id)
    group_id_exists = await check_id_exists(id=check_id)

    if group_id_exists is False:
        error: dict = {"error": f"Group ID '{check_id}' does not exist"}
        logger.warning(error)
        return JSONResponse(status_code=404, content=error)

    check_user = str(group.user)
    exist_user = await check_user_exists(user=check_user, group_id=check_id)

    if exist_user is True:
        error: dict = {"error": f"User ID '{check_id}' already in group"}
        logger.warning(error)
        return JSONResponse(status_code=400, content=error)

    try:

        user_id = str(uuid.uuid4())
        group_data = {
            "id": user_id,
            "user": group.user,
            "group_id": group.group_id
        }
        logger.debug(group_data)
        # create group
        query = groups_item.insert()
        group_result = await execute_one_db(query=query, values=group_data)
        logger.debug(str(group_result))
        # if "error" in group_result:
        #     error: dict = group_result
        #     logger.critical(error)
        #     return JSONResponse(status_code=400, content=error)

        # data result
        full_result: dict = group_data
        # full_result: dict = {"id": str(user_id), "data": group_result}
        logger.debug(full_result)
        return JSONResponse(status_code=status.HTTP_201_CREATED,
                            content=full_result)
    except Exception as e:
        error: dict = {"error": str(e)}
        logger.debug(e)
        logger.critical(f"Critical Error: {e}")
        return JSONResponse(status_code=400, content=error)
Exemplo n.º 10
0
async def group_state(
    *,
    id: str = Query(
        ...,
        title="group id",
        description="Group UUID",
        alias="id",
    ),
    is_active: bool = Query(
        None,
        title="active status",
        description="true or false of status",
        alias="isActive",
    ),
    delay: int = Query(
        None,
        title=title,
        ge=1,
        le=10,
        alias="delay",
        description="integer delay value for simulating delays",
    ),
) -> dict:
    """[summary]
        Active or Deactivate a Group ID
    Args:
        id (str, optional): [description]. Defaults to
         Query(..., title="group id", description="Group UUID", alias="id",).
        state (bool, optional): [description]. Defaults to
         Query( ..., title="active state", description="true or false of state", alias="state", ).
        delay (int, optional): [description]. Defaults to
         Query( None, title=title, ge=1, le=10, alias="delay",
          description="integer delay value for simulating delays", ).

    Returns:
        dict: [id, state]
    """
    # sleep if delay option is used
    if delay is not None:
        logger.info(f"adding a delay of {delay} seconds")
        await asyncio.sleep(delay)
    if is_active is None:
        error: dict = {
            "error": f"isActive must be true or false and cannot be empty"
        }
        logger.warning(error)
        return JSONResponse(status_code=422, content=error)

    id_exists = await check_id_exists(id)

    if id_exists is False:
        error: dict = {"error": f"Group ID: '{id}' not found"}
        logger.warning(error)
        return JSONResponse(status_code=404, content=error)

    try:

        group_data = {
            "is_active": is_active,
            "date_update": datetime.now(),
        }
        logger.debug(group_data)
        # create group
        query = groups.update().where(groups.c.id == id)
        group_result = await execute_one_db(query=query, values=group_data)
        logger.debug(str(group_result))

        # if "error" in group_result:
        #     error: dict = group_result
        #     logger.critical(error)
        #     return JSONResponse(status_code=400, content=error)

        # data result
        full_result: dict = {"id": id, "status": is_active}
        logger.debug(full_result)
        return JSONResponse(status_code=status.HTTP_201_CREATED,
                            content=full_result)
    except Exception as e:
        error: dict = {"error": str(e)}
        logger.debug(e)
        logger.critical(error)
        return JSONResponse(status_code=400, content=error)
Exemplo n.º 11
0
async def create_group(
    *,
    group: GroupCreate,
    delay: int = Query(
        None,
        title=title,
        ge=1,
        le=10,
        alias="delay",
    ),
) -> dict:
    """[summary]
    Create a new group
    Args:
        group (GroupCreate): [description]
        delay (int, optional): [description]. Defaults to Query(None,
         title=title, ge=1, le=10, alias="delay",).

    Returns:
        dict: [description]
        Group data
    """
    # sleep if delay option is used
    if delay is not None:
        logger.info(f"adding a delay of {delay} seconds")
        await asyncio.sleep(delay)

    # approval or notification
    group_type_check: list = ["approval", "notification"]
    if group.group_type not in group_type_check:
        error: dict = {
            "error":
            f"Group Type '{group.group_type}'\
                 is not 'approval' or 'notification'"
        }
        logger.warning(error)
        return JSONResponse(status_code=400, content=error)

    check_name = str(group.name)
    duplicate = await check_unique_name(check_name)

    try:
        if duplicate is False:
            error: dict = {
                "error": f"Group Name '{group.name}' is a duplicate"
            }
            logger.warning(error)
            return JSONResponse(status_code=400, content=error)

        group_id = uuid.uuid4()
        group_data = {
            "id": str(group_id),
            "name": group.name,
            "is_active": group.is_active,
            "description": group.description,
            "group_type": group.group_type,
            "date_create": datetime.now(),
            "date_update": datetime.now(),
        }
        logger.debug(group_data)
        # create group
        query = groups.insert()
        group_result = await execute_one_db(query=query, values=group_data)

        # if "error" in group_result:
        #     error: dict = group_result
        #     logger.critical(error)
        #     return JSONResponse(status_code=400, content=error)

        # data result
        full_result: dict = {"id": str(group_id), "data": group_result}
        logger.debug(full_result)
        return JSONResponse(status_code=status.HTTP_201_CREATED,
                            content=full_result)
    except Exception as e:
        error: dict = {"error": str(e)}
        logger.critical(error)
        return JSONResponse(status_code=400, content=error)
Exemplo n.º 12
0
def _err(msg: str) -> JSONResponse:
    return JSONResponse(content={"err": True, "errmsg": msg})
Exemplo n.º 13
0
            if c is not None:
                cases["þf"] = c
            c = n.dative
            if c is not None:
                cases["þgf"] = c
            c = n.genitive
            if c is not None:
                cases["ef"] = c

        resp["cases"] = cases
        resp["err"] = False
    except Exception as _:
        raise
        #return _err(f"Villa kom upp við fallbeygingu nafnliðar: '{e}'")

    return JSONResponse(content=resp)


_MAX_LEMMAS_TXT_LEN = 8192


@app.get("/lemmas")  # type: ignore
def lemmas(q: str, all_lemmas: bool = False) -> Response:
    """ Lemmatization API. """
    if not q:
        return _err("Missing query parameter")
    if len(q) > _MAX_LEMMAS_TXT_LEN:
        return _err(f"Param exceeds max length ({_MAX_LEMMAS_TXT_LEN} chars)")

    # Lazy-load Greynir engine
    global greynir
Exemplo n.º 14
0
async def empty_exception_handler(request: Request, e: EmptyException):
    return JSONResponse(
        status_code=418,
        content={"message": f"The sent request {e.query} can not be {e.name}"})
Exemplo n.º 15
0
async def auth_secret_token(request: Request, call_next):
    if os.getenv("PRODUCTION"):
        if request.headers.get("X-Negainoido-Secret") != load_secret_token():
            return JSONResponse(content={"error": "Unauthorized"}, status_code=401)
    return await call_next(request)
Exemplo n.º 16
0
def scanning(request,
             request_id: Optional[str] = None,
             scanner_name: Optional[str] = None):
    start_time = time.time()

    global ls
    global lock
    global scanners
    global scanners_set
    global last_lock

    if lock:
        if last_lock + LOCK_THRESHOLD < time.time():
            lock = False
        else:
            output = {
                "request_id": request_id,
                "output": False,
                "code": "LOCK",
                "msg": "The scanner is locking, please wait",
                "time": time.time() - start_time
            }
            return JSONResponse(status_code=status.HTTP_423_LOCKED,
                                content=output)

    if scanner_name is not None:
        if scanner_name not in scanners_set:
            ls, scanners, scanners_set, scanner_name = get_scanner()

        if scanner_name not in scanners_set:
            output = {
                "request_id": request_id,
                "output": scanners,
                "code": "NOT_FOUND",
                "msg": "Not found scanner {0}".format(scanner_name),
                "time": time.time() - start_time
            }
            return JSONResponse(status_code=status.HTTP_409_CONFLICT,
                                content=output)
    else:
        if len(scanners) == 0:
            ls, scanners, scanners_set, scanner_name = get_scanner()

        if len(scanners) == 0:
            output = {
                "request_id": request_id,
                "output": False,
                "code": "NO_SCANNER",
                "msg": "There's no plugin scanners, check your cable",
                "time": time.time() - start_time
            }
            return JSONResponse(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                content=output)
        scanner_name = scanners[0]

    lock = True
    last_lock = time.time()

    try:
        image = ls.scan(scanner_name=scanner_name, return_type="based64")
    except Exception as ex:
        lock = False
        output = {
            "request_id":
            request_id,
            "error":
            "Scan Error",
            "code":
            "ERROR",
            "msg":
            "There's some error when scanner: {0}".format(
                traceback.format_exc()),
            "time":
            time.time() - start_time
        }
        ls, scanners, scanners_set, scanner_name = get_scanner()
        return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            content=output)

    lock = False

    if image is False or image is None:
        output = {
            "request_id": request_id,
            "error": "Scan Error",
            "code": "ERROR",
            "msg": "There's some error when scanner, I doesn't know.",
            "time": time.time() - start_time
        }
        return JSONResponse(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                            content=output)

    output = {
        "request_id": request_id,
        "output": image,
        "code": "SUCCESS",
        "msg": "SUCCESS",
        "time": time.time() - start_time
    }
    return JSONResponse(status_code=status.HTTP_200_OK, content=output)
Exemplo n.º 17
0
def validation_exception_handler(request, exc):
    msg = ", ".join([f'{err["loc"]}: {err["msg"]}' for err in exc.errors()])
    return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST,
                        content={"message": msg})
Exemplo n.º 18
0
def get_response() -> JSONResponse:
    error = ErrorResponse(error="Uncaught server exception")
    json_error = jsonable_encoder(error.dict())
    return JSONResponse(content=json_error,
                        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemplo n.º 19
0
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)
Exemplo n.º 20
0
async def delete_by_id(
        session: AsyncSession = Depends(get_session),
        user_id: int = Path(..., alias='id', ge=1),
) -> JSONResponse:
    await crud.delete(session, User, user_id)
    return JSONResponse({}, status_code=status.HTTP_200_OK)
Exemplo n.º 21
0
async def resource_select():
    """权限列表查询接口"""
    result, lis = curd_category.resource_select()
    return_dict = {'code': 200, 'message': '操作成功', 'data': None}
    return_dict['data'] = lis
    return JSONResponse(return_dict)
Exemplo n.º 22
0
def custom_http_exception_handler(request: Request, exc: HTTPException):
    try:
        if exc.status_code == 401:
            print(request.__dict__)
            if hasattr(exc, "burning_request") and hasattr(
                    exc.burning_request, "__dict__"):
                request.__dict__.update(exc.burning_request.__dict__)
            return error_templates.TemplateResponse(
                "401.html",
                {
                    "request":
                    request,
                    "current_url":
                    request.url,
                    "current_method":
                    request.method,
                    "alert":
                    Alert(
                        "Вы не обладаете достаточными правами для просмотра этой страницы!"
                        "Возможно, вам надо авторизоваться...", Alert.ERROR)
                },
                status_code=401,
            )
        elif exc.status_code == 403:
            print(request.__dict__)
            if hasattr(exc, "burning_request") and hasattr(
                    exc.burning_request, "__dict__"):
                request.__dict__.update(exc.burning_request.__dict__)
            return error_templates.TemplateRedirectResponse(
                "/log_in",
                "403.html",
                {
                    "url":
                    "/log_in",
                    "request":
                    request,
                    "alert":
                    Alert(
                        "Вам необходимо авторизоваться, чтобы просматривать эту страницу",
                        Alert.ERROR),
                },
            )
            # return  RedirectResponseWithBody(f"/log_in", Ajax300Answer(
            #     url=f"/log_in",
            #     alert=Alert("Вам необходимо авторизоваться, чтобы просматривать эту страницу", Alert.ERROR),
            #     request=request))
        elif exc.status_code == 404:
            print(request.__dict__)
            if hasattr(exc, "burning_request") and hasattr(
                    exc.burning_request, "__dict__"):
                request.__dict__.update(exc.burning_request.__dict__)
            return error_templates.TemplateResponse(
                "404.html", {
                    "request": (exc.burning_request if hasattr(
                        exc, "burning_request") else request),
                    "detail":
                    exc.detail,
                    "alert":
                    Alert("Похоже данной страницы не существует...",
                          Alert.ERROR)
                })
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "message": f"Oops! did something. There goes a rainbow..."
            },
        )
    except FileExistsError as e:
        print("произошла ошибка в функции обработки ошибок:", e)
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "message": f"Oops! did something. There goes a rainbow..."
            },
        )
Exemplo n.º 23
0
async def get_items():
    return JSONResponse(production_parameters, status_code=200)
Exemplo n.º 24
0
async def image_upload(
        id: int,
        data: Request,
        Authorize: AuthJWT = Depends(),
        db: Session = Depends(get_db),
):
    Authorize.jwt_required()
    user_id = Authorize.get_jwt_subject()
    dbpost = postCRUD.get(db, id)
    raw_image = await data.body()

    # CHECKS
    if not dbpost:
        return JSONResponse(content={'details': 'Post not found'},
                            status_code=404)

    if dbpost.owner_id != user_id:
        return JSONResponse(content={'details': 'Post is not current user\'s'},
                            status_code=401)

    if dbpost.image:
        return JSONResponse(
            content={'details': 'Image is already associated with post'},
            status_code=400)

    try:
        # Opening the image & getting the
        # metadata from the image
        image = Image.open(io.BytesIO(raw_image))
        meta = get_metadata(image)

        if meta:
            # Putting in the time the photo was taken
            # if the data is available
            if "DateTimeOriginal" in meta:
                date_str = meta["DateTimeOriginal"]
                print("Taken at: " + date_str)
                # dbpost = postCRUD.update(db, db_obj=dbpost, obj_in={
                #     'datetime_taken': datetime.strptime(date_str, "%Y:%m:%d %H:%M:%S")})

        # Converting the image to a JPG no
        # matter the format it was taken in
        image = image.convert("RGB")

        # Setting variables and getting UUIDs
        # for identifying images
        cleaned = io.BytesIO()
        cleaned_uuid = str(uuid.uuid4())
        cleaned_name = cleaned_uuid + ".jpg"

        image.save(cleaned, format='JPEG')

        # Getting a thumbnail
        thumbnail = io.BytesIO()
        thumbnail_uuid = str(uuid.uuid4())
        thumbnail_name = thumbnail_uuid + ".jpg"

        width, height = image.size
        image.thumbnail((width, 120) if (width >= height) else (120, height))
        image = crop_center(image, 120, 120)
        image.save(thumbnail, format='JPEG')

        # Uploading the images as blobs to Google Cloud Storage
        upload_image_blob("snapquest-post-images", cleaned_name, cleaned)
        upload_image_blob("snapquest-post-images", thumbnail_name, thumbnail)
    except UnidentifiedImageError:
        raise HTTPException(400, "File uploaded was not an image")

    # TODO: Put image in google cloud
    # TODO: Don't put image into database, and put reference instead
    dbimage = postCRUD.file_upload(db,
                                   id=id,
                                   image=cleaned.getvalue(),
                                   thumbnail=thumbnail.getvalue())
    return Response(dbimage, media_type='image/jpeg')
Exemplo n.º 25
0
async def update_item(parameter: str, value: float):
    update_item_encoded = jsonable_encoder(value)
    production_parameters[parameter] = update_item_encoded
    return JSONResponse(update_item_encoded, status_code=200)
Exemplo n.º 26
0
def no_film_found_handler(responce: Response, exc: NoFilmFound) -> Response:
    return JSONResponse(
        status_code=status.HTTP_404_NOT_FOUND,
        content={'detail': 'Film with id %s was not found' % exc.film_id},
    )
Exemplo n.º 27
0
async def get_themed_excerpts(
    theme: str = Path(
        ...,
        description=
        "Search in excerpts from gazettes that are associated to the given theme.",
    ),
    entities: List[str] = Query(
        [],
        description=
        "Search in excerpts which contains any of the given entities (entities are theme-specific).",
    ),
    subthemes: List[str] = Query(
        [],
        description=
        "Search in excerpts which contains any of the given subthemes (subthemes are theme-specific).",
    ),
    territory_ids: List[str] = Query(
        [],
        description=
        "Search in excerpts from gazettes published by cities with the given 7-digit IBGE IDs (an empty field searches in all available cities).",
    ),
    since: date = Query(
        None,
        description=
        "Search in excerpts from gazettes published on given date or after (format: YYYY-MM-DD).",
    ),
    until: date = Query(
        None,
        description=
        "Search in excerpts from gazettes published on given date or before (format: YYYY-MM-DD).",
    ),
    querystring: str = Query(
        "",
        description=
        'Search in excerpts using ElasticSearch\'s "simple query string syntax".',
    ),
    pre_tags: List[str] = Query(
        [""],
        description=
        "List of strings (usually HTML tags) to be inserted before the text which matches the query in the excerpts.",
    ),
    post_tags: List[str] = Query(
        [""],
        description=
        "List of strings (usually HTML tags) to be inserted after the text which matches the query in the excerpts.",
    ),
    size: int = Query(
        10,
        description=
        "Maximum number of results to be returned in the response (use with caution).",
    ),
    offset: int = Query(
        default=0,
        description="Number of search results to be skipped in the response.",
    ),
    sort_by: SortBy = Query(
        SortBy.RELEVANCE,
        description="How to sort the search results.",
    ),
):
    themed_excerpt_request = ThemedExcerptRequest(
        theme=theme,
        entities=entities,
        subthemes=subthemes,
        territory_ids=territory_ids,
        since=since,
        until=until,
        querystring=querystring,
        pre_tags=pre_tags,
        post_tags=post_tags,
        size=size,
        offset=offset,
        sort_by=sort_by.value,
    )
    try:
        excerpts_count, excerpts = app.themed_excerpts.get_themed_excerpts(
            themed_excerpt_request)
    except Exception as exc:
        return JSONResponse(status_code=404, content={"detail": str(exc)})

    return {
        "total_excerpts": excerpts_count,
        "excerpts": excerpts,
    }
Exemplo n.º 28
0
def wrong_password_handler(responce: Response, exc: WrongPassword) -> Response:
    return JSONResponse(
        status_code=status.HTTP_400_BAD_REQUEST,
        content={'detail': 'Incorrect login or password'},
        headers={'WWW-Authenticate': 'Basic'},
    )
Exemplo n.º 29
0
def health() -> JSONResponse:
    """ヘルスチェック"""
    return JSONResponse({"message": "It worked!!"})
Exemplo n.º 30
0
async def sendtext(text: str):
    output = text
    return JSONResponse(content=output)