当前位置: 首页>>代码示例>>Python>>正文


Python flask.send_file方法代码示例

本文整理汇总了Python中flask.send_file方法的典型用法代码示例。如果您正苦于以下问题:Python flask.send_file方法的具体用法?Python flask.send_file怎么用?Python flask.send_file使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在flask的用法示例。


在下文中一共展示了flask.send_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: jobs_download

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def jobs_download(job_id):
    # FIXME may crash if no crashes available
    if job_id is None:
        flask.flash("Invalid job ID")
        return flask.redirect('/jobs/show')

    job = Job.objects.get(id=job_id)
    if not can_do_stuff_with_job(current_user, job.owner):
        flask.flash('User is not allowed to download job.')
        return flask.redirect('/jobs/show')

    job_crashes = Crash.objects(job_id=job_id)
    if job_crashes:
        imz = InMemoryZip()
        summary = {}
        for c in job_crashes:
            summary[str(c.id)] = _get_summary_for_crash(c)
            imz.append("%s" % str(c.id), c.test_case)
        imz.append("summary.json", json.dumps(summary, indent=4))

        filename = os.path.join('/tmp', '%s.zip' % job_id)
        if os.path.exists(filename):
            os.remove(filename)
        imz.writetofile(filename)
        return flask.send_file(filename, as_attachment=True) 
开发者ID:fkie-cad,项目名称:LuckyCAT,代码行数:27,代码来源:Jobs.py

示例2: audit_work_rollback

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def audit_work_rollback(id):
    """
    Roll back sql.
    :param id:
    :return:
    """
    sql_roll = get_sql_roll(id)
    base_dir = os.path.dirname(__file__)
    roll_back_dir = base_dir + '/tmp'

    if not os.path.exists(roll_back_dir):
        os.makedirs(roll_back_dir)
    fp = open(roll_back_dir + '/roll_back.sql', 'w')

    for i in range(len(sql_roll)):
        fp.write(sql_roll[i] + '\n')
    fp.close()

    response = make_response(send_file(roll_back_dir + '/roll_back.sql'))
    response.headers['Content-Disposition'] = "attachment; filename=ex.sql"

    return response 
开发者ID:Tianny,项目名称:incepiton-mysql,代码行数:24,代码来源:views.py

示例3: download_message_media

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def download_message_media(msg_id):
    """Download a media file"""
    message = g.driver.get_message_by_id(msg_id)

    if not message or not message.mime:
        abort(404)

    profile_path = create_static_profile_path(g.client_id)
    filename = message.save_media(profile_path, True)

    if os.path.exists(filename):
        return send_file(filename, mimetype=message.mime)

    abort(404)


# --------------------------- Admin methods ---------------------------------- 
开发者ID:mukulhase,项目名称:WebWhatsapp-Wrapper,代码行数:19,代码来源:webapi.py

示例4: redirect_file

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def redirect_file(user,fileid):
    filename=GetName(fileid)
    downloadUrl,play_url=GetDownloadUrl(fileid,user)
    req = browser.get(play_url, stream = True)
    headers = dict([(name, value) for (name, value) in req.raw.headers.items()])
    cache_root=os.path.join(GetConfig('config_dir'),'cache')
    if not os.path.exists(cache_root):
        os.mkdir(cache_root)
    filepath=os.path.join(cache_root,filename)
    if not os.path.exists(filepath):
        with open(filepath,'wb') as f:
            for chunk in req.iter_content(1024):
                if chunk:
                    f.write(chunk)
                    f.flush()
    resp=send_file(filepath,conditional=True)
    return resp 
开发者ID:abbeyokgo,项目名称:PyOne,代码行数:19,代码来源:views.py

示例5: ebook_file_content

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def ebook_file_content(fpath=None):
	if fpath is None:
		fpath = ""

	fpath = os.path.join(settings.EBOOK_STORAGE_DIR, fpath)
	fpath = os.path.abspath(fpath)
	assert fpath.startswith(settings.EBOOK_STORAGE_DIR)

	print("Fpath request:", fpath)

	if not os.path.exists(fpath):
		return render_ebook_error(fpath)

	if os.path.isfile(fpath):
		return send_file(fpath)

	else:
		return render_ebook_error(fpath) 
