Exemplo n.º 1
0
    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)
async def oauth_start(req: Request):
    state = state_store.issue()
    url = authorization_url_generator.generate(state)
    return HTTPResponse(
        status=200,
        body=f'<a href="{url}">' \
           f'<img alt=""Add to Slack"" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/[email protected] 2x" /></a>'
    )
 def response(self, id, error):
     id = id if id else uuid.uuid1().__str__()
     base64_data, code = self.code()
     session[id] = code
     body = self.body.format(base64_data=base64_data, error=error)
     response = HTTPResponse(body, content_type="text/html; charset=utf-8")
     response.cookies["uuid"] = id
     return response
Exemplo n.º 4
0
async def create_resource(request: Request) -> HTTPResponse:
    # If you want to be really fancy, here, you could generate the `route` name
    # from your API docs, or from your function name, or something like that.
    await verify_auth('create-resource', request.headers)

    # business logic goes here

    return HTTPResponse('successfully created resource', status=200)
Exemplo n.º 5
0
async def process_file_async(request: Request):
    file_path = request.body.decode('utf8')
    if not file_path:
        return HTTPResponse(status=400)

    with provide_throttling() as throttling:
        await throttling
        features_path = await extract_features_async(file_path)
        if not features_path:
            return HTTPResponse(status=500)

        results = await run_model_async(features_path)

        return json({
            'features_path': features_path,
            'data': list(r.to_tuple() for r in results)
        })
Exemplo n.º 6
0
async def json(request):
    await asyncio.sleep(10)

    return HTTPResponse(
        data,
        headers=None,
        status=200,
        content_type="application/json",
    )
Exemplo n.º 7
0
 async def get(self, request, doc_id):
     doc = await self.mongo.get_doc(doc_id=doc_id)
     if doc:
         return HTTPResponse(body=self.mongo.docs_to_json(doc),
                             content_type="application/json")
     else:
         raise sanic.exceptions.NotFound(
             message='Cannot find document with'
                     ' id:{0}'.format(doc_id))
Exemplo n.º 8
0
def jobs_results_id_delete(request: Request, job_id: str, result_id: str) -> HTTPResponse:
    try:
        url_root = _get_url_root(request)
        JobDeleteService(url_root, job_id).delete_partial(result_id)
        return HTTPResponse({})
    except Exception as e:
        log.exception(e)
        message = 'Error while deleting : job_id = {}, result_id = {}'.format(job_id, result_id)
        raise ServerError(message, status_code=500)
Exemplo n.º 9
0
async def provide_to_model(request, model_type, model_name):
    print(request.method)
    if request.method == 'GET':
        response = json(get_model_data(model_type, model_name, request.args))
        response.content_type = 'application/json; charset=utf-8;'
    elif request.method == 'POST':
        update_model_data(model_type, model_name, loads(request.json))
        response = HTTPResponse(status=200, body='OK')
    return response
Exemplo n.º 10
0
            def wrapped(*args, **kwargs):
                if asyncio.iscoroutinefunction(func):
                    coro = func
                else:
                    coro = asyncio.coroutine(func)

                context = yield from coro(*args, **kwargs)

                # wrapped function return HTTPResponse
                # instead of dict-like object
                if isinstance(context, HTTPResponse):
                    return context

                # wrapped function is class method
                # and got `self` as first argument
                if isinstance(args[0], HTTPMethodView):
                    request = args[1]
                else:
                    request = args[0]

                if context is None:
                    context = {}

                env = getattr(request.app, "jinja_env", None)
                if not env:
                    raise ServerError(
                        "Template engine has not been initialized yet.",
                        status_code=500)
                try:
                    template = env.get_template(template_name)
                except TemplateNotFound as e:
                    raise ServerError(
                        "Template '{}' not found".format(template_name),
                        status_code=500)
                if not isinstance(context, Mapping):
                    raise ServerError(
                        "context should be mapping, not {}".format(
                            type(context)),
                        status_code=500,
                    )
                # if request.get(REQUEST_CONTEXT_KEY):
                #     context = dict(request[REQUEST_CONTEXT_KEY], **context)
                update_request_context(request, context)

                if request.app.enable_async:
                    text = yield from template.render_async(context)
                else:
                    text = template.render(context)

                content_type = "text/html; charset={}".format(encoding)

                return HTTPResponse(
                    text,
                    status=status,
                    headers=headers,
                    content_type=content_type,
                )
Exemplo n.º 11
0
 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))
Exemplo n.º 12
0
async def image_from_id(request, id):
    path = await conn.fetchval("select path from pictures where id = $1", id)
    async with aiofiles.open(path, 'rb') as f:
        data = await f.read()

    return HTTPResponse(status=200,
                        headers=None,
                        content_type="image/jpeg",
                        body_bytes=data)
Exemplo n.º 13
0
def create_product(request: Request) -> HTTPResponse:
    product_storage = request.app.services.product_storage
    product_data = request.json
    try:
        product_storage.create_product(product_data)
    except Exception:
        raise Exception('Failed to create product')

    return HTTPResponse(status=204)
Exemplo n.º 14
0
async def image_from_id(request):
    path = request.args['path'][0]
    async with aiofiles.open(path, 'rb') as f:
        data = await f.read()

    return HTTPResponse(status=200,
                        headers=None,
                        content_type="image/jpeg",
                        body_bytes=data)
