Python starlette.responses.JSONResponse() Examples

The following are 30 code examples of starlette.responses.JSONResponse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module starlette.responses , or try the search function .
Example #1
Source File: _endpoints.py    From tartiflette-asgi with MIT License 7 votes vote down vote up
def _get_response(self, request: Request, data: QueryParams) -> Response:
        try:
            query = data["query"]
        except KeyError:
            return PlainTextResponse("No GraphQL query found in the request", 400)

        config = get_graphql_config(request)
        background = BackgroundTasks()
        context = {"req": request, "background": background, **config.context}

        engine: Engine = config.engine
        result: dict = await engine.execute(
            query,
            context=context,
            variables=data.get("variables"),
            operation_name=data.get("operationName"),
        )

        content = {"data": result["data"]}
        has_errors = "errors" in result
        if has_errors:
            content["errors"] = format_errors(result["errors"])
        status = 400 if has_errors else 200

        return JSONResponse(content=content, status_code=status, background=background) 
Example #2
Source File: app.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("fetch-counter", request, tracer) as span:
        with outgoing_trace("next-count", request, tracer, span) as out:
            outgoing_span, ougoing_headers = out

            counter_breaker = CircuitBreaker(
                fail_max=3, timeout_duration=timedelta(seconds=30))
            counter = await counter_breaker.call_async(
                requests.get, 'http://service2:8000/', timeout=1,
                headers=ougoing_headers)
            data = counter.json()

            count = data['last']
            app.counter_gauge.set({"path": request.url.path}, count)

            return JSONResponse({
                'svc': 'service1',
                'version': '3',
                'timestamp': time.time(),
                'count': count
            }) 
Example #3
Source File: _endpoints.py    From tartiflette-asgi with MIT License 6 votes vote down vote up
def post(self, request: Request) -> Response:
        content_type = request.headers.get("Content-Type", "")

        if "application/json" in content_type:
            try:
                data = await request.json()
            except json.JSONDecodeError:
                return JSONResponse({"error": "Invalid JSON."}, 400)
        elif "application/graphql" in content_type:
            body = await request.body()
            data = {"query": body.decode()}
        elif "query" in request.query_params:
            data = request.query_params
        else:
            return PlainTextResponse("Unsupported Media Type", 415)

        return await self._get_response(request, data=data) 
Example #4
Source File: server.py    From fastai-serving with MIT License 6 votes vote down vote up
def analyze(request):
    data = await request.body()
    instances = json.loads(data.decode('utf-8'))['instances']

    # convert from image bytes to images to tensors
    img_bytes = [b64decode(inst['image_bytes']['b64']) for inst in instances]
    tensors = [pil2tensor(Image.open(BytesIO(byts)), dtype=np.float32).div_(255) for byts in img_bytes]
    tfm_tensors = [learner.data.valid_dl.tfms[0]((tensor, torch.zeros(0)))[0] for tensor in tensors]

    # batch predict, dummy labels for the second argument
    dummy_labels = torch.zeros(len(tfm_tensors))
    tensor_stack = torch.stack(tfm_tensors)
    if torch.cuda.is_available():
        tensor_stack = tensor_stack.cuda()
    pred_tensor = learner.pred_batch(batch=(tensor_stack, dummy_labels))

    # find the maximum value along the prediction axis
    classes = np.argmax(np.array(pred_tensor), axis=1)
    return JSONResponse(dict(predictions=classes.tolist())) 
Example #5
Source File: web.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
def simulator(request: requests.Request):
    token = request.headers.get("Authorization")
    if token:
        token = token[6:]  # Drop 'token '

    data = SimulatorSchema(await request.json())
    if data["pull_request"]:
        loop = asyncio.get_running_loop()
        title, summary = await loop.run_in_executor(
            None,
            functools.partial(
                _sync_simulator,
                data["mergify.yml"]["pull_request_rules"],
                *data["pull_request"],
                token=token,
            ),
        )
    else:
        title, summary = ("The configuration is valid", None)

    return responses.JSONResponse(
        status_code=200, content={"title": title, "summary": summary}
    ) 
