class Auth(HTTPMethodView): @doc.description('登录接口,所需参数有username,password') @doc.consumes( doc.JsonBody({ "device_id": doc.String("456"), "password": doc.String("123"), }), location="body", ) @doc.response(400, {"msg": str}, description="帐号密码输错了") @doc.response(500, {'msg': str}, description="程序出错,找后端查看日志") @doc.response(403, {'msg': str}, description="未登录") def post(self, req): try: device_id = req.json['device_id'] login_user = get_user_by_device_id(device_id) if login_user is None or req.json['password'] != login_user[ 'password']: return response.json({'msg': '帐号不存在或密码错误'}, status=400) # 默认无法序列化实体类,使用 dict 代替 req.ctx.session['user'] = login_user return response.json(login_user) except Exception as e: print(e) return response.json({'msg': '服务器错误'}, status=500)
class user_login_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: recaptcha_token = doc.String("Google RECaptcha token") username = doc.String("Username") password = doc.String("Password") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On success login" class model: username = doc.String("Username") token = doc.String("User's jwt token") model = dict(vars(model)) class FailResp: code = 401 description = "On failed login" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp]
class change_bed_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: source_bed = doc.String("Source bed") # source_username = doc.String("Source user") dest_bed = doc.String("Destination bed") # dest_username = doc.String("Destination user") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On success register" class model: message = doc.String("Error message") model = dict(vars(model)) class FailResp: code = 401 description = "On failed register" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp]
class add_user_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: username = doc.String("Username") nick = doc.String("User's name") department = doc.String("User's department") back_mail = doc.String("User's backup mail") note = doc.String("Additional note") bed = doc.String("User's bed") is_panda = doc.Boolean("Is user panda") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On success login" class model: username = doc.String("Username") model = dict(vars(model)) class FailResp: code = 400 description = "On failed login" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp]
def test_jsonbody_field(app): field = doc.JsonBody() assert field.serialize() == { "name": "body", "schema": { "properties": {}, "type": "object" }, } @app.get("/") @doc.consumes(field, location="body", required=True) def test(request): return text("test") _, response = app.test_client.get("/swagger/swagger.json") assert response.status == 200 assert response.content_type == "application/json" swagger_json = response.json path = swagger_json["paths"]["/"]["get"] assert path["parameters"][0] == { "required": True, "in": "body", "name": "body", "schema": { "properties": {}, "type": "object" }, }
class forgot_password_verify_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: password = doc.String("User's new password") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 202 description = "On success request" class model: message = doc.String("message") model = dict(vars(model)) class FailResp: code = 401 description = "On failed request" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp]
class SimpleView(HTTPMethodView): ex1 = {'11': int, '123': str} @doc.tag("test") @doc.consumes(doc.String(name="X-API-VERSION"), location="header", required=True) @doc.consumes(doc.String(name="name"), location="query") @doc.response(200, ex1, description='123aaa') def get(self, request): return text("I am get method") @doc.consumes(doc.JsonBody({ "useranme": doc.String("The name of your user account."), "password": doc.String("The password of your user account."), }), content_type="Application/json", location="body") def post(self, request): return text("I am post method") def put(self, request): return text("I am put method") def patch(self, request): return text("I am patch method") def delete(self, request): return text("I am delete method")
class _test_suite: id = doc.String() test_suite = doc.String() path = doc.String() test_cases = doc.List(doc.String()) variables = doc.JsonBody() author = doc.String()
def response(handler): async def handle_request(request): # log.info("Accept request: {}".format(request.json)) return json(asdict(handler(Box(request.json)))) _, newHandler = post(handle_request) doc.summary(summary) doc.consumes(doc.JsonBody(to_dict(requestData)), content_type="application/json", location='body')(newHandler) doc.produces(to_dict(responseData), content_type="application/json")(newHandler) return newHandler
def open_api_schemas(schemas: BaseSchema, is_json: bool = False, many: bool = False): """ Отдает схему для swagger документации получая из marshmallow схему """ swagger_schema = {} for field_key in schemas.fields: field_obj = schemas.fields[field_key] swagger_schema[field_key] = marshmallow_to_swagger(field_key, field_obj) if schemas.many is True or many: return doc.List(swagger_schema) if is_json: return doc.JsonBody(swagger_schema) return swagger_schema
class abuse_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: title = doc.String("lock title for public") description = doc.String("description only for admin") lock_until = doc.Date("YYYY-MM-DD") no_update = doc.Boolean("Should do switch_update(dev only)") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On request succeded" class model: message = doc.String("OPERATION_SUCCESS") model = dict(vars(model)) class FailResp: code = 400 description = "On failed request" class model: message = doc.String("BAD_REQUEST") model = dict(vars(model)) class ServerFailResp: code = 500 description = "When server failed to process the response" class model: message = doc.String("INTERNAL_SERVER_ERROR") model = dict(vars(model)) class AuthResp: code = 401 description = "On failed auth" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp, ServerFailResp, AuthResp]
class unlock_abuse_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = False class consumes: unlock_date = doc.Date( "Set unlock date. if not provided will unlock immediately") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On request succeded" class model: message = doc.String("OPERATION_SUCCESS") model = dict(vars(model)) class FailResp: code = 400 description = "On failed request" class model: message = doc.String("BAD_REQUEST") model = dict(vars(model)) class ServerFailResp: code = 500 description = "When server failed to process the response" class model: message = doc.String("INTERNAL_SERVER_ERROR") model = dict(vars(model)) class AuthResp: code = 401 description = "On failed auth" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp, ServerFailResp, AuthResp]
class user_register_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: username = doc.String("Username") bed = doc.String("User's bed number") password = doc.String("User's password") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On success register" class model: message = doc.String("Error message") model = dict(vars(model)) class FailResp: code = 401 description = "On failed register" class model: message = doc.String("Error message") model = dict(vars(model)) class InteralFailResp: code = 500 description = "On Server-side failed register" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp, InteralFailResp]
class user_set_owned_ip_mac_doc(api.API): consumes_content_type = "application/json" consumes_location = "body" consumes_required = True class consumes: old_password = doc.String("Old password") new_password = doc.String("New Password") consumes = doc.JsonBody(vars(consumes)) class SuccessResp: code = 200 description = "On success request" class model: message = doc.String("Message") model = dict(vars(model)) class FailResp: code = 500 description = "On failed request" class model: message = doc.String("Error message") model = dict(vars(model)) class AuthResp: code = 401 description = "On failed Auth" class model: message = doc.String("Error message") model = dict(vars(model)) response = [SuccessResp, FailResp, AuthResp]
async def get_record(request): result = None with db_conn.cursor() as cur: sql = "SELECT * FROM `record` LIMIT 100" cur.execute(sql) result = cur.fetchall() for line in result: line["ts"] = line["ts"].strftime("%Y-%m-%d %H:%M:%S") return json(result) @app.post("/temp") @doc.consumes(doc.JsonBody({ "IOT_ID": doc.Integer("iot's id"), "air_temp": doc.Float("air temperature"), "air_hum": doc.Float("air hum"), "dirt_hum": doc.Float("dirt hum") }), location="body", content_type="application/json") async def save_record(request): # iot_id = request.json["IOT_ID"] iot_id = 1 air_temp = request.json["air_temp"] air_hum = request.json["air_hum"] dirt_hum = request.json["dirt_hum"] data = (iot_id, air_temp, air_hum, dirt_hum) with db_conn.cursor() as cur: sql = "INSERT INTO `record` VALUES (null, %s, %s, %s, %s, null)" cur.execute(sql, data) db_conn.commit()
MLJobManager.delete_job(id) return response.json({}, status=204) except Exception: logger.exception('faile to delete ml job') return response.json({}, status=500) @ml_svc.post('/ml_jobs', strict_slashes=True) @doc.summary('creat a ml job') @doc.produces({}, content_type="application/json") @doc.consumes( doc.JsonBody({ "name": str, "type": str, "dataset": str, "features": [str], "targets": [str], "job_option": {}, "validation_option": {}, }), content_type="application/json", location="body", ) async def create_job(request): logger.debug(f'get create ml job with payload={request.body}') try: request_body = json.loads(request.body) job = MLJobManager.create_job(request_body) return response.json(job, status=201) except Exception: logger.exception('faile to create ml job')
@blueprint.get("/<key>") @doc.summary("View a specific template") async def detail(request, key): template = Template.objects.get_or_none(key) if template: return response.json(template.jsonify(request.app)) abort(404) @blueprint.post("/custom") @doc.summary("Create a meme from any image") @doc.consumes( doc.JsonBody({ "image_url": str, "text_lines": [str], "extension": str }), location="body", ) async def custom(request): if request.form: payload = dict(request.form) with suppress(KeyError): payload["text_lines"] = payload.pop("text_lines[]") else: payload = request.json url = Template("_custom").build_custom_url( request.app, payload.get("text_lines") or [],
[{"name": str, "id": str, "type": str, "description": str}], content_type="application/json" ) async def list_datasets(request): try: datasets = DatasetManager.list_datasets() return response.json(datasets, status=200) except Exception: logger.exception('faile to list dataset') return response.json({}, status=500) @dataset_svc.post('/datasets', strict_slashes=True) @doc.summary('creat a dataset') @doc.produces({}, content_type="application/json") @doc.consumes( doc.JsonBody({"name": str, "id": str, "type": str, "file": str, "description": str}), content_type="application/json", location="body", ) async def create_datasets(request): logger.debug(f'create dataset with payload={request.body}') try: request_body = json.loads(request.body) DatasetManager.add_dataset(request_body) return response.json({}, status=201) except Exception: logger.exception('faile to create dataset') return response.json({}, status=500) @dataset_svc.get('/datasets/<id>', strict_slashes=True)
:return: The success message if the service is up. """ LOGGER.logger.info("Checking the service setup.\n") return response.json({ "status": 200, "version": "1.0", "message": "The web service is up and running!", }) @app.route("v1/predict", methods=["POST"]) @doc.summary( "Hit this end-point with a post request to predict the label for the text in the request." ) @doc.consumes( doc.JsonBody({"text": str}), location="body", content_type="application/json", ) async def get_response(request): """ This end point predicts the label for the given text and returns the result in the response. :param request: The request for the API. :return: The response with the prediction results. """ tic = time.time() # Step 01: Set the default response. prediction_service_response = response.json({ "status":
"""Get specific proposal by proposal_id.""" log_request(request) head_block = await get_request_block(request) conn = await create_connection() proposal = await proposals_query.fetch_proposal_resource(conn, proposal_id) proposal_resource = await compile_proposal_resource(conn, proposal) conn.close() return await create_response(conn, request.url, proposal_resource, head_block) @PROPOSALS_BP.patch("api/proposals") @doc.summary("API Endpoint to get update multiple proposals") @doc.description("API Endpoint to update multiple proposals.") @doc.consumes( doc.JsonBody( {"ids": [str], "reason": str, "status": str}, description="List of IDs are required for this endpoint.", ), location="body", required=True, content_type="application/json", ) @doc.produces( {"proposal_ids": [str]}, description="List of proposals that were successfully updated", content_type="application/json", ) @doc.response( 400, {"code": int, "message": str}, description="Bad request: status must be either REJECTED or APPROVED.", )
def json_consumes(json_body: Dict, *args, **kwargs): return doc.consumes(doc.JsonBody(json_body), *args, **kwargs, content_type='application/json', location='body')
from rbac.server.db.users_query import search_users, search_users_count LOGGER = get_default_logger(__name__) SEARCH_BP = Blueprint("search") @SEARCH_BP.post("api/search") @doc.summary("API Endpoint to get all roles, packs, or users containing a string.") @doc.description("API Endpoint to get all roles, packs, or users containing a string.") @doc.consumes( doc.JsonBody( { "query": { "page_size": int, "page": int, "search_object_types": [str], "search_input": str, } }, description="For search_object_types, you may include: role, pack, and/or user.", ), location="body", content_type="application/json", ) @doc.produces( {"data": {"roles": {}, "packs": {}, "users": {}}, "page": int, "total_pages": int}, description="Success response with search results", content_type="application/json", ) @doc.response( 401,
end = datetime.datetime.strptime(end_date, "%Y-%m-%d").date() if end <= start: raise InvalidUsage('start must be before end') inventory = get_inventory_inner(hotel_id, start, end) return response.json(inventory) except Exception as e: raise InvalidUsage(' error->' + ' ' + str(e) + traceback.format_exc()) @app.route("/reservation", methods=["POST", "OPTIONS"]) @doc.summary( "add reservations in hotel_id from start_date to end_date,dateformat YYYY-mm-dd" ) @doc.consumes(doc.JsonBody({ "start": str, "end": str, "hotel_id": int, "inventory_id": int }), content_type="application/json", location="body", required=True) @doc.produces({"reservation_id": int}) async def add_reservation(request): hotel_id = request.json['hotel_id'] start_date = datetime.datetime.strptime(request.json['start'], "%Y-%m-%d").date() end_date = datetime.datetime.strptime(request.json['end'], "%Y-%m-%d").date() # validate: start less than end if (end_date <= start_date
content_type="application/json", ) @doc.response(404, str, description="Template not found") async def detail(request, key): template = Template.objects.get_or_none(key) if template: return response.json(template.jsonify(request.app)) abort(404) @blueprint.post("/custom") @doc.summary("Create a meme from any image") @doc.consumes( doc.JsonBody({ "image_url": str, "text_lines": [str], "extension": str, "redirect": bool }), content_type="application/json", location="body", ) @doc.response(201, {"url": str}, description="Successfully created a meme from a custom image") async def custom(request): if request.form: payload = dict(request.form) with suppress(KeyError): payload["text_lines"] = payload.pop("text_lines[]") else: payload = request.json
logger.exception('failed to list configurations') return response.json({}, status=500) @conf_svc.get('/confs/<domain>', strict_slashes=True) @doc.summary('get content of configurations for specific domain') @doc.produces({}, content_type="application/json") async def get_confs(request, domain): try: config = ConfigurationManager.get_confs_values(domain) return response.json(config, status=200) except Exception: logger.exception('failed to get content of configurations') return response.json({}, status=500) @conf_svc.post('/confs/<domain>', strict_slashes=True) @doc.summary('save content of configurations for specific domain') @doc.consumes(doc.JsonBody({}), content_type="application/json", location="body") async def save_confs(request, domain): logger.debug(f'save configuration to domain={domain} with {request.body}') try: request_body = json.loads(request.body) ConfigurationManager.save_conf(domain, request_body) return response.json({}, status=200) except Exception: logger.exception('failed to save configurations') return response.json({}, status=500)
async def index(request): loop = asyncio.get_event_loop() samples = await loop.run_in_executor(None, helpers.get_sample_images, request) return response.json([{ "url": url, "template": template } for url, template in samples]) @blueprint.post("/") @doc.summary("Create a meme from a template") @doc.consumes( doc.JsonBody({ "template_key": str, "text_lines": [str], "extension": str }), location="body", ) async def create(request): if request.form: payload = dict(request.form) with suppress(KeyError): payload["template_key"] = payload.pop("template_key")[0] with suppress(KeyError): payload["text_lines"] = payload.pop("text_lines[]") else: payload = request.json try:
async def create_db_connection(app: Sanic, loop) -> None: await app.db.connect() if env.bool('migrate', False): await app.db.migrate() @app.listener('after_server_stop') async def close_db_connection(app: Sanic, loop) -> None: await app.db.close() @app.post('/couriers') @doc.tag("Add couriers") @doc.summary("Add some couriers to the service") @doc.consumes(doc.JsonBody({"data": [CourierModel.schema()]}), location="body", required=True, content_type="application/json") @doc.response(201, {"couriers": [{"id": int}]}, description="Couriers added") @doc.response(400, {"validation_error": { "couriers": [{ "id": int }] }}, description="Some of couriers are invalid") async def add_couriers(request: Request) -> response.HTTPResponse: couriers, invalid_couriers_id = [], [] for courier in request.json['data']: try: courier = CourierModel(**courier)
from rbac.server.api import utils from rbac.common.logs import get_default_logger LOGGER = get_default_logger(__name__) WEBHOOKS_BP = Blueprint("webhooks") @WEBHOOKS_BP.post("webhooks/chatbot") @doc.summary("Webhook that enables chatbot to execute RBAC actions") @doc.description("Webhook that enables chatbot to execute RBAC actions.") @doc.consumes( doc.JsonBody({ "tracker": { "slots": { "resource_id": str, "reason": str, "resource_type": str } }, "sender_id": str, }), location="body", content_type="application/json", required=True, ) @doc.produces( {"events": [{ "event": str, "name": str, "value": int }]}, description="Successful execution of RBAC action returns an event payload",
class UserDataView(HTTPMethodView): @doc.summary("Returns all users documents") @doc.consumes(UsernameHeader, location="header", required=True) @username_required() async def get(self, request: Request): collection = request.app.db[request.headers["username"]] docs = await collection.find().to_list(length=None) for document in docs: document['id'] = str(document['_id']) del document['_id'] result = {"documents_count": docs} return json(result) @doc.summary("Add new document(s) to user collection") @doc.consumes(UsernameHeader, location="header", required=True) @doc.consumes(doc.JsonBody(description="Any json data to store"), location="body", required=True) @username_required() async def post(self, request: Request): if not request.json: return json( { "status": "ERROR", "error_code": 404, "error": "Provide json data!", }, status=404) collection = request.app.db[request.headers["username"]] result = await collection.insert_one(request.json) return json({"status": "OK", "record_id": str(result.inserted_id)}) @doc.summary("Delete document(s) from user collection") @doc.consumes(UsernameHeader, location="header", required=True) @doc.consumes( doc.JsonBody(description="Json for filtering data to delete"), location="body", required=True) @username_required() async def delete(self, request: Request): if not request.json: return json({"error": "Provide json data!"}, status=404) collection = request.app.db[request.headers["username"]] documents_count = await collection.count_documents(request.json) if documents_count < 1: return json( { "status": "ERROR", "error_code": 404, "error": "No data found!" }, status=404) deleted = await collection.delete_many(request.json) return json({ "status": "OK", "deleted_count": deleted.deleted_count }, status=200)
@blueprint.get("/", strict_slashes=True) @doc.summary("Fetches all cars") @doc.description("Really gets the job done fetching these cars. I mean, really, wow.") @doc.produces([Car]) def car_list(request): return json([test_car]) @blueprint.get("/<car_id:int>", strict_slashes=True) @doc.summary("Fetches a car") @doc.produces(Car) def car_get(request, car_id): return json(test_car) @blueprint.put("/<car_id:int>", strict_slashes=True) @doc.summary("Updates a car") @doc.consumes(doc.JsonBody(Car), location='body') @doc.produces(Car) def car_put(request, car_id): return json(test_car) @blueprint.delete("/<car_id:int>", strict_slashes=True) @doc.summary("Deletes a car") @doc.produces(Status) def car_put(request, car_id): return json(test_success)