How to use the sanic.response.json function in sanic

To help you get started, we’ve selected a few sanic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github huge-success / sanic / tests / test_blueprints.py View on Github external
def get_resource_hander(request, resource_id):
        resource = {"resource_id": resource_id}
        return json(resource)
github icon-project / loopchain / loopchain / rest_server / rest_server.py View on Github external
logging.debug(f"query result : {grpc_response}")
                    query_data['response_code'] = str(grpc_response.response_code)
                    try:
                        query_data['response'] = json.loads(grpc_response.response)

                    except json.JSONDecodeError as e:
                        logging.warning("your response is not json, your response(" + str(grpc_response.response) + ")")
                        query_data['response'] = grpc_response.response

            except _Rendezvous as e:
                logging.error(f'Execute Query Error : {e}')
                if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
                    logging.debug("gRPC timeout !!!")
                    query_data['response_code'] = str(message_code.Response.timeout_exceed)

        return response.json(query_data)
github etalab / sirene / ulysse / server.py View on Github external
def format_response(rows, format, column_names):
    """Given a `format`, serialize and return the appropriated data."""
    if format == 'json':
        return json(rows)
    elif format == 'csv':
        headers = ';'.join(column_names) + '\n'
        rows = [dict_to_csv(row, column_names) for row in rows]
        return text(headers + '\n'.join(rows))
github baojiweicn / susnote / app / server.py View on Github external
async def cros(request):
    if session_interface:
        await session_interface.open(request)
    if request.method == 'OPTIONS':
        headers = {'Access-Control-Allow-Origin': '*',
                   'Access-Control-Allow-Headers': 'Content-Type',
                   'Access-Control-Allow-Method': 'POST, PUT, DELETE'}
        return json({'message': 'Hello World'}, headers=headers)
github jrmi / byemail / byemail / httpserver.py View on Github external
async def contacts_search(request, user_id, account):

        if account.name != user_id:
            raise Forbidden("You can't consult another person account.")

        text = request.args.get("text", "")

        if not text:
            return json([])

        results = await storage.contacts_search(account, text)

        return json(results)
github Jupyter-Kale / kale / kale / services / manager.py View on Github external
def find_worker(request, wid):
    worker = ws.find(wid)
    if worker is None:
        return sanic.response.json(body=[{"error": "{} not found".format(wid)}], status=404)
    data = {
        "id": worker[0],
        "protocol": worker[1],
        "host": worker[2],
        "port": worker[3]
        }
    return sanic.response.json(data)
github sourcepirate / devmap / app / roadmap / blueprints / mapblueprint.py View on Github external
def remove_child(request, _id, _node):
    """remove child to the existing tree"""
    dct = RoadMap.get_map(_id)
    if not dct:
        return response.json({"Error": "Not Found"}, status=404)
    dct.delete(_node)
    dct.put()
    return response.json(dct.to_dict(), status=200)
github simonw / json-head / json_head.py View on Github external
async def handle_request(request):
    urls = request.args.getlist('url')
    callback = request.args.get('callback')
    if urls:
        if len(urls) > 10:
            return response.json([{
                'ok': False,
                'error': 'Max 10 URLs allowed'
            }], status=400)
        async with aiohttp.ClientSession() as session:
            head_infos = await asyncio.gather(*[
                head(session, url) for url in urls
            ])
            if callback and is_valid_callback(callback):
                return response.text(
                    '{}({})'.format(callback, json.dumps(head_infos, indent=2)),
                    content_type='application/javascript',
                    headers={'Access-Control-Allow-Origin': '*'},
                )
            else:
                return response.json(
                    head_infos,
github botfront / rasa-for-botfront / rasa / server.py View on Github external
)

        nlu_data = rasa.utils.io.create_temporary_file(request.body, mode="w+b")
        data_path = os.path.abspath(nlu_data)

        if not os.path.exists(eval_agent.model_directory):
            raise ErrorResponse(409, "Conflict", "Loaded model file not found.")

        model_directory = eval_agent.model_directory
        model_directory = os.path.abspath(model_directory) # bf
        _, nlu_model = model.get_model_subdirectories(model_directory)

        try:
            language = request.args.get("language", None) # bf
            evaluation = run_evaluation(data_path, nlu_model.get(language)) #bf
            return response.json(evaluation)
        except Exception as e:
            logger.debug(traceback.format_exc())
            raise ErrorResponse(
                500,
                "TestingError",
                f"An unexpected error occurred during evaluation. Error: {e}",
            )