コード例 #1
0
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)
コード例 #2
0
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)
コード例 #3
0
ファイル: cch.py プロジェクト: Som-Energia/infoenergia-api
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)
コード例 #4
0
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)
コード例 #5
0
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()
コード例 #6
0
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)
コード例 #7
0
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])
コード例 #8
0
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)
コード例 #9
0
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()})
コード例 #10
0
ファイル: initialization.py プロジェクト: shinybrar/sanic-jwt
 def inject_user(self, *args, **kwargs):
     args = list(args)
     args.insert(0, self.instance)
     return inject_user(*args, **kwargs)
コード例 #11
0
class GraphQLView(HTTPMethodView):
    """ Local fork of sanic_graphql lib """

    decorators = [inject_user(), ax_auth.ax_protected()]

    schema = None
    executor = None
    root_value = None
    context = None
    pretty = False
    graphiql = False
    graphiql_version = None
    graphiql_template = None
    middleware = None
    batch = False
    jinja_env = None
    max_age = 86400

    _enable_async = True

    methods = ['GET', 'POST', 'PUT', 'DELETE']

    def __init__(self, **kwargs):
        """ Initiate """
        super(GraphQLView, self).__init__()
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)

        self._enable_async = self._enable_async and isinstance(
            self.executor, AsyncioExecutor)
        assert isinstance(self.schema, GraphQLSchema), 'A Schema is required'

    # noinspection PyUnusedLocal

    def get_root_value(self, request):  # pylint: disable=unused-argument
        """ Some getter """
        return self.root_value

    def get_context(self, request):
        """ Returns saved context. Contains reqest, db_session, user """
        context = (self.context.copy() if self.context
                   and isinstance(self.context, Mapping) else {})
        if isinstance(context, Mapping) and 'request' not in context:
            context.update({'request': request})

        # log_reguest(request)
        # logger.debug(request.json['query'])

        return context

    def get_middleware(self, request):  # pylint: disable=unused-argument
        """ Some getter """
        return self.middleware

    def get_executor(self, request):  # pylint: disable=unused-argument
        """ Some getter """
        return self.executor

    format_error = staticmethod(default_format_error)
    encode = staticmethod(json_encode)

    async def dispatch_request(self, request, *args, **kwargs):
        """ Sanic view request dispatch.  """
        start_time = time.time()  # TODO this is debug profile

        with ax_model.scoped_session("GQL error -") as db_session:
            try:
                request_method = request.method.lower()
                data = self.parse_body(request)

                show_graphiql = request_method == 'get' and self.should_display_graphiql(
                    request)
                catch = show_graphiql

                pretty = self.pretty or show_graphiql or request.args.get(
                    'pretty')

                user = kwargs['user'] or None

                # auth_header = request.headers['authorization']
                # print(auth_header)

                ax_context = self.get_context(request)
                ax_context.update({'session': db_session})
                ax_context.update({'user': user})

                if request_method != 'options':
                    execution_results, all_params = run_http_query(
                        ax_schema.schema,
                        request_method,
                        data,
                        query_data=request.args,
                        batch_enabled=self.batch,
                        catch=catch,

                        # Execute options
                        return_promise=self._enable_async,
                        root_value=self.get_root_value(request),
                        context_value=ax_context,
                        middleware=self.get_middleware(request),
                        executor=self.get_executor(request),
                    )  # pylint: disable=unused-argument
                    del all_params
                    awaited_execution_results = await Promise.all(
                        execution_results)
                    result, status_code = encode_execution_results(
                        awaited_execution_results,
                        is_batch=isinstance(data, list),
                        format_error=self.format_error,
                        encode=partial(self.encode, pretty=pretty))
                    log_reguest(request, (time.time() - start_time))

                    return HTTPResponse(result,
                                        status=status_code,
                                        content_type='application/json')
                else:
                    log_reguest(request, (time.time() - start_time))
                    return self.process_preflight(request)

            except HttpQueryError as err:
                logger.exception(f'graqlView -> {err}')
                return HTTPResponse(self.encode(
                    {'errors': [default_format_error(err)]}),
                                    status=err.status_code,
                                    headers=err.headers,
                                    content_type='application/json')
            except Exception as err:  # pylint: disable=broad-except
                logger.exception(f'graqlView -> {err}')

    # noinspection PyBroadException

    def parse_body(self, request):
        """ - """
        content_type = self.get_mime_type(request)
        if content_type == 'application/graphql':
            return {'query': request.body.decode('utf8')}

        elif content_type == 'application/json':
            return load_json_body(request.body.decode('utf8'))

        elif content_type in ('application/x-www-form-urlencoded',
                              'multipart/form-data'):
            return request.form

        return {}

    @staticmethod
    def get_mime_type(request):
        """ - """
        # We use mimetype here since we don't need the other
        # information provided by content_type
        if 'content-type' not in request.headers:
            return None

        mimetype, _ = parse_header(request.headers['content-type'])
        return mimetype

    def should_display_graphiql(self, request):
        """ - """
        if not self.graphiql or 'raw' in request.args:
            return False

        return self.request_wants_html(request)

    def request_wants_html(self, request):
        """ - """
        accept = request.headers.get('accept', {})
        return 'text/html' in accept or '*/*' in accept

    def process_preflight(self, request):
        """ Preflight request support for apollo-client
        https://www.w3.org/TR/cors/#resource-preflight-requests """
        origin = request.headers.get('Origin', '')
        method = request.headers.get('Access-Control-Request-Method',
                                     '').upper()

        if method and method in self.methods:
            return HTTPResponse(status=200,
                                headers={
                                    'Access-Control-Allow-Origin':
                                    origin,
                                    'Access-Control-Allow-Methods':
                                    ', '.join(self.methods),
                                    'Access-Control-Max-Age':
                                    str(self.max_age),
                                })
        else:
            return HTTPResponse(status=400, )