class PostsView(HTTPMethodView): decorators = [protected()] async def post(self, request: Request): title = request.json.get("title") if title is None or not title: abort(400, "'title' is required") now = time.time() post = await Post.insert_one({"title": title, "createdAt": now}) return json({ "title": title, "createdAt": now, "id": str(post.inserted_id) }) async def get(self, request: Request): posts = await Post.find({}) responses = [] for post in posts.objects: responses.append({ "id": str(post["_id"]), "title": post["title"], "createdAt": post["createdAt"] }) return json(responses)
class PostView(HTTPMethodView): decorators = [protected()] async def get(self, request: Request, id): if not ObjectId.is_valid(id): abort(400, "Id is not valid!") post = await Post.find_one({"_id": ObjectId(id)}) if post is None: abort(404, "Post not found!") return json({ "title": post["title"], "createdAt": post["createdAt"], "id": str(post["_id"]) }) async def delete(self, request: Request, id): if not ObjectId.is_valid(id): abort(400, "Id is not valid!") post = await Post.find_one({"_id": ObjectId(id)}) if post is None: abort(404, "Post not found!") await Post.delete_one({"_id": ObjectId(id)}) return text("Post deleted", status=201)
class OrderView(HTTPMethodView): decorators = [protected()] # 启用路由保护 @doc.summary("订单列表") async def get(self, request): query = request.args.get('query', None) if query: sql_where = f"WHERE is_delete=False and (order_id like '%{query}%' or customer_phone like '%{query}%')" else: sql_where = None status, response = await get_query_response( request=request, table='tb_sale_order', int_params=[], numeric_params=['purchase_price', 'price'], mis_params=[], sql_where=sql_where) return json(response, status=status) @doc.summary("订单添加") async def post(self, request): status, response = await post_create_response( request=request, table='tb_sale_order', numeric_params=['purchase_price', 'price'], fields=t_files.get('sale_orders_required')) return json(response, status=status) @doc.summary("订单批量删除") async def delete(self, request): status, response = await delete_unlink_response(request=request, table='tb_sale_order', fields=['is_delete']) return json(response, status=status)
class OrderUpdateView(HTTPMethodView): decorators = [protected()] # 启用路由保护 @doc.summary("订单指定查询") async def get(self, request, order_id): status, response = await get_instance_response( request=request, table='tb_sale_order', id=order_id, numeric_params=['purchase_price', 'price']) return json(response, status=status) @doc.summary("订单指定修改") async def put(self, request, order_id): status, response = await put_update_response( request=request, table='tb_sale_order', id=order_id, numeric_params=['purchase_price', 'price'], fields=t_files.get('sale_orders_required')) return json(response, status=status) @doc.summary("订单指定删除") async def delete(self, request, order_id): status, response = await delete_instance_response( request=request, id=order_id, table='tb_sale_order', fields=['is_delete']) return json(response, status=status)
class NormalizationView(HTTPMethodView): decorators = [protected()] def post(self, request): body_json = request.body.decode('utf-8') body_decoded = loads(body_json) normalized = {current["name"]: current[[x for x in current.keys() if "val" in x.lower()][0]] for current in body_decoded} return json(normalized)
class UploadImageView(HTTPMethodView): """ 上传图片文件接口, business and functionality should be separated, and, too lazy to write """ decorators = [protected()] def __init__(self): self.collection = app.mongo["account_center"].user self.user_model = UserModel(self.collection) self.follower_model = Follower(app.mongo["account_center"].follower) self.friends_model = FriendModel(app.mongo["account_center"].friends) async def post(self, request): user_id = await get_user_id_by_request(request) return_data = {"message": "success", "code": "200", "results": {}} image = request.files.get('file', None) assert image, "文件对象名字不正确" image = image.body # 判断文件是否支持 image_name = request.files.get('file').name image_suffix = get_suffix(image_name) if 'error' in image_suffix: return_data['code'] = "300" return_data['message'] = "图片不支持" return json(return_data) # 组织图片存储路径 m1 = hashlib.md5() m1.update(image) md5_name = m1.hexdigest() # 用 md5 的前两位来建文件夹,防止单个文件夹下图片过多,又或者根目录下建立太多的文件夹 save_dir = HEAD_PATH + md5_name[0:2] + '/' save_path = save_dir + md5_name[2:] + '.' + image_suffix res_path = '/' + md5_name[0:2] + '/' + md5_name[2:] + '.' + image_suffix # 如果文件夹不存在,就创建文件夹 if not os.path.exists(save_dir): os.makedirs(save_dir) # 将文件写入到硬盘 temp_file = open(save_path, 'wb') temp_file.write(image) temp_file.close() # im = Image.open(HEAD_PATH + res_path) sum_path = "/static/img/user/head" + res_path await update_server.update_head("head", sum_path, user_id, self.user_model, self.follower_model, self.friends_model, app) # await self.user_model.update_head(user_id, sum_path) # 给客户端返回结果 return_data['results']['path'] = do_main + sum_path return_data['results']['width'] = im.size[0] return_data['results']['height'] = im.size[1] return json(return_data)
class PolyDataResource(Resource): decorators = [protected()] async def get(self, request: Request, object_id: int): result = poly_db.get(doc_id=object_id) if not result: raise ApiError( status_code=404, error_code="Not Found", message=f"Resource with id {object_id} was not found", ) return json(asdict(PolyData(object_id=result.doc_id, data=result["data"]))) async def delete(self, request: Request, object_id: int): try: _ = poly_db.remove(doc_ids=[object_id]) except KeyError: pass return "", 204
class TasksView(HTTPMethodView): decorators = [protected(), inject_user()] async def post(self, request, trip_id, user): task_title = request.json.get('title') task_suggestion = request.json.get('converted_suggestion', None) task_importance = request.json.get('importance', 0) task_validator = NewTaskValidator(title=task_title) if not await task_validator.is_valid(): return json({ 'status': 'failed validation', 'errors': task_validator.errors }) users_trip = await UsersTrip.query.where(UsersTrip.user_id == user.id) \ .where(UsersTrip.trip_id == int(trip_id)).gino.first() if not users_trip: return json({'status': 'not found'}, status=404) task = await Task.create(title=task_title, trip_id=int(trip_id), converted_suggestion=task_suggestion, importance=task_importance) return json(task.serialize()) async def get(self, request, trip_id, user): users_trip = await UsersTrip.query.where(UsersTrip.user_id == user.id) \ .where(UsersTrip.trip_id == int(trip_id)).gino.first() if not users_trip: return json({'status': 'not found'}, status=404) tasks = await Task.query.where(Task.trip_id == int(trip_id)).gino.all() return json({ 'tasks': [task.serialize() for task in tasks], 'suggestions': [] })
def add_swagger_doc(): AuthenticateEndpoint.decorators.extend([ doc.summary("Authenticate user and get token"), doc.consumes(LoginSwDoc, location='body'), doc.produces(LoginSwDoc), ]) RetrieveUserEndpoint.decorators.extend([ doc.summary("Retrieve use logged in"), doc.consumes({'AUTHORIZATION': str}, location='header'), ]) VerifyEndpoint.decorators = [ protected(), doc.summary("Verify token"), doc.consumes({'Authorization': str}, location='header'), ] RefreshEndpoint.decorators.extend([ doc.summary("refresh token"), doc.consumes({'Authorization': str}, location='header'), doc.consumes({'refresh_token': str}, location='body'), ])
class TaskDetailView(HTTPMethodView): decorators = [protected(), inject_user()] async def delete(self, request, trip_id, task_id, user): users_trip = await UsersTrip.query.where(UsersTrip.user_id == user.id) \ .where(UsersTrip.trip_id == int(trip_id)).gino.first() if not users_trip: return json({'status': 'not found'}, status=404) await Task.delete.where(Task.id == int(task_id)).gino.status() return json({'status': 'deleted'}) async def put(self, request, trip_id, task_id, user): new_title = request.json.get('title') new_suggestion = request.json.get('converted_suggestion', None) new_importance = request.json.get('importance', 0) task_validator = NewTaskValidator(title=new_title) if not await task_validator.is_valid(): return json({ 'status': 'failed validation', 'errors': task_validator.errors }) users_trip = await UsersTrip.query.where(UsersTrip.user_id == user.id) \ .where(UsersTrip.trip_id == int(trip_id)).gino.first() if not users_trip: return json({'status': 'not found'}, status=404) task = await Task.get(int(task_id)) await task.update(title=new_title, trip_id=int(trip_id), converted_suggestion=new_suggestion, importance=new_importance).apply() return json({'status': 'modified', 'task': task.serialize()})
class Tester(TestMethodView): decorators = [protected()] async def get(self, request): return text("ok")
class SanixGraphql(GraphQLView): schema = schema graphiql = True decorators = [protected(), inject_user()] middleware = [AuthorizationMiddleware]