def file(path, name=None): """ Returns a file response :param path: str Path to the file :param name: str Name of the file which will be returned. If it is None the name is like the real file name. Default = None :return: :class:`werkzeug.wsgi.FileWrapper` """ if not os.path.isabs(path): caller_file = os.path.abspath( _utils.caller_frame().f_globals['__file__']) path = caller_file.replace(os.path.basename(caller_file), path) f = open(path, 'rb') if f: mime = mimetypes.guess_type(path)[0] size = os.path.getsize(path) filename = os.path.basename(path) if not name else name headers = { 'Content-Type': mime, 'Content-Disposition': 'attachment;filename=' + filename, 'Content-Length': size } return FileWrapper(f, 8192), 200, headers raise FileNotFoundError()
def file(uuid): dbo = current_app.attachment_dbo attachment = dbo.read_by_uuid(uuid) filename = attachment.filename filetype = attachment.filetype filetype = file_types[filetype] filename += "." + filetype file_binary = base64.b64decode(attachment.base64) file_data = io.BytesIO(file_binary) file_wrapper = FileWrapper(file_data) headers = { 'Content-Disposition': 'attachment; filename="{}"'.format(filename) } response = Response(file_wrapper, mimetype=mime_types[filetype], direct_passthrough=True, headers=headers) return response
def download_cpd_log(): """ Generates a csv file of all CPD events in-memory for download """ user_id = current_user.database_id username = get_name_by_user_id(user_id) today = datetime.date.today().strftime('%d-%m-%Y') out_data = format_query_for_csv() ### Write csv to temporary file temp = StringIO() csv.writer(temp).writerows(out_data) temp.seek(0) ### Convert to BytesIO for download b = BytesIO() b.write(temp.getvalue().encode()) b.seek(0) ### Create filename filename = f"{username} CPD Log {today}.csv" ### Add wrapper file_wrapper = FileWrapper(b) headers = {"Content-Disposition": f"attachment; filename={filename}"} response = Response(file_wrapper, mimetype='text/csv', direct_passthrough=True, headers=headers) #return send_file(b, attachment_filename=f"{username} CPD Log {today}.csv", as_attachment=True) return response
def buffer_on_disk(data_iter): tmp = tempfile.TemporaryFile(mode='w+', encoding='utf-8') for block in data_iter: tmp.write(block) tmp.flush() tmp.seek(0) return FileWrapper(tmp)
def export_excel(): timestamp = datetime.utcnow() with open('data.txt') as json_file: summary = json.load(json_file) output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() bold = workbook.add_format({'bold': 1}) worksheet.write('A1', 'Product', bold) worksheet.write('B1', 'Location', bold) worksheet.write('C1', 'Available Qty', bold) row = 1 for item in summary: if item['available_quantity'] == 0: continue worksheet.write(row, 0, item['product']) worksheet.write(row, 1, item['location']) worksheet.write(row, 2, item['available_quantity']) row += 1 workbook.close() output.seek(0) data = FileWrapper(output) return Response( data, mimetype= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", direct_passthrough=True)
def files_download(key): if request.method == "GET": """ key: encoded """ key = urllib.parse.unquote_plus(key) fs3viewer = FlaskS3Viewer.get_instance(g.BUCKET_NAMESPACE) obj = fs3viewer.find_one(key) if obj: try: key = os.path.basename(key).encode('latin-1') except UnicodeEncodeError: encoded_key = unicodedata.normalize('NFKD', key).encode( 'latin-1', 'ignore') filenames = { 'filename': encoded_key, 'filename*': "UTF-8''{}".format(url_quote(key)), } else: filenames = {'filename': key} rv = Response(FileWrapper(obj.get('Body')), direct_passthrough=True, mimetype=obj['ContentType']) rv.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' rv.headers['Pragma'] = 'no-cache' rv.headers['Expires'] = '0' rv.headers.set('Content-Disposition', 'attachment', **filenames) return rv else: return render_template( f'{fs3viewer.template_namespace}/error.html', FS3V_TEMPLATE_NAMESPACE=fs3viewer.template_namespace, FS3V_MESSAGE="Can't not found resource.", FS3V_CODE=404), 404
def send_bytes(bytes_io, mimetype): if FileWrapper is not None: return Response(FileWrapper(bytes_io), mimetype=mimetype, direct_passthrough=True) else: return flask.send_file(bytes_io, mimetype=mimetype)
def exp_variances(): img = explained_variance_chart() img_file = FileWrapper(img) return Response(img_file, mimetype='image/png', direct_passthrough=True, content_type='image/png')
def all_files(order_id): dbo = current_app.attachment_dbo attachments = dbo.read_by_order(order_id) zip_file = InMemoryZipFile() for attachment in attachments: filename = attachment.filename filetype = attachment.filetype filetype = file_types[filetype] filename += "." + filetype image_binary = base64.b64decode(attachment.base64) zip_file.write(filename, image_binary) file_data = zip_file.get_zip() file_wrapper = FileWrapper(file_data) headers = { 'Content-Disposition': 'attachment; filename="{}"'.format("bundle.zip") } response = Response(file_wrapper, mimetype="application/zip", direct_passthrough=True, headers=headers) return response
def download(): if request.method == "POST": dir_name = os.path.join(CONF.get('SERVER', 'files_dir'), hex(int(time.time()))[2:]) if request.form.get('img_height') and request.form.get('img_width'): img_size = (min(640, int(request.form.get('img_height'))), min(640, int(request.form.get('img_width')))) max_count = min(5000, int(request.form.get('max_count', 100))) else: img_size = None max_count = min(1000, int(request.form.get('max_count', 100))) tag = request.form.get('tag', 100) photos = Photos.query.filter(Photos.tag == tag)\ .order_by(Photos.update_time.desc())\ .limit(max_count).all() urls = [ph.url for ph in photos] downloader.main(urls, dir_name, img_size) zip_file = downloader.zipdir(dir_name) return_data = io.BytesIO() with open(zip_file, 'rb') as fo: return_data.write(fo.read()) return_data.seek(0) os.remove(zip_file) wrapped_data = FileWrapper(return_data) return Response(wrapped_data, mimetype="application/zip", direct_passthrough=True) else: tags = db.session.query( func.count(Photos.tag).label('count'), Photos.tag).group_by(Photos.tag).all() return render_template('download.html', tag_list=tags)
def text_mof(pdf_part, pdf_year, pdf_number, pdf_name): s3_url = "https://mgax-mof.s3.amazonaws.com" pdf_url = s3_url + "/" + pdf_name with temp_dir() as tmp: pdf_local_path = tmp / pdf_name text_path = tmp / 'plain.txt' with pdf_local_path.open('wb') as f: resp = requests.get(pdf_url, stream=True) assert resp.status_code == 200 for chunk in FileWrapper(resp.raw): f.write(chunk) subprocess.check_call(['pdftotext', pdf_local_path, text_path]) with text_path.open('r') as f: raw_text = f.read() json = dict([('part', int(pdf_part)), ('year', int(pdf_year)), ('number', int(pdf_number)), ('slug', pdf_name.split('.')[0]), ('text', raw_text)]) resp = requests.put(flask.current_app.config['ELASTIC_SEARCH_URL'] + pdf_name.split('.')[0], data=flask.json.dumps(json)) assert 200 <= resp.status_code < 300, repr(resp)
def index(): if request.method == 'POST': f = request.files.get('image_file') if not f and not allowed_file(f.filename): return redirect(url_for('index')) file_obj = BytesIO(f.read()) form = ASCIIGenerationForm(formdata=request.form) if form.validate_on_submit(): output = generate_image(file_obj, scaling_factor=form.scaling_factor.data, gradient=(form.from_color.data, form.to_color.data)) response = Response(FileWrapper(output), mimetype='image/png', direct_passthrough=True) response.headers['Content-Disposition'] = \ 'attachment; filename="ascii_art.png"' return response else: errors = form.errors return jsonify({'detail': errors, 'status': 400}), 400 else: form = ASCIIGenerationForm() return render_template('index.html', form=form)
def top_correlations(): img = top_correlations_chart() img_file = FileWrapper(img) return Response(img_file, mimetype='image/png', direct_passthrough=True, content_type='image/png')
def encode(): # validate form entry if not 'image' in request.files: return jsonify(message='No image key in the request files.'), 400 if not 'message' in request.form: return jsonify(message='No message key in the request form.'), 400 if len(request.form['message']) == 0: return jsonify(message='Message is empty.'), 400 if len(request.files['image'].filename) == 0: return jsonify(message='Empty file submitted.'), 400 # below we encrypt the message into the image, putting 'steg-py' # at the beginning for detection later try: image = core.dataToImage(core.evenOddEncryption( core.getImageData(request.files['image']), 'steg-py.' + request.form['message'])) except RuntimeError as e: return jsonify(message=str(e)), 400 img_io = BytesIO() image.save(img_io, 'PNG') img_io.seek(0) w = FileWrapper(img_io) return Response(w, mimetype="image/png", direct_passthrough=True)
def top_importances(): img = most_important_features_chart() img_file = FileWrapper(img) return Response(img_file, mimetype='image/png', direct_passthrough=True, content_type='image/png')
def vrc_time(): ip = request.headers['x-appengine-user-ip'] #ip = request.headers['X-Real-IP'] ctime = get_current_time(ip) img = generate_image(ctime) f = FileWrapper(img) return Response(f, mimetype="image/PNG", direct_passthrough=True)
def zipresults(): payload = dict(request.form) # return str(payload).replace(', ','\n') mem = io.BytesIO() with zipfile.ZipFile(mem, 'w') as zf: for k, filename in [ ('report', 'report.txt'), ('table_of_sessions_csv', 'csv/sessions.csv'), ('table_of_samples_csv', 'csv/samples.csv'), ('table_of_analyses_csv', 'csv/analyses.csv'), ]: data = zipfile.ZipInfo(f'/{filename}') data.date_time = time.localtime(time.time())[:6] data.compress_type = zipfile.ZIP_DEFLATED zf.writestr(data, payload[k]) txt = payload['csv_of_sessions'] txt = [[x.strip() for x in l.split(',')] for l in txt.splitlines() if l.strip()] sessions = [{k: smart_type(v) for k, v in zip(txt[0], l)} for l in txt[1:]] for s in sessions: s['Xa'] = [float(x) for x in s['Xa'].split(';')] s['Ya'] = [float(x) for x in s['Ya'].split(';')] s['Xu'] = [float(x) for x in s['Xu'].split(';')] s['Yu'] = [float(x) for x in s['Yu'].split(';')] X = [x for s in sessions for k in ['Xa', 'Xu'] for x in s[k]] Y = [y for s in sessions for k in ['Ya', 'Yu'] for y in s[k]] xmin, xmax, ymin, ymax = [min(X), max(X), min(Y), max(Y)] dx = xmax - xmin dy = ymax - ymin xmin -= dx / 20 xmax += dx / 20 ymin -= dy / 20 ymax += dy / 20 for s in sessions: fig = figure(figsize=(5, 5)) subplots_adjust(.15, .15, .9, .9) plot_session(s, [xmin, xmax, ymin, ymax]) buf = io.BytesIO() savefig(buf, format='pdf') close(fig) zf.writestr(f"/sessions/{s['Session']}.pdf", buf.getvalue()) mem.seek(0) response = Response(FileWrapper(mem), mimetype="application/zip", direct_passthrough=True) response.headers[ 'Content-Disposition'] = 'attachment; filename=ClumpyCrunch.zip' return response
def getMnistImagePng(id): image = digit_image(id) bytes = BytesIO() image.save(bytes, 'PNG') bytes.seek(0) wrapper = FileWrapper(bytes) return Response(wrapper, mimetype='image/png', direct_passthrough=True)
def send_stream(stream, filename, size, mtime, mimetype=None, restricted=True, as_attachment=False, etag=None, content_md5=None, chunk_size=8192, conditional=True): """Send the contents of a file to the client.""" # Guess mimetype from filename if not provided. if mimetype is None and filename: mimetype = mimetypes.guess_type(filename)[0] if mimetype is None: mimetype = 'application/octet-stream' # Construct headers headers = Headers() if as_attachment: headers.add('Content-Disposition', 'attachment', filename=filename) else: headers.add('Content-Disposition', 'inline') headers['Content-Length'] = size if content_md5: headers['Content-MD5'] = content_md5 # Construct response object. rv = current_app.response_class( FileWrapper(stream, buffer_size=chunk_size), mimetype=mimetype, headers=headers, direct_passthrough=True, ) # Set etag if defined if etag: rv.set_etag(etag) # Set last modified time if mtime is not None: rv.last_modified = int(mtime) # Set cache-control if not restricted: rv.cache_control.public = True cache_timeout = current_app.get_send_file_max_age(filename) if cache_timeout is not None: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if conditional: rv = rv.make_conditional(request) return rv
def send_file(buffer, filename, mimetype): file_wrapper = FileWrapper(buffer) headers = { "Content-Disposition": 'attachment; filename="{}"'.format(filename) } return Response(file_wrapper, mimetype=mimetype, direct_passthrough=True, headers=headers)
def art_thumb(request, pk): art = get_object_or_404(Art, pk=pk) image = art.rasterize_thumb() # https://help.pythonanywhere.com/pages/FlaskSendFileBytesIO/ wrapped_image = FileWrapper(image) response = HttpResponse(wrapped_image, content_type="image/png") response["Content-Disposition"] = 'filename="thumb.png"' return response
def thumbnail(self, pk: int, digest: str, **kwargs: Dict[str, bool]) -> WerkzeugResponse: """Get Chart thumbnail --- get: description: Compute or get already computed chart thumbnail from cache. parameters: - in: path schema: type: integer name: pk - in: path schema: type: string name: sha responses: 200: description: Chart thumbnail image content: image/*: schema: type: string format: binary 302: description: Redirects to the current digest 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 500: $ref: '#/components/responses/500' """ chart = self.datamodel.get(pk, self._base_filters) if not chart: return self.response_404() if kwargs["rison"].get("force", False): cache_chart_thumbnail.delay(chart.id, force=True) return self.response(202, message="OK Async") # fetch the chart screenshot using the current user and cache if set screenshot = ChartScreenshot(pk).get_from_cache(cache=thumbnail_cache) # If not screenshot then send request to compute thumb to celery if not screenshot: cache_chart_thumbnail.delay(chart.id, force=True) return self.response(202, message="OK Async") # If digests if chart.digest != digest: return redirect( url_for(f"{self.__class__.__name__}.thumbnail", pk=pk, digest=chart.digest)) return Response(FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True)
def get(self, exam_id): csr = CSR.find_by_username(g.jwt_oidc_token_info['username']) try: exam = Exam.query.filter_by(exam_id=exam_id).first() if not (exam.office_id == csr.office_id or csr.ita2_designate == 1): return {"The Exam Office ID and CSR Office ID do not match!" }, 403 job = self.bcmp_service.check_exam_status(exam) my_print(job) if job['jobStatus'] == 'PACKAGE_GENERATED': package_url = job["jobProperties"]["EXAM_PACKAGE_URL"] req = urllib.request.Request(package_url) response = urllib.request.urlopen(req).read() exam_file = io.BytesIO(response) file_wrapper = FileWrapper(exam_file) return Response(file_wrapper, mimetype="application/pdf", direct_passthrough=True, headers={ "Content-Disposition": 'attachment; filename="%s.csv"' % exam.exam_id, "Content-Type": "application/pdf" }) else: return { 'message': 'Package not yet generated', 'status': job['jobStatus'] }, 400 # test_url = 'http://www.pdf995.com/samples/pdf.pdf' # req = urllib.request.Request(test_url) # response = urllib.request.urlopen(req).read() # exam_file = io.BytesIO(response) # file_wrapper = FileWrapper(exam_file) # # return Response(file_wrapper, # mimetype="application/pdf", # direct_passthrough=True, # headers={ # "Content-Disposition": 'attachment; filename="%s.csv"' % exam.exam_id, # "Content-Type": "application/pdf" # }) except exc.SQLAlchemyError as error: logging.error(error, exc_info=True) return {'message': 'API is down'}, 500
def api_blob_get(): with open(os.environ.get("MAILROUND_STATUS_LOG_PATH", "./data.mrmp"), "rb") as fobj: bin_data = io.BytesIO(fobj.read()) w = FileWrapper(bin_data) return send_file(bin_data, attachment_filename='data.mrmp', mimetype='application/x-msgpack')
def download(version): download_dict = {} for each in list(main.find()): try: download_dict[each['version']] = jsonpickle.decode(each['file']) except KeyError: continue try: return flask.Response(FileWrapper(download_dict[version]), mimetype="application/zip") except KeyError: return flask.abort(404)
def motion(docket_number): title, document = generate_motion_using_file(docket_number) f = BytesIO() document.save(f) f.seek(0) return Response(FileWrapper(f), mimetype="text/docx", direct_passthrough=True, headers={ 'Content-Disposition': 'attachment; filename="{}.docx"'.format(title) })
def download_photos(): memory_file = BytesIO() with zipfile.ZipFile(memory_file, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk(current_app.config['UPLOADS_FOLDER']): for file in files: zipf.write(os.path.join(root, file), file) memory_file.seek(0) return Response(FileWrapper(memory_file), mimetype="application/zip",\ direct_passthrough=True, headers = { 'Content-Disposition': 'attachment; filename=%s.zip' %\ (urllib.parse.quote(current_app.config['SITE_TITLE'])) })
def emptymap_view(): coordinates = load_coordinates(COORDINATE_PATH) image = captureImage() result = annotateEmptySpaces(image, coordinates, THRESHOLD) im = Image.fromarray( (255.0 / result.max() * (result - result.min())).astype(np.uint8) ) bio = io.BytesIO() im.save(bio, "png") bio.seek(0) w = FileWrapper(bio) return Response(w, mimetype="image/png", direct_passthrough=True)
def send_excel_file(data, filename): # See: https://www.pythonanywhere.com/forums/topic/13570/ file_wrapper = FileWrapper(data) headers = { 'Content-Disposition': 'attachment; filename="{}"'.format(filename) } response = Response( file_wrapper, mimetype= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', direct_passthrough=True, headers=headers) return response
def rd(): req = request.get_json() # 获取json key = req['_key'] # 获取key if req['filename'] == STATE[key]['filename']: attachment = io.BytesIO(b'') else: attachment = io.BytesIO(STATE[key]['im']) w = FileWrapper(attachment) resp = Response(w, mimetype='text/plain', direct_passthrough=True) resp.headers['filename'] = STATE[key]['filename'] return resp