def validate_json_object(obj: Dict[Union[str, int], Any], spec: List[str]) -> validate: try: validate(obj, spec) except ValidationError as e: log_exception(e) raise errors.BadRequestBody()
def insert_users(users_to_insert: List[MutableMapping[Any, Any]]) -> List[str]: """Insert new users to collection, return ids.""" try: db_adaptor = get_db_adaptor() return db_adaptor.insert_many(users_to_insert).inserted_ids except Exception as e: log_exception(e) raise errors.InternalServerError()
def insert_user(required_fields_digest: MutableMapping[Any, Any]) -> str: """Inserts one user to users collection. Returns id.""" try: db_adaptor = get_db_adaptor() return db_adaptor.insert_one(required_fields_digest).inserted_id except Exception as e: log_exception(e) raise errors.InternalServerError()
def find_one_by_filter(search_filter: Dict[Union[str, int], Any]) \ -> Optional[Dict[Union[str, int], Any]]: """Find one user by search_filter. Returns user object.""" try: db_adaptor = get_db_adaptor() return db_adaptor.find_one(search_filter, projection={'_id': False}) except Exception as e: log_exception(e) raise errors.InternalServerError()
def count_tot_users() -> Optional[int]: """ Returns current size of Users collection. Raises errors.InternalServerError is any other errors. """ try: db_adaptor = get_db_adaptor() return db_adaptor.count() except Exception as e: log_exception(e) raise errors.InternalServerError()
def get_users() -> List[Dict[Union[str, int], Any]]: """ Returns list of user objects from users collection. Raises errors.InternalServerError is any other errors. """ try: db_adaptor = get_db_adaptor() return [i for i in db_adaptor.find_cursor()] except Exception as e: log_exception(e) raise errors.InternalServerError()
def make_drop() -> Optional[Iterable[str]]: """ Drops users collection. Raises errors.InternalServerError is any errors. """ try: db_adaptor = get_db_adaptor() return db_adaptor.drop() except Exception as e: log_exception(e) raise errors.InternalServerError()
def read_by_uuid(user_uuid: str) -> Optional[Dict[Union[str, int], Any]]: """ Get user obj from collection by given user_uuid. Raises errors.UserNotFound if user is not found by user_uuid. Raises errors.InternalServerError is any other errors. """ try: db_adaptor = get_db_adaptor() return db_adaptor.find_one({'uuid': user_uuid}, projection={'_id': False}) except errors.UserNotFound as e: log_exception(e) raise except Exception as e: log_exception(e) raise errors.InternalServerError()
def drop_collection() -> Union[BaseResponse, None]: """Drop collection endpoint.""" validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/drop_collection']) if request.method == 'POST': try: result = make_drop() return json_response(result, status=202) except errors.ExternalResource as e: e.message_json = 'External resource error ' \ 'when dropping collection.' log_exception(e) return json_error_response(e) except errors.InternalServerError as e: e.message_json = 'Error while dropping collection.' log_exception(e) return json_error_response(e)
def update_user(user_uuid: str, user_to_db: MutableMapping[Any, Any]) \ -> Optional[Dict[Union[str, int], Any]]: """ Updates single user object by given user_uuid. Raises errors.ResourceNotFound if user is not found by user_uuid. Raises errors.InternalServerError is any other errors. """ try: fields = {'_id': False} db_adaptor = get_db_adaptor() return db_adaptor.find_one_and_update( {'uuid': user_uuid}, {'$set': user_to_db}, projection=fields, return_document=ReturnDocument.AFTER) except errors.UserNotFound as e: log_exception(e) raise except Exception as e: log_exception(e) raise errors.InternalServerError()
def delete_by_uuid(user_uuid: str): """ Deletes user from collection given by user_uuid. Raises errors.InternalServerError is any errors. """ try: # Check that user is actually present db_adaptor = get_db_adaptor() user = db_adaptor.find_one({'uuid': user_uuid}, projection={'_id': False}) if user is None: raise errors.UserNotFound() # Delete user result = db_adaptor.delete_one({'uuid': user_uuid}) if not result.acknowledged: raise errors.InternalServerError() return result except Exception as e: log_exception(e) raise errors.InternalServerError()
def delete_user(user_uuid: str): """ tags: - userAPI summary: Delete a single user record description: Delete a user parameters: - name: user_uuid in: path description: UUID of the user to delete required: true type: string responses: '204': description: Delete is OK '404': description: User not found or already deleted schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' """ validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/delete_user']) if request.method == 'DELETE': try: delete_by_uuid(user_uuid) return Response(status=204) except errors.UserNotFound as e: e.message_json = f'User {user_uuid} not found' log_exception(e) return json_error_response(e) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)
def validate_request(headers, method, supported_methods): """Validation of requested headers, method, supported_methods""" try: validate_request_method(method, supported_methods) validate_request_headers(headers) except errors.WrongMethod as e: e.message_json = e.message_json.format(method, supported_methods) log_exception(e) return json_error_response(e) except errors.AcceptTypeError as e: log_exception(e) return json_error_response(e) except errors.ContentTypeError as e: log_exception(e) return json_error_response(e)
def post_user() -> Optional[BaseResponse]: """ tags: - userAPI summary: Adds a single user record parameters: - in: body name: body description: User object required: true schema: $ref: '#/definitions/User' responses: '200': description: OK '400': description: Validation error schema: $ref: '#/definitions/Error' '404': description: User not found schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' '406': description: >- Accept header is provided but 'application/json' type is not present in header schema: $ref: '#/definitions/Error' '415': description: >- Unsupported media type. 'Content-Type' header is provided and it is not the 'application/json' schema: $ref: '#/definitions/Error' """ validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/post_user']) if request.method == 'POST': try: user_to_create = request.json except Exception as e: log_exception(e) return json_error_response(errors.BadRequestBody()) try: # Validate JSON schema keys_to_digest, user_obj_spec = get_spec_digest() validate_json_object(user_to_create, user_obj_spec) except errors.BadRequestBody as e: log_exception(e) return json_error_response(e) try: # Process post user new, result = process_post_user(user_to_create, keys_to_digest) status = 201 if new else 200 return json_response(result, status=status) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)
def update_user(user_uuid: str) -> Union[BaseResponse, None]: """ tags: - userAPI summary: Updates an existing user parameters: - name: user_uuid in: path description: UUID of user to update required: true type: integer - name: body in: body description: User object to update required: true schema: $ref: '#/definitions/User' responses: '200': description: OK '400': description: Validation error schema: $ref: '#/definitions/Error' '404': description: User not found schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' '406': description: >- Accept header is provided but 'application/json' type is not present in header schema: $ref: '#/definitions/Error' '415': description: >- Unsupported media type. 'Content-Type' header is provided and it is not the 'application/json' schema: $ref: '#/definitions/Error' """ validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/update_user']) try: # Validate the UUID parameter validate_user_uuid(user_uuid) except errors.BadRequestQuery as e: e.message_json = f'Wrong user UUID: {user_uuid}' log_exception(e) return json_error_response(e) if request.method == 'PUT': # Request new user try: new_user = request.json except Exception as e: log_exception(e) return json_error_response(errors.BadRequestBody()) try: # Validate JSON schema keys_to_digest, user_obj_spec = get_spec_digest() validate_json_object(new_user, user_obj_spec) except errors.BadRequestBody as e: log_exception(e) return json_error_response(e) try: # Update user updated_user = process_update_user(user_uuid, new_user, keys_to_digest) return json_response(updated_user) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)
def by_uuid(user_uuid: str) -> Union[Response, None]: """ tags: - userAPI summary: Get's a single user record description: Get single user record by given user_uuid parameters: - name: user_uuid in: path description: UUID of the user to get required: true type: string responses: '200': description: OK '400': description: Validation error schema: $ref: '#/definitions/Error' '404': description: User not found schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' '406': description: >- Accept header is provided but 'application/json' type is not present in header schema: $ref: '#/definitions/Error' '415': description: >- Unsupported media type. 'Content-Type' header is provided and it is not the 'application/json' schema: $ref: '#/definitions/Error' """ validate_request(request.headers, request.method, SUPPORTED_METHODS['/get_user_by_uuid']) try: # Validate the UUID parameter validate_user_uuid(user_uuid) except errors.BadRequestQuery as e: e.message_json = f'Wrong user UUID: {user_uuid}' log_exception(e) return json_error_response(e) if request.method == 'GET': try: user = read_by_uuid(user_uuid) return json_response(user) except errors.UserNotFound as e: e.message_json = f'User with this ' \ f'{user_uuid} was not found.' log_exception(e) return json_error_response(e) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)
def post_users() -> Union[BaseResponse, None]: """ tags: - userAPI summary: Adds users to User db. Upload as many as you want. description: 'Add as many users to User db, as want.' parameters: - name: body in: body description: List of users to post required: true schema: $ref: '#/definitions/Users' responses: '200': description: OK '400': description: Validation error schema: $ref: '#/definitions/Error' '404': description: User not found schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' '406': description: >- Accept header is provided but 'application/json' type is not present in header schema: $ref: '#/definitions/Error' '415': description: >- Unsupported media type. 'Content-Type' header is provided and it is not the 'application/json' schema: $ref: '#/definitions/Error' """ validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/post_users']) if request.method == 'POST': try: # Load JSON object users_to_create = request.json except Exception as e: log_exception(e) return json_error_response(errors.BadRequestBody()) try: # Validate JSON schema keys_to_digest, user_obj_spec = get_spec_digest() [ validate_json_object(user, user_obj_spec) for user in users_to_create ] except errors.BadRequestBody as e: log_exception(e) return json_error_response(e) try: # Post users new, res = process_post_users(users_to_create, keys_to_digest) status = 201 if new else 200 return json_response(res, status=status) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)