开发者ID:fake-name,项目名称:ReadableWebProxy,代码行数:20,代码来源:ebook_view.py

示例6: download

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def download(hash_id):
    paste = Paste.objects.get_or_404(hash_id=hash_id)
    str = StringIO.StringIO()
    zf = zipfile.ZipFile(str, "w", zipfile.ZIP_DEFLATED, False)

    for i, code in enumerate(paste.codes):
        zf.writestr("code-%s.txt" % i, code.content.encode('utf-8'))

    for f in zf.filelist:
        f.create_system = 0

    zf.close()

    str.seek(0)

    return send_file(str,
                     mimetype="application/octet-stream",
                     as_attachment=True,
                     attachment_filename="%s.zip" % hash_id) 
开发者ID:DoubleCiti,项目名称:daimaduan.com,代码行数:21,代码来源:pastes.py

示例7: get

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def get(self, attachment_file_id):
        attachment_file = comments_service.get_attachment_file(
            attachment_file_id
        )
        comment = tasks_service.get_comment(attachment_file["comment_id"])
        task = tasks_service.get_task(comment["object_id"])
        user_service.check_project_access(task["project_id"])
        user_service.check_entity_access(task["entity_id"])
        file_path = comments_service.get_attachment_file_path(attachment_file)
        try:
            return flask_send_file(
                file_path,
                conditional=True,
                mimetype=attachment_file["mimetype"],
                as_attachment=False,
                attachment_filename=attachment_file["name"],
            )
        except:
            abort(404) 
开发者ID:cgwire,项目名称:zou,代码行数:21,代码来源:resources.py

示例8: xlsx

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def xlsx():
    '''Returns an xlsx file containing the entire dataset for the current
    workspace.'''
    sfp = BytesIO()
    with xlsxwriter.Workbook(sfp) as workbook:
        # create a worksheet for each table in the current workspace
        for table in recon.get_tables():
            rows = recon.query(f"SELECT * FROM {table}", include_header=True)
            columns = rows.pop(0)
            rows = columnize(columns, rows)
            add_worksheet(workbook, table, rows)
    sfp.seek(0)
    return send_file(
        sfp,
        mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        as_attachment=True,
        attachment_filename=f"{current_app.config['WORKSPACE']}.xlsx"
    ) 
开发者ID:lanmaster53,项目名称:recon-ng,代码行数:20,代码来源:reports.py

示例9: font_file

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def font_file():
    file_name = request.args.get("file")

    if file_name:
        if file_name in FONT_FILES:
            with open(file_name, 'rb') as bites:
                response = make_response(send_file(
                    io.BytesIO(bites.read()),
                    attachment_filename=os.path.basename(file_name),
                    mimetype='application/octet-stream'
                ))

                if request.referrer:
                    response.headers['Access-Control-Allow-Origin'] = \
                        request.referrer[:-1] if request.referrer.endswith("/") else \
                        request.referrer[:-1]

                response.headers['Content-Type'] = 'application/json'

                return response

    return ('', 404) 
开发者ID:tryvin,项目名称:figma-linux-font-helper,代码行数:24,代码来源:server.py

示例10: make_thumbnail

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def make_thumbnail(img, level):
	if level > len(ALLOWED_RESOLUTIONS) or level <= 0:
		abort(403)

	w, h = ALLOWED_RESOLUTIONS[level - 1]

	upload_dir = current_app.config["UPLOAD_DIR"]
	thumbnail_dir = current_app.config["THUMBNAIL_DIR"]
	mkdir(thumbnail_dir)

	output_dir = os.path.join(thumbnail_dir, str(level))
	mkdir(output_dir)

	cache_filepath  = os.path.join(output_dir, img)
	source_filepath = os.path.join(upload_dir, img)

	resize_and_crop(source_filepath, cache_filepath, (w, h))
	return send_file(cache_filepath) 
开发者ID:minetest,项目名称:contentdb,代码行数:20,代码来源:__init__.py

示例11: qr_code

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def qr_code(path):
    if os.environ.get('WIFIONLY'):
        return ''

    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(short_base+path)
    qr.make(fit=True)
    img = io.BytesIO()
    qr.make_image().save(img, 'PNG')
    img.seek(0)
    return send_file(img, mimetype='image/png') 
