示例#1
0
    async def post(self) -> Response:
        """Post route function."""
        db = self.request.app["db"]
        # Authenticate and authorize:
        token = await extract_token_from_request(self.request)
        await AuthorizationService.authorize(db, token, [Role.ADMIN, Role.USER_ADMIN])

        # Process request:
        body = await self.request.json()
        logging.debug(f"Got create request for user {body} of type {type(body)}")

        try:
            user = User.from_dict(body)
        except KeyError as e:
            raise HTTPUnprocessableEntity(
                reason=f"Mandatory property {e.args[0]} is missing."
            ) from e

        try:
            id = await UsersService.create_user(db, user)
        except IllegalValueException as e:
            raise HTTPUnprocessableEntity() from e
        if id:
            logging.debug(f"inserted document with id {id}")
            headers = MultiDict([(hdrs.LOCATION, f"{BASE_URL}/users/{id}")])

            return Response(status=201, headers=headers)
        raise HTTPBadRequest() from None
示例#2
0
    async def put(self) -> Response:
        """Put route function."""
        db = self.request.app["db"]
        # Authenticate and authorize:
        token = await extract_token_from_request(self.request)
        await AuthorizationService.authorize(db, token, [Role.ADMIN, Role.USER_ADMIN])

        # Process request:
        body = await self.request.json()
        try:
            user = User.from_dict(body)
        except KeyError as e:
            raise HTTPUnprocessableEntity(
                reason=f"Mandatory property {e.args[0]} is missing."
            ) from e

        id = self.request.match_info["id"]
        logging.debug(f"Got request-body {body} for {id} of type {type(body)}")
        try:
            await UsersService.update_user(db, id, user)
        except IllegalValueException as e:
            raise HTTPUnprocessableEntity() from e
        except UserNotFoundException as e:
            raise HTTPNotFound() from e
        return Response(status=204)
示例#3
0
def _deserialize_user_type(value):
    value = value.upper()
    if value in [t.name for t in UserType]:
        return UserType[value]
    else:
        raise HTTPUnprocessableEntity(text=json.dumps({
            "type": ["Unsupported value"],
        }))
示例#4
0
 async def post(self):
     data = await self.request.json()
     try:
         timestamp = int(parse(data['timestamp']).strftime('%s'))
     except KeyError:
         return HTTPUnprocessableEntity(text="Missing data for timestamp field.")
     except ValueError:
         return HTTPUnprocessableEntity(text="Not a valid datetime.")
     tr = self.redis.multi_exec()
     try:
         for sensor in data['sensors']:
             tr.zadd(self.thingy_uuid+':'+sensor, timestamp, dumps(data))
             await self.redis.publish_json(self.thingy_uuid+'.sensors.'+sensor, data)
     except KeyError:
         return HTTPUnprocessableEntity(text="Missing data for sensors field.")
     tr.sadd('thingy', self.thingy_uuid)
     await tr.execute()
     return json_response(data)
示例#5
0
async def json_handler(request, handler):
    if request.content_type == "application/json":
        try:
            body = await request.json()
            request["json"] = body
        except JSONDecodeError:
            raise HTTPUnprocessableEntity(
                text=json.dumps({"error_message": "Invalid json"}))
    else:
        request["json"] = {}

    resp = await handler(request)

    return resp
示例#6
0
async def handle(request):
    try:
        data = await request.json()
    except JSONDecodeError as e:
        return HTTPUnprocessableEntity(text=e.msg)
    try:
        coefficients = data['coefficients']
    except KeyError:
        return HTTPUnprocessableEntity(
            text="Missing data for coefficients field.")
    try:
        constraints = data['constraints']
    except KeyError:
        return HTTPUnprocessableEntity(
            text="Missing data for constraints field.")

    # define the problem
    prob = pl.LpProblem("voting", pl.LpMaximize)

    variables = variables_gen(len(coefficients))
    # objective function - maximize value of objects in voting
    prob += reduce(add, map(mul, coefficients, variables))

    for c in constraints:
        try:
            c_variables = [variables[cv] for cv in c['variables']]
            c_operator = operators[c['operator']]
            c_value = c['value']
            prob += c_operator(reduce(add, c_variables), c_value)
        except KeyError:
            raise

    status = prob.solve()  # solve using the default solver, which is cbc
    if status != pl.LpStatusOptimal:
        return HTTPUnprocessableEntity(text=pl.LpStatus[status])

    return json_response(list(map(pl.value, variables)))
示例#7
0
async def default_handler(request: Request) -> str:
    args_schema = {
        'foo': {
            'type': 'integer',
            'coerce': int,
            'required': True,
        },
        'bar': {
            'type': 'float',
            'coerce': float,
            'required': False,
            'default': 0.0,
        },
    }
    validator = Validator(args_schema)
    if not validator.validate(dict(request.query)):
        raise HTTPUnprocessableEntity()

    await asyncio.sleep(1.0)
    return 'bar'