Exemplo n.º 15
0
async def get_idioms(request):
    if 'query' not in request.args:
        return HTTPResponse(status=400, body='invalid query')

    query = ''.join(request.args['query'])
    if len(query) > 15:
        return HTTPResponse(status=400, body='query too long')

    try:
        res = await scraper.scrape_idioms(query)
        return json([{
            'idiom': r[0],
            'score': r[1]
        } for r in res],
                    ensure_ascii=False)
    except Exception as e:
        logger.exception(e)
        return HTTPResponse(status=503)
Exemplo n.º 16
0
async def get_initialize(request):
    db_initialize()
    global VOTE_CACHE, VOTE_COUNT_CACHE, VOTE_KEYWORD_CACHE, HTML_CACHE, VOTE_COUNTER
    VOTE_CACHE = defaultdict(int)
    VOTE_COUNT_CACHE = defaultdict(int)
    VOTE_KEYWORD_CACHE = defaultdict(Counter)
    HTML_CACHE = {}
    VOTE_COUNTER = 0
    return HTTPResponse()
Exemplo n.º 17
0
 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))
Exemplo n.º 18
0
async def status(request: Request) -> HTTPResponse:
    redis = request.app.redis

    with timeout(1):
        result = await redis.ping()

    if result != b'PONG':
        return HTTPResponse("Backend is not Redis", status=500)

    return text("OK", status=200)
Exemplo n.º 19
0
def test_response_body_bytes_deprecated(app):
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter("always")

        HTTPResponse(body_bytes=b"bytes")

        assert len(w) == 1
        assert issubclass(w[0].category, DeprecationWarning)
        assert ("Parameter `body_bytes` is deprecated, use `body` instead"
                in str(w[0].message))
Exemplo n.º 20
0
def redirect(to,
             headers=None,
             status=302,
             content_type="text/html; charset=utf-8"):
    headers = headers or {}
    safe_to = to
    headers["Location"] = safe_to
    return HTTPResponse(status=status,
                        headers=headers,
                        content_type=content_type)
Exemplo n.º 21
0
async def configurate(request):
    try:
        configuration = request.json
        logger.debug('configuration: %s', configuration)
    except InvalidUsage:
        logger.error('invalid configuration')
        return HTTPResponse(status=400)

    if configuration:
        try:
            await sc.update_servers(configuration)
            logger.debug('configuration succedded')
            return HTTPResponse()
        except Exception as e:
            logger.error('failed to configurate: %s', e)
            return HTTPResponse(status=500)
    else:
        logger.error('empty configuration')
        return HTTPResponse(status=400)
Exemplo n.º 22
0
    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, )
Exemplo n.º 23
0
def json(body: Dict[str, Any],
         status: int = 200,
         headers: Optional[Any] = None,
         content_type: str = "application/json",
         **kwargs: Any) -> HTTPResponse:
    return HTTPResponse(
        dumps(body, separators=(",", ":"), cls=APIJSONEncoder, **kwargs),
        headers=headers,
        status=status,
        content_type=content_type,
    )
Exemplo n.º 24
0
def ParameterException(request):
    return HTTPResponse(
        json_dumps({
            "error_code": 1000,
            "message": "invalid parameter",
            "request": request.method + " " + request.path
        }),
        headers=None,
        status=400,
        content_type="application/json",
    )
Exemplo n.º 25
0
    def run(self):
        if self.request.method == 'GET':
            return self.get()
        elif self.request.method == 'POST':
            return self.post()
        elif self.request.method == 'PATCH':
            return self.patch()
        elif self.request.method == 'DELETE':
            return self.delete()

        return HTTPResponse(status=405)
Exemplo n.º 26
0
    async def distrib(request):
        potatoes = dbServer.get_all_potatoes()
        pie_chart = pygal.Pie()
        for potato in potatoes:
            pie_chart.add(potato['type'], int(potato['count']))

        return HTTPResponse(
            body_bytes=pie_chart.render(),
            status=200,
            headers=None,
            content_type="image/svg+xml")
Exemplo n.º 27
0
def AuthFailed(request):
    return HTTPResponse(
        json_dumps({
            "error_code": 1005,
            "message": "authorization failed",
            "request": request.method + " " + request.path
        }),
        headers=None,
        status=401,  #禁止访问
        content_type="application/json",
    )
Exemplo n.º 28
0
def AuthFailed2(request, error_code, message):
    return HTTPResponse(
        json_dumps({
            "error_code": error_code,
            "message": message,
            "request": request.method + " " + request.path
        }),
        headers=None,
        status=401,
        content_type="application/json",
    )
Exemplo n.º 29
0
 def output_json_fast_orjson(request, data, code, headers=None):
     current_app = request.app
     if current_app.debug:
         return output_json_pretty(request, data, code, headers=headers)
     settings = current_app.config.get('RESTPLUS_JSON', {})
     dumped = fast_dumps(
         data, option=orjson_opts, default=orjson_default, **
         settings) + b"\n"
     if use_body_bytes:
         resp = HTTPResponse(None,
                             code,
                             headers,
                             content_type='application/json',
                             body_bytes=dumped)
     else:
         resp = HTTPResponse(dumped,
                             code,
                             headers,
                             content_type='application/json')
     return resp
Exemplo n.º 30
0
    async def inner(*args, **kwargs):
        result = func(*args, **kwargs)
        if result is None or isinstance(result, HTTPResponse):
            return result

        if isawaitable(result):
            result = await result

        return HTTPResponse(json.dumps(result),
                            content_type="application/json",
                            status=200)