开发者ID:c3nav,项目名称:c3nav-32c3,代码行数:18,代码来源:main.py

示例12: get

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def get(self, job_id):
        con = sqlite3.connect(os.path.dirname(os.path.abspath(__file__)) + '/assets.db')
        con.row_factory = sqlite3.Row
        cur = con.cursor()

        cur.execute("SELECT zip_file FROM tool_jobs WHERE id = ?",(job_id,))
        data = dict(result=[dict(r) for r in cur.fetchall()])
        zip_file = data['result'][0]['zip_file'] + '.zip'

        # Close connection
        if con:
            con.close()

        return send_file(zip_file, as_attachment=True)

# Retrieve dependencies for tool 
开发者ID:rascal999,项目名称:torc,代码行数:18,代码来源:__init__.py

示例13: get_pdf_for_notification

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def get_pdf_for_notification(notification_id):
    _data = {"notification_id": notification_id}
    validate(_data, notification_by_id)
    notification = notifications_dao.get_notification_by_id(
        notification_id, authenticated_service.id, _raise=True
    )

    if notification.notification_type != LETTER_TYPE:
        raise BadRequestError(message="Notification is not a letter")

    if notification.status == NOTIFICATION_VIRUS_SCAN_FAILED:
        raise BadRequestError(message='File did not pass the virus scan')

    if notification.status == NOTIFICATION_TECHNICAL_FAILURE:
        raise BadRequestError(message='PDF not available for letters in status {}'.format(notification.status))

    if notification.status == NOTIFICATION_PENDING_VIRUS_CHECK:
        raise PDFNotReadyError()

    try:
        pdf_data, metadata = get_letter_pdf_and_metadata(notification)
    except Exception:
        raise PDFNotReadyError()

    return send_file(filename_or_fp=BytesIO(pdf_data), mimetype='application/pdf') 
开发者ID:alphagov,项目名称:notifications-api,代码行数:27,代码来源:get_notifications.py

示例14: bindiff_export

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def bindiff_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output = os.path.join(directory, "output.BinExport")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport", output)
            logger.info("Command completed successfully")
            return send_file(open(output, "rb"), as_attachment = True, attachment_filename = "%s.BinExport" % filename, mimetype = "application/binary")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
            
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:38,代码来源:ida_service.py

示例15: bindiff_pickle_export

# 需要导入模块: import flask [as 别名]
# 或者: from flask import send_file [as 别名]
def bindiff_pickle_export():
    """
    Run the IDA Pro autoanalysis on the input file and export a BinExport database.
    :param input: The input file
    :return: Status code 200 and a JSON object containing the output database
        name in key 'output', or status code 422 on invalid parameters, 408 on
        timeout or 500 on other errors.
    """
    logger.info("bindiff_pickle_export called")

    directory = None
    try:
        directory = tempfile.mkdtemp()
        if len(request.files) != 1:
            return make_response(jsonify(error = "Missing file parameter"), 422)

        filename, file_ = request.files.items()[0]
        input_ = os.path.join(directory, sanitize_filename(filename))
        file_.save(input_)

        output_binexport = os.path.join(directory, "output.BinExport")
        output_pickle = os.path.join(directory, "output.pickle")

        timeout = request.form.get('timeout', None)
        is_64_bit = request.form.get('is_64_bit', True)
        try:
            run_ida(input_, is_64_bit, timeout, os.path.join(PREFIX, "export_binexport_pickle.py"), "binexport_pickle", output_binexport, output_pickle)
            logger.info("Command completed successfully")
            output_tar = os.path.join(directory, "output.tar.gz")
            subprocess.check_call(["tar", "czf", output_tar, os.path.relpath(output_binexport, directory), os.path.relpath(output_pickle, directory)], cwd = directory)
            return send_file(open(output_tar, "rb"), as_attachment = True, attachment_filename = "%s.tar.gz" % filename, mimetype = "application/gzip")
        except TimeoutError:
            return jsonify(error = "Program execution timed out"), 408
        except OSError as err:
            return jsonify(error = "Program execution failed with error %d" % err.errno), 500
    finally:
        if directory is not None:
            shutil.rmtree(directory) 
开发者ID:Cisco-Talos,项目名称:BASS,代码行数:40,代码来源:ida_service.py


注:本文中的flask.send_file方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。