Python flask.send_file() Examples

The following are 30 code examples of flask.send_file(). 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 flask , or try the search function .
Example #1
Source File: __init__.py    From torc with GNU Affero General Public License v3.0 8 votes vote down vote up
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 
Example #2
Source File: webapi.py    From WebWhatsapp-Wrapper with MIT License 7 votes vote down vote up
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 ---------------------------------- 
Example #3
Source File: __init__.py    From contentdb with GNU General Public License v3.0 7 votes vote down vote up
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) 
Example #4
Source File: main.py    From c3nav-32c3 with Apache License 2.0 7 votes vote down vote up
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') 
Example #5
Source File: views.py    From PyOne with Mozilla Public License 2.0 6 votes vote down vote up
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 
Example #6
Source File: server.py    From figma-linux-font-helper with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: Jobs.py    From LuckyCAT with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #8
Source File: views.py    From incepiton-mysql with MIT License 6 votes vote down vote up
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 
Example #9
Source File: pastes.py    From daimaduan.com with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #10
Source File: ebook_view.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #11
Source File: resources.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example #12
Source File: reports.py    From recon-ng with GNU General Public License v3.0 6 votes vote down vote up
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"
    ) 
Example #13
Source File: get_notifications.py    From notifications-api with MIT License 6 votes vote down vote up
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') 
Example #14
Source File: backends.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def internal(identifier, size):
    '''
    Internal provider

    Use pydenticon to generate an identicon.
    '''
    identicon = generate_pydenticon(identifier, size)
    response = send_file(io.BytesIO(identicon), mimetype='image/png')
    etag = hashlib.sha1(identicon).hexdigest()
    response.set_etag(etag)
    return response 
Example #15
Source File: model_app.py    From FATE with Apache License 2.0 5 votes vote down vote up
def operate_model(model_operation):
    request_config = request.json or request.form.to_dict()
    job_id = generate_job_id()
    required_arguments = ["model_id", "model_version"]
    if model_operation not in [ModelOperation.STORE, ModelOperation.RESTORE, ModelOperation.EXPORT, ModelOperation.IMPORT]:
        raise Exception('Can not support this operating now: {}'.format(model_operation))
    check_config(request_config, required_arguments=required_arguments)
    if model_operation in [ModelOperation.EXPORT, ModelOperation.IMPORT]:
        if model_operation == ModelOperation.IMPORT:
            file = request.files.get('file')
            file_path = os.path.join(TEMP_DIRECTORY, file.filename)
            try:
                os.makedirs(os.path.dirname(file_path), exist_ok=True)
                file.save(file_path)
            except Exception as e:
                shutil.rmtree(file_path)
                raise e
            request_config['file'] = file_path
            model = pipelined_model.PipelinedModel(model_id=request_config["model_id"], model_version=request_config["model_version"])
            model.unpack_model(file_path)
            return get_json_result()
        else:
            model = pipelined_model.PipelinedModel(model_id=request_config["model_id"], model_version=request_config["model_version"])
            archive_file_path = model.packaging_model()
            return send_file(archive_file_path, attachment_filename=os.path.basename(archive_file_path), as_attachment=True)
    else:
        data = {}
        job_dsl, job_runtime_conf = gen_model_operation_job_config(request_config, model_operation)
        job_id, job_dsl_path, job_runtime_conf_path, logs_directory, model_info, board_url = JobController.submit_job(
            {'job_dsl': job_dsl, 'job_runtime_conf': job_runtime_conf}, job_id=job_id)
        data.update({'job_dsl_path': job_dsl_path, 'job_runtime_conf_path': job_runtime_conf_path,
                     'board_url': board_url, 'logs_directory': logs_directory})
        return get_json_result(job_id=job_id, data=data) 
Example #16
Source File: routes.py    From LiSa with Apache License 2.0 5 votes vote down vote up
def download_json(id):
    """Download json report (serve file)."""
    json_file = f'{storage_path}/{id}/report.json'

    if not os.path.isfile(json_file):
        res = ErrorAPIResponse(1004).to_dict()
        return jsonify(res), 404

    return send_file(json_file, as_attachment=True) 
Example #17
Source File: routes.py    From LiSa with Apache License 2.0 5 votes vote down vote up
def download_pcap(id):
    """Get analysis pcap."""
    pcaps = glob.glob(f'{storage_path}/{id}/*.pcap')

    if len(pcaps) == 0:
        res = ErrorAPIResponse(1003).to_dict()
        return jsonify(res), 404

    return send_file(pcaps[0], as_attachment=True) 
Example #18
Source File: job_app.py    From FATE with Apache License 2.0 5 votes vote down vote up
def job_log():
    job_id = request.json.get('job_id', '')
    memory_file = io.BytesIO()
    tar = tarfile.open(fileobj=memory_file, mode='w:gz')
    job_log_dir = job_utils.get_job_log_directory(job_id=job_id)
    for root, dir, files in os.walk(job_log_dir):
        for file in files:
            full_path = os.path.join(root, file)
            rel_path = os.path.relpath(full_path, job_log_dir)
            tar.add(full_path, rel_path)
    tar.close()
    memory_file.seek(0)
    return send_file(memory_file, attachment_filename='job_{}_log.tar.gz'.format(job_id), as_attachment=True) 
Example #19
Source File: webapi.py    From WebWhatsapp-Wrapper with MIT License 5 votes vote down vote up
def get_screen():
    """Capture chrome screen image and send it back. If the screen is currently 
    at qr scanning phase, return the image of qr only, else return image of full
    screen"""
    img_title = "screen_" + g.client_id + ".png"
    image_path = STATIC_FILES_PATH + img_title
    if g.driver_status != WhatsAPIDriverStatus.LoggedIn:
        try:
            g.driver.get_qr(image_path)
            return send_file(image_path, mimetype="image/png")
        except Exception as err:
            pass
    g.driver.screenshot(image_path)
    return send_file(image_path, mimetype="image/png") 