Example #6
Source File: asgi.py    From ariadne with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def graphql_http_server(self, request: Request) -> Response:
        try:
            data = await self.extract_data_from_request(request)
        except HttpError as error:
            return PlainTextResponse(error.message or error.status, status_code=400)

        context_value = await self.get_context_for_request(request)
        extensions = await self.get_extensions_for_request(request, context_value)
        middleware = await self.get_middleware_for_request(request, context_value)

        success, response = await graphql(
            self.schema,
            data,
            context_value=context_value,
            root_value=self.root_value,
            validation_rules=self.validation_rules,
            debug=self.debug,
            introspection=self.introspection,
            logger=self.logger,
            error_formatter=self.error_formatter,
            extensions=extensions,
            middleware=middleware,
        )
        status_code = 200 if success else 400
        return JSONResponse(response, status_code=status_code) 
Example #7
Source File: app.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("fetch-counter", request, tracer) as span:
        with outgoing_trace("next-count", request, tracer, span) as out:
            outgoing_span, ougoing_headers = out

            counter = await requests.get(
                'http://service2:8000/', headers=ougoing_headers, timeout=1)
            data = counter.json()

            count = data['last']
            app.counter_gauge.set({"path": request.url.path}, count)

            return JSONResponse({
                'svc': 'service1',
                'version': '2',
                'timestamp': time.time(),
                'count': count
            }) 
Example #8
Source File: starlette_plugin.py    From spectree with Apache License 2.0 6 votes vote down vote up
def register_route(self, app):
        self.app = app
        from starlette.responses import JSONResponse, HTMLResponse

        self.app.add_route(
            self.config.spec_url,
            lambda request: JSONResponse(self.spectree.spec),
        )

        for ui in PAGES:
            self.app.add_route(
                f'/{self.config.PATH}/{ui}',
                lambda request, ui=ui: HTMLResponse(
                    PAGES[ui].format(self.config.spec_url)
                ),
            ) 
Example #9
Source File: starlette_demo.py    From spectree with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        """
        health check
        """
        return JSONResponse({'msg': 'pong'}) 
Example #10
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("next-count", request, tracer) as span:
        await asyncio.sleep(2)

        return JSONResponse({
            'svc': 'service2',
            'version': '4',
            'last': next(counter)
        }) 
Example #11
Source File: server.py    From Malaria-Detection-using-Keras with MIT License 5 votes vote down vote up
def analyze(request):
    data = await request.form()
    img_bytes = await (data['file'].read())
    img = plt.imread(BytesIO(img_bytes))
    img = np.array(img)
    img = resize(img, (64, 64, 3))

    img = img[None, ...]
    inp = graph.get_tensor_by_name('input_1_1:0')
    out = graph.get_tensor_by_name('fc2_1/Softmax:0')

    with tf.Session(graph=graph) as sess:
        pred = sess.run([out], feed_dict={inp: img})
    return JSONResponse({'result': str(classes[np.argmax(pred[0][0])])}) 
Example #12
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("fetch-counter", request, tracer) as span:
        count = next(counter)
        app.counter_gauge.set({"path": request.url.path}, count)

        return JSONResponse({
            'svc': 'service1',
            'version': '1',
            'timestamp': time.time(),
            'count': count
        }) 
Example #13
Source File: server.py    From fastai-serving with MIT License 5 votes vote down vote up
def status(request):
    return JSONResponse(dict(status='OK')) 
Example #14
Source File: main.py    From local-data-api with MIT License 5 votes vote down vote up
def data_api_exception_handler(_: Request, exc: DataAPIException) -> JSONResponse:
    return JSONResponse(
        status_code=exc.status_code, content={"message": exc.message, "code": exc.code}
    ) 
Example #15
Source File: app.py    From starlette-jwt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def homepage(request):
    return JSONResponse({'hello': 'world'}) 
Example #16
Source File: app.py    From starlette-jwt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def homepage(request):
    return JSONResponse({'hello': request.session['username']}) 
Example #17
Source File: test_middleware.py    From starlette-jwt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def with_auth(request):
    return JSONResponse({'auth': {"username": request.user.display_name}}) 
