How to use the sanic.response.file 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 rmorshea / idom / src / py / idom / server / simple.py View on Github external
async def client(self, request: request.Request, path: str):
        return await response.file(
            os.path.join(STATIC, "simple-client", *path.split("\n"))
        )
github RasaHQ / rasa / rasa / server.py View on Github external
if "domain" in rjs:
            domain_path = os.path.join(temp_dir, "domain.yml")
            dump_obj_as_str_to_file(domain_path, rjs["domain"])

        try:
            model_path = await train_async(
                domain=domain_path,
                config=config_path,
                training_files=temp_dir,
                output_path=rjs.get("out", DEFAULT_MODELS_PATH),
                force_training=rjs.get("force", False),
            )

            filename = os.path.basename(model_path) if model_path else None

            return await response.file(
                model_path, filename=filename, headers={"filename": filename}
            )
        except InvalidDomain as e:
            raise ErrorResponse(
                400,
                "InvalidDomainError",
                "Provided domain file is invalid. Error: {}".format(e),
            )
        except Exception as e:
            logger.debug(traceback.format_exc())
            raise ErrorResponse(
                500,
                "TrainingError",
                "An unexpected error occurred during training. Error: {}".format(e),
            )
github its-a-feature / Apfell / apfell-docker / app / api / command_api.py View on Github external
async def get_command_code(request, user, id, resp_type):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    resp_type = unquote_plus(resp_type)
    try:
        query = await db_model.command_query()
        command = await db_objects.get(query, id=id)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to get command'})
    if command.payload_type.external:
        return text("")
    try:
        if resp_type == "file":
            return file("./app/payloads/{}/commands/{}".format(command.payload_type.ptype, command.cmd))
        else:
            rsp_file = open("./app/payloads/{}/commands/{}".format(command.payload_type.ptype, command.cmd), 'rb').read()
            encoded = base64.b64encode(rsp_file).decode("UTF-8")
            return text(encoded)
    except Exception as e:
        print(e)
        return text("")
github EvanPurkhiser / tune-manager / tune_manager / api / catalog.py View on Github external
async def statics(request, key):
    return await response.file(
        os.path.join(request.app.config.ARTWORK_PATH, key[0:2], key)
    )
github its-a-feature / Apfell / apfell-docker / app / api / reporting_api.py View on Github external
async def get_full_timeline_api(request, user):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    try:
        return await file("./app/files/{}/full_timeline.pdf".format(user['current_operation']), filename="full_timeline.pdf")
    except Exception as e:
        print(str(sys.exc_info()[-1].tb_lineno) + " " + str(e))
        return json({'status': 'error', 'error': str(e)})
github Oslandia / postile / postile / postile.py View on Github external
async def get_jsonstyle(request):
    if not Config.style:
        return response.text('no style available', status=404)

    return await response.file(
        Config.style,
        headers={"Content-Type": "application/json"}
    )
github huge-success / sanic / examples / run_asgi.py View on Github external
async def handler_file(request):
    return await response.file(Path("../") / "setup.py")
github its-a-feature / Apfell / apfell-docker / app / api / payloadtype_api.py View on Github external
async def download_file_for_payloadtype(request, ptype, user):
    if user['auth'] not in ['access_token', 'apitoken']:
        abort(status_code=403, message="Cannot access via Cookies. Use CLI or access via JS in browser")
    payload_type = unquote_plus(ptype)
    try:
        query = await db_model.payloadtype_query()
        payloadtype = await db_objects.get(query, ptype=payload_type)
    except Exception as e:
        print(e)
        return json({'status': 'error', 'error': 'failed to find payload type'})
    try:
        data = dict(folder=request.raw_args['folder'], file=request.raw_args['file'])
        path = os.path.abspath("/app/payloads/{}/payload/".format(payload_type))
        attempted_path = os.path.abspath(data['folder'] + "/" + data['file'])
        if path in attempted_path:
            return await file(attempted_path, filename=data['file'])
        return json({'status': 'success', 'folder': data['folder'], 'file': data['file']})
    except Exception as e:
        return json({'status': 'error', 'error': 'failed finding the file: ' + str(e)})
github RasaHQ / rasa / rasa / core / training / interactive.py View on Github external
    @app.route(VISUALIZATION_TEMPLATE_PATH, methods=["GET"])
    def visualisation_html(request):
        return response.file(visualization.visualization_html_path())
github omarryhan / pyfy / examples / oauth2_async.py View on Github external
return json(dict(error=request.args.get("error_description")))
    elif request.args.get("code"):
        grant = request.args.get("code")
        callback_state = request.args.get("state")
        if callback_state != state:
            abort(401)
        try:
            user_creds = await spt.build_user_creds(grant=grant)
            async with aiofiles.open(os.getcwd() + "SPOTIFY_CREDS.json", "w") as file:
                await file.write(stdlib_json.dumps(user_creds.__dict__))
        except AuthError as e:
            return json(dict(error_description=e.msg, error_code=e.code), e.code)
        else:
            await spt.populate_user_creds()
            print(os.getcwd())
            return await response.file(os.getcwd() + "SPOTIFY_CREDS.json")
            # return response.json(dict(user_creds=user_creds.__dict__, check_if_active=app.url_for('is_active', _scheme='http', _external=True, _server=local_full_address)), 200)
    else:
        return response.text("Something is wrong with your callback")