Example #20
Source File: views.py    From openvpn-admin-ui with Apache License 2.0 5 votes vote down vote up
def process_error():
    url = current_app.config['SCHEDULER_ERROR'];
    if os.path.exists(url):
        respnse = make_response(send_file(url))
        respnse.headers["Content-Disposition"] = "attament; filename=scheduler.error"
        return respnse
    else:
        flash('Log file does not exist', 'danger')
        return render_template('status.html') 
Example #21
Source File: server.py    From rtkbase with GNU Affero General Public License v3.0 5 votes vote down vote up
def downloadLog(log_name):
    """ Route for downloading raw gnss data"""
    try:
        full_log_path = rtk.logm.log_path + "/" + log_name
        return send_file(full_log_path, as_attachment = True)
    except FileNotFoundError:
        abort(404) 
Example #22
Source File: routes.py    From LiSa with Apache License 2.0 5 votes vote down vote up
def get_report(id):
    """Get task report endpoint."""
    task = celery_app.AsyncResult(id)

    if task.state != 'SUCCESS':
        res = ErrorAPIResponse(1000).to_dict()
        return jsonify(res), 404

    return send_file(f'{storage_path}/{id}/report.json') 
Example #23
Source File: botlistapi.py    From BotListBot with MIT License 5 votes vote down vote up
def thumbnail(username):
    if username[0] != '@':
        username = '@' + username
    try:
        item = Bot.by_username(username)
    except Bot.DoesNotExist:
        item = None
    if not item:
        return _error("There is no bot in the BotList with the username {}.".format(username))
    if not os.path.exists(item.thumbnail_file):
        return _error("Sorry, we don't have a thumbnail for this bot.")

    return send_file(item.thumbnail_file, mimetype='image/jpeg') 
Example #24
Source File: app.py    From robotreviewer with GNU General Public License v3.0 5 votes vote down vote up
def get_pdf(report_uuid, pdf_uuid):
    # returns PDF binary from database by pdf_uuid
    # where the report_uuid also matches
    c = rr_sql_conn.cursor()
    c.execute("SELECT pdf_file FROM article WHERE report_uuid=? AND pdf_uuid=?", (report_uuid, pdf_uuid))
    pdf_file = c.fetchone()
    strIO = StringIO()
    strIO.write(pdf_file[0])
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename="%s.pdf" % pdf_uuid,
                     as_attachment=False) 
Example #25
Source File: app.py    From robotreviewer with GNU General Public License v3.0 5 votes vote down vote up
def download_report(report_uuid, format):
    report = produce_report(report_uuid, format, download=True)
    strIO = StringIO()
    strIO.write(report.encode('utf-8')) # need to send as a bytestring
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename="robotreviewer_report_%s.%s" % (report_uuid, format),
                     as_attachment=True) 
Example #26
Source File: honeyku.py    From honeyku with GNU General Public License v3.0 5 votes vote down vote up
def catch_all(path):
	# Load the config file
	config=load_config()
	# Honeytoken alerts
	if request.path in config['traps'] and request.path != "/favicon.ico":
		# Preparing the alert message
		alertMessage = alert_msg(request, config)
		# Slack alert
		if config['alert']['slack']['enabled'] == "true":
			WEBHOOK_URL = config['alert']['slack']['webhook-url']
			slack_alerter(alertMessage, WEBHOOK_URL)
		# Email alert
		if config['alert']['email']['enabled'] == "true":
			email_alerter(alertMessage, config)
		# SMS alert
		#TODO: Complete and test the SMS alert
		#if config['alert']['sms']['enabled'] == "true":
		#	sms_alerter(alertMessage, config)
		#TODO: HTTP Endpoint Support
	# Honeypot event logs
	if request.headers.getlist("X-Forwarded-For"):
		source_ip = request.headers.getlist("X-Forwarded-For")[0]
	else:
		source_ip = request.remote_addr
	logger.info('{{"sourceip":"{}","host":"{}","request":"{}","http_method":"{}","body":"{}","user_agent":"{}"}}'.format(
		source_ip, request.url_root, request.full_path, request.method, request.data, request.user_agent.string))
	# Prepare and send the custom HTTP response
	contype, body = generate_http_response(request, config)
	# Customize the response using a template (in case you want to return a dynamic response, etc.)
	# You can comment the next 2 lines if you don't want to use this. /Just an example/
	if body == "custom.html":
		return (render_template(body, browser = request.user_agent.browser, ua = request.user_agent.string))
	return (send_file(body, mimetype=contype) if "image" in contype else render_template(body)) 
Example #27
Source File: base.py    From gordo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self):
        """
        Responds with a serialized copy of the current model being served.

        Returns
        -------
        bytes
            Results from ``gordo.serializer.dumps()``
        """
        serialized_model = serializer.dumps(g.model)
        buff = io.BytesIO(serialized_model)
        return send_file(buff, attachment_filename="model.tar.gz") 
Example #28
Source File: app.py    From flyingcloud with Apache License 2.0 5 votes vote down vote up
def canny():
    # adapted from https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_canny/py_canny.html#canny
    img = cv2.imread('static/img/ship.jpg', 0)
    edges = cv2.Canny(img, 100, 200)
    im = Image.fromarray(edges)
    img2 = StringIO()
    im.save(img2, format="png")
    img2.seek(0)
    return send_file(img2, mimetype='image/png') 
Example #29
Source File: statusserver.py    From onion-expose with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_info(self, path):
        return send_file("infopage_status.html") 
Example #30
Source File: fileserver.py    From onion-expose with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_info(self, path):
        return send_file("infopage_file.html")