Example #18
Source File: test_middleware.py    From starlette-jwt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def without_auth(request):
    return JSONResponse({'auth': None}) 
Example #19
Source File: main.py    From uvicorn-gunicorn-starlette-docker with MIT License 5 votes vote down vote up
def homepage(request):
    message = f"Hello world! From Starlette running on Uvicorn with Gunicorn. Using Python {version}"
    return JSONResponse({"message": message}) 
Example #20
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("next-count", request, tracer) as span:
        return JSONResponse({
            'svc': 'service2',
            'version': '2',
            'last': next(counter)
        }) 
Example #21
Source File: main.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def message(request):
    message = f"Hello world! From Starlette running on Uvicorn with Gunicorn in Alpine."
    return JSONResponse({"message": message, "version": version}) 
Example #22
Source File: main.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def mydatetime(request):
    print(datetime.datetime.now())
    return JSONResponse({'hello': 'world', 'now': str(datetime.datetime.now())}) 
Example #23
Source File: app.py    From community-playground with Apache License 2.0 5 votes vote down vote up
def index(request: Request) -> JSONResponse:
    with incoming_trace("next-count", request, tracer) as span:
        return JSONResponse({
            'svc': 'service2',
            'version': '1',
            'last': next(counter)
        }) 
Example #24
Source File: validation_error.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def http422_error_handler(
    _: Request, exc: Union[RequestValidationError, ValidationError],
) -> JSONResponse:
    return JSONResponse(
        {"errors": exc.errors()}, status_code=HTTP_422_UNPROCESSABLE_ENTITY,
    ) 
Example #25
Source File: starlette_demo.py    From spectree with Apache License 2.0 5 votes vote down vote up
def predict(request):
    """
    async api

    descriptions about this function
    """
    print(request.path_params)
    print(request.context)
    return JSONResponse({'label': 5, 'score': 0.5}) 
Example #26
Source File: test_plugin_starlette.py    From spectree with Apache License 2.0 5 votes vote down vote up
def get(self, request):
        """summary
        description"""
        return JSONResponse({'msg': 'pong'}) 
Example #27
Source File: test_plugin_starlette.py    From spectree with Apache License 2.0 5 votes vote down vote up
def user_score(request):
    score = [randint(0, request.context.json.limit) for _ in range(5)]
    score.sort(reverse=request.context.query.order)
    assert request.context.cookies.pub == 'abcdefg'
    assert request.cookies['pub'] == 'abcdefg'
    return JSONResponse({
        'name': request.context.json.name,
        'score': score
    }) 
Example #28
Source File: serve.py    From ludwig with Apache License 2.0 5 votes vote down vote up
def server(model):
    app = FastAPI()

    input_features = {
        f['name'] for f in model.model_definition['input_features']
    }

    @app.get('/')
    def check_health():
        return JSONResponse({"message": "Ludwig server is up"})

    @app.post('/predict')
    async def predict(request: Request):
        form = await request.form()
        files, entry = convert_input(form)

        try:
            if (entry.keys() & input_features) != input_features:
                return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
                                    status_code=400)
            try:
                resp = model.predict(data_dict=[entry]).to_dict('records')[0]
                return JSONResponse(resp)
            except Exception as e:
                logger.error("Error: {}".format(str(e)))
                return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
                                    status_code=500)
        finally:
            for f in files:
                os.remove(f.name)

    return app 
Example #29
Source File: exception_handlers.py    From fastapi with MIT License 5 votes vote down vote up
def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
    headers = getattr(exc, "headers", None)
    if headers:
        return JSONResponse(
            {"detail": exc.detail}, status_code=exc.status_code, headers=headers
        )
    else:
        return JSONResponse({"detail": exc.detail}, status_code=exc.status_code) 
Example #30
Source File: exception_handlers.py    From fastapi with MIT License 5 votes vote down vote up
def request_validation_exception_handler(
    request: Request, exc: RequestValidationError
) -> JSONResponse:
    return JSONResponse(
        status_code=HTTP_422_UNPROCESSABLE_ENTITY,
        content={"detail": jsonable_encoder(exc.errors())},
    )