class F1MeasuresView(PaginationLinksMixin, HTTPMethodView): decorators = [ inject_user(), protected(), ] endpoint_name = 'f1.get_f1_measures' async def get(self, request, user): logger.info("Getting f1 measures") request.ctx.user = user invoices_ids, links, total_results = await self.paginate_results( request, function=async_get_invoices) f1_measure_json = [ await request.app.loop.run_in_executor( request.app.thread_pool, lambda: Invoice(invoice_id).f1_measures) for invoice_id in invoices_ids ] response = { 'total_results': total_results, 'count': len(f1_measure_json), 'data': f1_measure_json } response.update(links) return json(response)
class TariffContractIdView(PaginationLinksMixin, HTTPMethodView): decorators = [ protected(), ] endpoint_name = 'tariff.get_tariff_by_contract_id' async def get(self, request, contractId): logger.info("Getting tariffs") tariff_price_ids, links, total_results = await self.paginate_results( request, function=async_get_tariff_prices, contractId=contractId ) tariff_json = list(filter(None, [ await request.app.loop.run_in_executor( request.app.thread_pool, lambda: TariffPrice(tariff_price_id).tariff ) for tariff_price_id in tariff_price_ids ])) tariff_results = len(tariff_json) reactive_energy_json = ReactiveEnergyPrice.create().reactiveEnergy tariff_json.append(reactive_energy_json) response = { 'count': tariff_results, 'data': tariff_json } response.update(links) return json(response)
class ModContractsView(PaginationLinksMixin, HTTPMethodView): decorators = [ inject_user(), protected(), ] endpoint_name = 'modcontracts.get_modcontracts' async def get(self, request, user): logger.info("Getting contractual modifications") request.ctx.user = user contracts_ids, links, total_results = await self.paginate_results( request, function=async_get_modcontracts) contracts_json = [ await request.app.loop.run_in_executor( request.app.thread_pool, lambda: Contract(contract_id).contracts) for contract_id in contracts_ids ] response = { 'total_results': total_results, 'count': len(contracts_json), 'data': contracts_json } response.update(links) return json(response)
class CustomerRouter(HTTPMethodView): decorators = [protected(), inject_user()] async def get(self, request: Request, user: User): customers = await Customer.all() return json([customer.dict() for customer in customers]) async def post(self, request: Request, user: User): customer = Customer(**request.json) await customer.save() return json(customer.dict(), status=201) async def put(self, request: Request, user: User): customer = await Customer.filter(id=request.args.get('id', None) ).first() if customer is None: return empty(status=404) customer.name = request.json.get('name', customer.name) await customer.save() return json(customer.dict()) async def delete(self, request: Request, user: User): customer = await Customer.filter(id=request.args.get('id', None) ).first() if customer is None: return empty(status=404) await customer.delete() return empty()
class UserView(HTTPMethodView): decorators = [protected(), ] @doc.summary("Fetches a user by ID") @doc.produces({"user": {"name": str, "id": int}}) async def get(self, request): import pdb pdb.set_trace() name = request.raw_args.get('name', '') persons = Person.select() if name: persons = persons.select().where(Person.name == name) persons_list = [model_to_dict(p) for p in persons] return HTTPResponse(sjson.dumps(persons_list, default=str)) async def post(self, request): # import pdb # pdb.set_trace() data = request.form post_data = {'name': data.get('name', ''), 'birthday': data.get('birthday', '')} persons = Person.create(**post_data) # persons = Person.insert_many(**data) # persons = [model_to_dict(i) for i in persons] # return json(model_to_dict(persons)) return HTTPResponse(sjson.dumps(persons, default=str)) def put(self, request): pass def patch(self, request): pass def delete(self, request): pass
class CchMeasuresView(PaginationLinksMixin, HTTPMethodView): decorators = [ inject_user(), protected(), ] endpoint_name = 'cch.get_cch_measures' async def get(self, request, user): request.ctx.user = user logger.info("Getting cch measures") cch_ids, links, total_results = await self.paginate_results( request, function=async_get_cch ) collection = request.args['type'][0] if collection in ('P1', 'P2'): collection = 'tg_p1' cch_measure_json = [ await (await Cch.create(cch_id, collection)).cch_measures(user, request) for cch_id in cch_ids ] response = { 'total_results': total_results, 'count': len(cch_measure_json), 'data': cch_measure_json } response.update(links) return json(response)
class ReportsView(PaginationLinksMixin, HTTPMethodView): decorators = [ inject_user(), protected(), ] endpoint_name = 'reports.reports' async def post(self, request, user): logger.info("Uploading contracts") report_ids, month, type = await get_report_ids(request) bapi = await BeedataApiClient.create( url=request.app.config.BASE_URL, username=request.app.config.USERNAME, password=request.app.config.PASSWORD, company_id=request.app.config.COMPANY_ID, cert_file=request.app.config.CERT_FILE, cert_key=request.app.config.KEY_FILE) request.app.loop.create_task( Beedata(bapi, request.app.mongo_client, request.app.redis).process_reports(report_ids, month, type)) response = { 'reports': len(report_ids), } return json(response)
class LogoutView(BaseEndpoint): decorators = [protected()] def post(self, request): response = HTTPResponse(status=204) del response.cookies['access_token'] return response
class Follow(HTTPMethodView): 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) # def get(self, request): # # get logging user follow # print(dir(request)) # print(request.args) # return json("this is protected") async def post(self, request): """ add logging user following follow_user_id data = {"following_user_id": ""} :param request: :return: """ # param check # print(" user_id ", user.user_id) login_user_id = await get_user_id_by_request(request) if not login_user_id: raise AuthenticationFailed() # assert login_user_id, following_user_id = request.json.get("following_user_id", None) assert following_user_id, "参数不能为空" assert login_user_id != following_user_id, ( "关注错误,自己不能关注自己", "login_user_id {}, following_user_id {}".format(login_user_id, following_user_id)) # 1 check user id is real user await check_server.is_user(following_user_id, self.user_model) # 2 update or created follow relationship in mongo # count = self.follower_model.update_or_created_follow_relationship() # write follower collection server await write_model_server.write_follower_relationship(app, self.follower_model, self.user_model, self.friends_model, login_user_id, following_user_id) # res = await self.follower_model.update_or_created_follow_relationship_by_data(login_user_id, following_user_id) # if res is not "existed": # # if login id have not follow relationship. then inc following and followers count # # 3 a->b check, a is <- b, then add friend relationship # if await self.follower_model.check_is_mutual_follow(login_user_id, following_user_id): # await self.friends_model.add(login_user_id, following_user_id) # await app.redis.sadd("{}_{}".format(login_user_id, "friends"), following_user_id) # await app.redis.sadd("{}_{}".format(following_user_id, "friends"), login_user_id) # # # 4 update or created follow redis # await self.user_model.add_follow_count(login_user_id, following_user_id) # if isinstance(following_user_id, bytes): # following_user_id = following_user_id.decode() # await app.redis.sadd("{}_{}".format(login_user_id, "follower"), following_user_id) return json(response_package("200", {}))
class UnFollow(HTTPMethodView): 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) # def get(self, request): # # get logging user follow # print(dir(request)) # print(request.args) # return json("this is protected") async def post(self, request): """ add logging user following follow_user_id data = {"following_user_id": ""} :param request: :return: """ # param check login_user_id = await get_user_id_by_request(request) assert login_user_id, "当前没有用户登录" following_user_id = request.json.get("un_following_user_id", None) assert following_user_id, "参数不能为空" assert login_user_id != following_user_id, ( "取消关注错误,自己不能对自己操作", "login_user_id {}, following_user_id {}".format(login_user_id, following_user_id)) # 1 check user id is real user await check_server.is_user(following_user_id, self.user_model) # 2 update or created follow relationship in mongo # count = self.follower_model.update_or_created_follow_relationship() await write_model_server.write_unfollower_relationship(app, self.follower_model, self.user_model, self.friends_model, login_user_id, following_user_id) # res = await self.follower_model.update_or_created_follow_relationship(login_user_id, following_user_id) # await self.follower_model.delete_follow_relationship(login_user_id, following_user_id) # if res is not "is_null": # # if login id have not follow relationship. then inc following and followers count # # 3 delete friend relationship # await self.friends_model.remove(login_user_id, following_user_id) # await app.redis.srem("{}_{}".format(login_user_id, "friends"), following_user_id) # await app.redis.srem("{}_{}".format(following_user_id, "friends"), login_user_id) # # # 4 update or created redis # await self.user_model.sub_follow_count(login_user_id, following_user_id) # await app.redis.srem("{}_{}".format(login_user_id, "follower"), count=1, value=following_user_id) return json(response_package("200", {}))
class RecordView(HTTPMethodView): decorators = [protected(), scoped('user'), inject_user()] async def post(self, request, user): payload = request.json project = Project.objects(name=payload['project_name']).first() payload = { "function_name": payload['name'], "start_time": datetime.fromtimestamp(payload['start']), "end_time": datetime.fromtimestamp(payload['end']), "arguments": json.dumps(payload['arguments']), "call_params": json.dumps(payload['call_params']), "type": payload['type'], "project_id": project.id, "user_id": user['id'], } print(payload) record = Record.create(**payload) return res.json({ "status": 201, "message": "Record Created", "record_id": str(record.id) }) async def get(self, request, user): payload = request.raw_args print(request.raw_args) project = Project.objects( name=payload['project_name']).allow_filtering().first() records = Record.objects( user_id=user['id'], project_id=project.id).allow_filtering().all() for record in records: if record['arguments']: record['arguments'] = json.loads(record['arguments']) if record['call_params']: record['call_params'] = json.loads(record['call_params']) payload = [{ **r, "start_time": r['start_time'].timestamp(), "end_time": r['end_time'].timestamp(), "id": str(r['id']), "project_id": str(r['project_id']), "user_id": str(r['user_id']) } for r in records] return res.json(payload)
class ProjectView(HTTPMethodView): decorators = [protected(), scoped('user'), inject_user()] async def post(self, request, user): payload = request.json payload['access_token'] = "some_token" payload['user_id'] = user['id'] if 'name' not in payload: return res.json({"message": "name is required"}, status=400) project_exists = Project.objects( name=payload['name'], user_id=user['id']).allow_filtering().first() if project_exists: return res.json({ "message": "Project Already Exists", }, status=409) project = Project.create(**payload) return res.json( { "message": "Project Created", "project_id": str(project.id) }, status=200) async def get(self, request, user): print(user) payload = Project.objects(user_id=user['id']).all() payload = [{ **p, "id": str(p['id']), "user_id": str(p['user_id']) } for p in payload] return res.json(payload)
class ChangePassword(HTTPMethodView): decorators = [protected()] def __init__(self): self.collection = app.mongo["account_center"].user self.user_model = UserModel(self.collection) async def post(self, request): try: user_id = await get_user_id_by_request(request) new_password = request.json.get("new_password", None) old_password = request.json.get("old_password", None) print(request.json) assert old_password, "原始密码未填写" assert new_password, "新密码未填写" doc = await check_server.is_user(user_id, self.user_model) assert doc["password"] == gen_password(old_password), "原始密码不对" await self.user_model.update_password(user_id, gen_password(new_password)) return response.json(response_package("200", {})) except TimeoutError as e: return response.json(response_package("999", {"e": str(e)}))
class TripsView(HTTPMethodView): decorators = [protected(), inject_user()] async def post(self, request, user): trip_title = request.json.get('title') trip_country = request.json.get('country') trip_city = request.json.get('city') trip_date = request.json.get('date') trip_validator = NewTripValidator(title=trip_title, city=trip_city, country=trip_country, date=trip_date) if not await trip_validator.is_valid(): return json({ 'status': 'failed validation', 'errors': trip_validator.errors }) trip = await Trip.create(title=trip_title, city=trip_city, country=trip_country, date=datetime.strptime(trip_date, '%Y-%m-%d').date()) await UsersTrip.create(user_id=user.id, trip_id=trip.id, is_owner=True) return json(trip.serialize()) async def get(self, request, user): trips = await UsersTrip.join(Trip).select(UsersTrip.user_id == user.id ).gino.all() trips = [ Trip(id=trip[4], title=trip[5], country=trip[6], city=trip[7], date=trip[8]) for trip in trips ] return json([trip.serialize() for trip in trips])
class EditView(HTTPMethodView): decorators = [protected()] fields = ["self_introduction", "name"] unique = ["name"] update_to_friend_follow = ["name"] 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 patch(self, request): try: user_id = await get_user_id_by_request(request) data = request.json new_data = {} for k, v in data.items(): if k not in self.fields: continue new_data[k] = v for k, v in new_data.items(): if k in self.unique: res = await self.user_model.check_unique_simple_field(k, v) if res is False: raise InvalidUsage("{} 已被使用".format(v)) # name need update to follow and friend collection doc = await self.user_model.update_by_id(user_id, new_data) if not doc: return response.json(response_package("500", {"error_id": str(user_id)})) for k, v in new_data.items(): if k in self.update_to_friend_follow: await update_server.update_name(k, v, user_id, self.follower_model, self.friends_model, app, self.user_model) data = await UserReadModel(data=doc, status="").to_dict() return response.json(response_package("200", data)) except TimeoutError as e: return response.json(response_package("999", {"e": str(e)}))
class TripDetailView(HTTPMethodView): decorators = [protected(), inject_user()] 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) trip = await Trip.get(int(trip_id)) return json(trip.serialize()) async def delete(self, request, trip_id, user): users_trip = await UsersTrip.query.where(UsersTrip.user_id == user.id)\ .where(UsersTrip.trip_id == int(trip_id))\ .where(UsersTrip.is_owner == True).gino.first() if not users_trip: return json({'status': 'not found'}, status=404) await Trip.delete.where(Trip.id == int(trip_id)).gino.status() return json({'status': 'deleted'}) async def put(self, request, trip_id, user): new_title = request.json.get('title') new_country = request.json.get('country') new_city = request.json.get('city') new_date = request.json.get('date') 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) trip = await Trip.get(int(trip_id)) await trip.update(title=new_title, country=new_country, city=new_city, date=datetime.strptime(new_date, '%Y-%m-%d').date()).apply() return json({'status': 'modified', 'trip': trip.serialize()})
class UserList(HTTPMethodView): decorators = [protected()] async def get(self, request): users = [] for user in User.select(): users.append({ "username": user.username, "password": user.password, "join_date": user.join_date }) return response.json(users) async def post(self, request): message = {} post = request.json username = post['username'] password = post['password'] if username == "": message['error'] = "username is required" elif len(username) < 6: message['error'] = "username must be atleast 6 chars" elif password == "": message['error'] = "password is required" elif len(password) < 6: message['error'] = "password must be atleast 6 chars" else: hash_password = hashlib.sha256( str(password).encode('utf-8')).hexdigest() insert = User.create(username=username, password=hash_password) message['success'] = "User created successfully" return response.json({'message': message, 'status': 201}) return response.json({'message': message})
def protected(self, *args, **kwargs): args = list(args) args.insert(0, self.instance) return protected(*args, **kwargs)
class HomeView(HTTPMethodView): decorators = [protected()] async def get(self, request): return jinja.render('home.html', request)
class ProtectedView(HTTPMethodView): decorators = [protected()] async def get(self, request): return json({"protected": True})
class AuthApi(HTTPMethodView): """Application Interface for RPS""" def __init__(self, loop=None, port=8080, site=None, amqp=None, id=None, username=None, password=None): loop = loop or asyncio.get_event_loop() self.app = Sanic(__name__) self.site = site self.port = port self.amqp = amqp self.db = {} users.append(User(id, username, password)) self.app.add_route(self.index, "/", methods=['GET'], strict_slashes=True) self.app.add_route(self.as_view(), "/v2/events", strict_slashes=True) def start(self): Initialize(self.app, authenticate=authenticate) self.app.run(host='0.0.0.0', port=self.port) async def index(self, request): return json({ 'info': '000000000000', 'amqp': '111111111111', 'api_version': 'V1', 'api': ['v2/system'], 'modules version': 'IPP-I' }) def get_system(self): return [{ "version": "1.1.0", "id": 201, "type": "alarm", "system": 1, "segment": 2, "offset": 0.5, "timestamp": "2018-01-01 08:30:45", "remark": "reserve" }, { "version": "1.1.0", "id": 208, "type": "alarm", "system": 3, "segment": 9, "offset": 0.8, "timestamp": "2018-01-01 09:39:01", "remark": "reserve" }] decorators = [protected()] async def get(self, request): data = self.get_system() return json(data)