def get_screenshot(): url = request.args.get("url", None) width = int(request.args.get("width", 400)) height = int(request.args.get("height", 400)) scale = float(request.args.get("scale", 0.5)) timeout = int(request.args.get("timeout", -1)) is_smart_load = timeout == -1 file_name = "%s.png" % (util.generate_uuid()) file_path = os.path.join(RESOURCES_FOLDER_PATH, file_name) x_width = int(width / scale) x_height = int(height / scale) params = { 'url': url, 'width': width, 'height': height, 'scale': scale, } cache_filename = slugify(json.dumps(params)) cache_filepath = os.path.join(RESOURCES_FOLDER_PATH, '%s.png' % (cache_filename)) if os.path.exists(cache_filepath): return send_file(cache_filepath, mimetype='image/png') driver = webdriver.PhantomJS() driver.set_window_size(x_width, x_height) driver.set_page_load_timeout(0) try: driver.get(url) except: if is_smart_load: while True: time.sleep(0.5) driver.get_screenshot_as_file(file_path) if is_0byte(file_path) or is_all_white(file_path): continue else: time.sleep(SMART_LOAD_LOAD_SECS) driver.get_screenshot_as_file(file_path) break else: time.sleep(timeout) driver.get_screenshot_as_file(file_path) finally: driver.quit() if is_0byte(file_path): return send_file(DEFAULT_IMAGE_PLACEHOLDER, mimetype='image/png') if is_all_white(file_path): return send_file(DEFAULT_IMAGE_PLACEHOLDER, mimetype='image/png') # crop image img = Image.open(file_path) worked_image = img.crop((0, 0, x_width, x_height)) worked_image = worked_image.resize((width, height), Image.ANTIALIAS) worked_image.save(cache_filepath) return send_file(cache_filepath, mimetype='image/png')
def decryptedPDFoutput(): pdfile = request.files['files'] password = request.form['password'] if pdfile.filename != '': file_ext = (pdfile.filename).split(sep='.')[-1] if file_ext not in app.config['UPLOAD_EXTENSIONS']: return bad_request(0) in_memory_file = io.BytesIO() pdfile.save(in_memory_file) #here in x we get bytes data of generated PDF file x = decryptPDF(in_memory_file, password) if (type(x) != dict): #here in send_file first parameter in filename or fp, so we are passing fp #as_attachment = True -> File directly downloads return send_file(io.BytesIO(x), mimetype='application/pdf', attachment_filename='output.pdf', as_attachment=False) else: #return f" <h1> {x['error']} </h1>" return bad_request(x['error'])
def imgtoPDFoutput(): imgBytesIO = [] for i in request.files.getlist('files'): if i.filename != '': file_ext = (i.filename).split(sep='.')[-1] if file_ext not in app.config['UPLOAD_EXTENSIONS']: return bad_request(0) in_memory_file = io.BytesIO() i.save(in_memory_file) imgBytesIO.append(in_memory_file) #here in x we get bytes data of generated PDF file x = imagetoPDF(imgBytesIO) if (x != "Error"): #here in send_file first parameter in filename or fp, so we are passing fp #as_attachment = True -> File directly downloads return send_file(io.BytesIO(x), mimetype='application/pdf', attachment_filename='output.pdf', as_attachment=False) else: #return f" <h1> {x['error']} </h1>" return bad_request(x['error'])
def wms(layer, x, y, z): if not tileconfig.layers.has_key(layer): return abort(404) coord = ModestMaps.Core.Coordinate(y, x, z) type, bytes = TileStache.getTile(tileconfig.layers[layer], coord, 'png') buf = BytesIO(bytes) return send_file(buf, mimetype=type)
def update_graph(graph_type): update_times() graph_name = 'graph_%s.png' % graph_type url = os.path.join(IMG_BASE, graph_name) resource_map = {res.res_id : res.name for res in get_all_resources()} plots = [] plot_names = [] series = {} db_data = query_db(g.db, 'select * from resource_time_tracking order by timestamp') for row in db_data: res_id = row['res_id'] if not series.has_key(res_id): series[res_id] = {'x_vals':[], 'y_vals':[]} series[res_id]['x_vals'].append(datetime.fromtimestamp(row['timestamp'])) series[res_id]['y_vals'].append(row['time_spent'] * 1.0 / 60.0 ) fig = plt.figure() ax = fig.add_subplot(111) for res_id in series.keys(): plot_name = resource_map[res_id] new_plot, = ax.plot(series[res_id]['x_vals'], series[res_id]['y_vals'], label=plot_name) plots.append(new_plot) plot_names.append(plot_name) ax.legend(plots, plot_names, loc=2) fig.autofmt_xdate() fig.savefig(url) return send_file(url, mimetype="image/png")
def send_file_partial(filePath): range_header = request.range if not range_header: return send_file(filePath) if range_header.units != 'bytes' or len(range_header.ranges) != 1: abort(400) size = os.path.getsize(filePath) content_range = range_header.make_content_range(size) app.logger.debug("Send file %s: %s" % (content_range, filePath)) length = content_range.stop - content_range.start def data_generator(length=length): buffer_size = 8192 with open(filePath, 'rb') as fp: fp.seek(content_range.start) while length > 0: data = fp.read(min(length, buffer_size)) length -= len(data) yield data rv = Response(data_generator(), 206, mimetype=mimetypes.guess_type(filePath)[0], direct_passthrough=True) rv.headers.add('Content-Range', content_range.to_header()) return rv
def pdf(): if build_mode: return send_file( generate_pdf(build_mode, pages, get_nav()['reference'])) else: return "Not supported in the dev mode, ask in #kotlin-web-site, if you need it"
def fortune(): msg = subprocess.check_output('/usr/games/fortune') with open(MESSAGES, 'a') as f: f.write(msg) with tempfile.NamedTemporaryFile() as f: synth.say(msg, out=f) return helpers.send_file(f.name, mimetype="audio/wav", as_attachment=False)
def _get_photo(self, request): photo_hash = request.values['photo_hash'] zdjecie = self.db_api.get_photo(photo_hash) # if res_db.status_code == 404: # return jsonify({'error': 'no such user'}), 404 return zdjecie return send_file(zdjecie)
def get_user_certs(): user = auth_user(request.values.get('username', ''), request.values.get('password', '')) if not user: # Authentication failed return simplejson.dumps(False) # Creates new certificates for this user certs = x509cert.generate_certificate( cert_dir=common.config.get('conpaas', 'CERT_DIR'), uid=str(user.uid), sid='0', role='user', email=user.email, cn=user.username, org='Contrail' ) # In-memory zip file zipdata = StringIO() archive = zipfile.ZipFile(zipdata, mode='w') # Add key.pem, cert.pem and ca_cert.pem to the zip file for name, data in certs.items(): archive.writestr(name + '.pem', data) archive.close() zipdata.seek(0) # Send zip archive to the client return helpers.send_file(zipdata, mimetype="application/zip", as_attachment=True, attachment_filename='certs.zip')
def wms(layer,x,y,z): if not tileconfig.layers.has_key(layer): return abort(404) coord = ModestMaps.Core.Coordinate(y,x,z) type, bytes = TileStache.getTile(tileconfig.layers[layer], coord, 'png') buf = BytesIO(bytes) return send_file(buf, mimetype=type)
def get_user_certs(): # Creates new certificates for this user certs = x509cert.generate_certificate( cert_dir=config_parser.get('conpaas', 'CERT_DIR'), uid=str(g.user.uid), sid='0', role='user', email=g.user.email, cn=g.user.username, org='Contrail' ) # In-memory zip file zipdata = StringIO() archive = zipfile.ZipFile(zipdata, mode='w') # Add key.pem, cert.pem and ca_cert.pem to the zip file for name, data in certs.items(): archive.writestr(name + '.pem', data) archive.close() zipdata.seek(0) log('New certificates for user %s created' % g.user.username) # Send zip archive to the client return helpers.send_file(zipdata, mimetype="application/zip", as_attachment=True, attachment_filename='certs.zip')
def doc_live(filename): filename = os.path.join(DOC, filename) if filename.endswith('.html'): from worksheet import worksheet_file return worksheet_file(filename) else: from flask.helpers import send_file return send_file(filename)
def give_chart(chart_ID): path = cached_generate(chart_ID) if path: mime = 'image/png' resp = send_file(path, mimetype=mime) else: resp = ("Chart was not found", 404) return resp
def view_image(selector, collection_id, seq_num, size=None): coll = collection_by(selector, collection_id) try: the_image = coll.images[seq_num] return send_file(the_image.image_data, mimetype='image/jpeg') except IndexError, TypeError: # seq_num is invalid somehow raise NotFound
def get(key): """ Return the file if found, otherwise 404 is raised. """ cache_base_folder = app.config.get('CACHE_BASE_FOLDER') file_path = os.path.join(cache_base_folder, key) if not os.path.exists(file_path): abort(404, 'File not found.') return helpers.send_file(file_path)
def get_albums(): base_path = pathlib.Path(os.path.join(app.config['UPLOAD_FOLDER'], 'album1')) data = io.BytesIO() with zipfile.ZipFile(data, mode='w') as z: for file in base_path.iterdir(): z.write(file) data.seek(0) return send_file(data, mimetype='application/zip', as_attachment=True, attachment_filename='data.zip')
def get(self, item): """Get the concluding plot for this session and a result item.""" approximator: LexicalItemApproximator = session['approximator'] session['result_plot'] = approximator.get_result_plot_image( item['item']) return send_file(io.BytesIO(session['result_plot']), mimetype='image/png', attachment_filename=f'plot{datetime.now()}.png')
def showCacheFile(self, filename = ''): file_path = os.path.join(Env.get('cache_dir'), os.path.basename(filename)) if not os.path.isfile(file_path): log.error('File "%s" not found', file_path) raise NotFound() return send_file(file_path, conditional = True)
def get_dog_image(id): dog = LostDog.query.get_or_404(id) mem = io.BytesIO() mem.write(dog.picture) mem.seek(0) return send_file( mem, mimetype='application/octet-stream' )
def mnist(): index = int(request.args.get('index', '-1')) if index == -1: return "image not found", 404 im = testset.data[index].detach().numpy() img = Image.fromarray(im) img_bin = io.BytesIO() img.save(img_bin, 'png') img_bin.seek(0) return send_file(img_bin, mimetype='image/png', as_attachment=False)
def get_html(): # with as f: # soup = BeautifulSoup(f, "html.parser") # for s in soup.select("script"): # s.extract() # for s in soup.select("iframe"): # s.extract() # for s in soup.select("link"): # s.extract() return send_file(open("./static/test.html", "rb"), mimetype="text/html")
def get_map(): x = float(request.args.get('x')) y = float(request.args.get('y')) alpha = float(request.args.get('alpha')) beta = float(request.args.get('beta')) gamma = float(request.args.get('gamma')) video_path = map.simulate(x, y, alpha, beta, gamma) return send_file(video_path, mimetype='video/mp4')
def reduce(): if request.files: if request.files['file'].filename != "": file = request.files['file'].read() npimg = numpy.fromstring(file, numpy.uint8) img = cv2.imdecode(npimg, cv2.IMREAD_COLOR) a = reduceSize.reduce_storeage(img) if a: return send_file("reduced.jpeg", mimetype='image/jpeg') else: return ""
def download_image_csv(name): """ GET Returns the specified image csv file to the client """ api_key = request.args.get('api_key') if not managers.users_manager.verify_api_key(api_key): return jsonify(success=False) return send_file(os.path.join('image_csv_files', name), as_attachment=True)
def raw_image(raw_id, data): filepath = os.path.join(upload_path, str(raw_id)) if not os.path.exists(filepath): return abort(404) if ':' in data: extension = data.split(':')[0] else: extension = 'image/png' return send_file(filepath, mimetype=extension)
def deliver_file(self, s3_key): # check again if it's in the cache. if a thumbnail was newly # created, it is now locally available. TODO guess extension? key_no_prefix = s3_key.replace(self.prefix, '') exts = ('.jpg', '.png') for ext in exts: cache_key = key_no_prefix + ext if cache_key in self.cache: mimetype, _ = mimetypes.guess_type(cache_key) return send_file(self.cache.path(cache_key), mimetype) url = self.bucket().make_url_authed(s3_key, 3600) return redirect(url, 307)
def get(self, session=None): """ Cache remote resources """ args = cached_parser.parse_args() url = args.get('url') force = args.get('force') try: file_path, mime_type = cached_resource(url, self.manager.config_base, force=force) except RequestException as e: raise BadRequest('Request Error: {}'.format(e.args[0])) except OSError as e: raise APIError('Error: {}'.format(str(e))) return send_file(file_path, mimetype=mime_type)
def index(): # pylint: disable=unused-variable plugins_snippets = [p.GenerateHTML() for p in current_app.config['manuskript_plugins']] with open(os.path.join(STATIC_PATH, "index.html")) as fd: contents = fd.read() contents = contents.replace("<!-- manuskript-plugins -->", "\n".join(plugins_snippets)) return helpers.send_file(StringIO.StringIO(contents), mimetype="text/html", conditional=True)
def get_streetview_image(): try: location = request.args['location'] heading = request.args['heading'] pitch = request.args['pitch'] fov = request.args['fov'] except: raise WebAppException(error_code=MISSING_ARGUMENTS) imagedata = google_streetview.get_image(location, heading, pitch, fov) return send_file(imagedata, 'image/jpeg')
def export(self): ids = _gl('order_ids') _info(ids) def _f(obj): if obj.destination_city_id: return "".join(map(lambda v : unicode(v), [obj.destination_province, obj.destination_city])) return unicode(obj.destination_province) data = [] for r in DBSession.query(OrderHeader).filter(OrderHeader.id.in_(ids)).order_by(OrderHeader.create_time): row = [r.order_time, r.ref_no, _f(r), unicode(r.destination_company), r.destination_contact, r.qty, r.weight, r.destination_tel, '', ] # A - H deliver_header = r.get_deliver_header() if deliver_header : row.extend(['', deliver_header.no, deliver_header.sendout_time, '', '', deliver_header.expect_time, deliver_header.actual_time, '', ]) # I - P else: row.extend(['', '', '', '', '', '', '', '', ]) # I - P pickup_info = ['', '', '', '', '', '0.5', '', '', ] tmp_count = 0 for index, d in enumerate(r.pickup_details): if index > 2: break if d.qty : pickup_info[index + 1] = d.qty tmp_count += d.qty pickup_info[4] = r.qty - tmp_count row.extend(pickup_info) # Q - X row.extend(['', '', '', 'Y' if r.actual_time > r.expect_time else 'N', 'Y' if r.signed_time else 'N', r.signed_contact or '', r.signed_time, '', '', ]) # Y - AG data.append(row) if not data : data = [['', ], ] if not os.path.exists(TMP_FOLDER): os.makedirs(TMP_FOLDER) current = dt.now() templatePath = os.path.join(TEMPLATE_FOLDER, "template.xls") tempFileName = os.path.join(TMP_FOLDER, "report_tmp_%s_%d.xls" % (current.strftime("%Y%m%d%H%M%S"), random.randint(0, 1000))) realFileName = os.path.join(TMP_FOLDER, "report_%s.xls" % (dt.now().strftime("%Y%m%d%H%M%S"))) shutil.copy(templatePath, tempFileName) report_xls = SummaryReport(templatePath = tempFileName, destinationPath = realFileName) report_xls.inputData(data = data) report_xls.outputData() try: os.remove(tempFileName) except: pass return send_file(realFileName, as_attachment = True)
def index(): # pylint: disable=unused-variable plugins_snippets = [ p.GenerateHTML() for p in current_app.config['manuskript_plugins'] ] with open(os.path.join(STATIC_PATH, "index.html")) as fd: contents = fd.read() contents = contents.replace("<!-- manuskript-plugins -->", "\n".join(plugins_snippets)) return helpers.send_file(StringIO.StringIO(contents), mimetype="text/html", conditional=True)
def getFilesFromBucket(): nomeFile = request.args.get('file') if nomeFile is not None: (uri, f) = bucketHelper.getFileFromBucket(nomeFile) print(nomeFile) return send_file(f, mimetype='audio/wav', attachment_filename=nomeFile) else: myFileInBucket = bucketHelper.getListBucket() result = app.response_class(response=json.dumps( [ob.__dict__ for ob in myFileInBucket]), status=200, mimetype='application/json') return result
def dowload_video(): link = "https://www.youtube.com/watch?v=" + request.form['id'] print(link) yt = YouTube(link) stream = yt.streams.first() downloadfile = stream.download() fname = downloadfile.split("//")[-1] @after_this_request def remove_file(response): os.remove(downloadfile) return response return send_file(fname, as_attachment=True)
def download_route(data_uuid): """Download converted file.""" try: data_uuid = str(uuid.UUID(data_uuid)) except ValueError: return """ <!doctype html> <p>invalid identifier</p> <p> """ out_file = os.path.join(settings.UPLOAD_DIR, data_uuid + ".h5ad") return helpers.send_file(out_file, mimetype="application/binary", as_attachment=True)
def aadhar_resize_mar(): if request.files: if request.files['file'].filename != "": file = request.files['file'].read() npimg = numpy.fromstring(file, numpy.uint8) img = cv2.imdecode(npimg, cv2.IMREAD_COLOR) height = int(request.form['height']) width = int(request.form['width']) a = aadharResize.resize_aadhar_mar(img, height=height, width=width) if a[0]: cv2.imwrite("resized.jpeg", a[1]) return send_file("resized.jpeg", mimetype='image/jpeg') else: return "Inappropiate size"
def rest_response(self): if self.http_status_code != 200: if self.content is None: abort(http_status_code=self.http_status_code) else: abort(http_status_code=self.http_status_code, message=self.content) if self.mimetype == 'application/json': return make_response(jsonify(self.content), self.http_status_code) else: if type(self.content) == str: self.content = self.content.encode('ISO-8859-1') return send_file(BytesIO(self.content), mimetype=self.mimetype)
def download(): if request.cookies['WOWPOW'] == '': return redirect(url_for('/')) else: id = int(E.decrypt(request.cookies['WOWPOW'])[1]) eid = str(hashlib.sha224(str(id).encode()).hexdigest()) if request.method == 'POST': if request.form.get('download'): dfile = request.form.get('download') dpath = request.form.get('dpath') if dpath == 'root': return send_file('user_stuff\\' + eid + '\\' + dfile, attachment_filename=dfile, as_attachment=True) else: return send_file('user_stuff\\' + eid + '\\' + dpath + '\\' + dfile, attachment_filename=dfile, as_attachment=True) else: return redirect(url_for('/')) else: return redirect(url_for('/'))
def get_file(file_path): base_path = "{0}/{1}".format(os.getcwd(), session['login_id']) abs_path = os.path.join(base_path, file_path) # Check if path is a file and serve if os.path.isfile(abs_path): if abs_path.endswith("task.log"): with open(abs_path, "r") as logs_file: return render_template('show_logs.html', name=escape(session['login_id']), data=escape(logs_file.read())) else: return send_file(abs_path, as_attachment=True) else: return abort(404)
def unconditional_download(worksheet, title): from sagenb.misc.misc import tmp_filename from flask.helpers import send_file filename = tmp_filename() + '.sws' if title.endswith('.sws'): title = title[:-4] try: #XXX: Accessing the hard disk. g.notebook.export_worksheet(worksheet.filename(), filename, title) except KeyError: return current_app.message(_('No such worksheet.')) from flask.helpers import send_file return send_file(filename, mimetype='application/sage')
def flask_response(self): """ Returns a Flask-friendly response or aborts the request if needed. """ if self.http_status_code != 200: if self.content is None: abort(status=self.http_status_code) else: abort(status=self.http_status_code, description=self.content) if self.mimetype == 'application/json': return make_response(jsonify(self.content), self.http_status_code) else: if type(self.content) == str: self.content = self.content.encode('ISO-8859-1') return send_file(BytesIO(self.content), mimetype=self.mimetype)
def download(username): result_id = username result_zip = ZipFile(file_path + result_id + '.zip', 'w') for f in glob.glob(file_path+result_id+'*.pdf'): result_zip.write(f, basename(f)) print("added pdf: " + f) for f in glob.glob(file_path+result_id+'*.csv'): result_zip.write(f, basename(f)) print('added csv: ' + f) for f in glob.glob(file_path+result_id+'*.tsv'): result_zip.write(f, basename(f)) print('added csv: ' + f) result_zip.close() return send_file(os.path.abspath(file_path + result_id + '.zip'), as_attachment=True)
def get_zip(id): work = db.session.query(Work).get(id) if work is None: abort(404) # zipファイルを作成する zip_stream = io.BytesIO() with zipfile.ZipFile(zip_stream, 'w') as zip_temp: zip_temp.writestr('index.html', work.html) zip_temp.writestr('style.css', work.css) zip_temp.writestr('index.js', work.javascript) zip_stream.seek(0) return send_file(zip_stream, attachment_filename=f'work_{work.id}.zip', as_attachment=True), 200
def send_static(filename): """Sends a file from the static folder if a given file exist. Otherwise, tries additional folders as a fallback. """ try: return current_app.send_static_file(filename) except NotFound: for prefix, folder in locations: if prefix: prefix = '{}{}'.format(prefix, os.sep) if filename.startswith(prefix): filename = filename[len(prefix):] filepath = safe_join(folder, filename) if os.path.isfile(filepath): return send_file(filepath) raise NotFound()
def doc_static_file(manual, path_static, filename): """ The docs reference a _static URL in the current directory, even if the real _static directory only lives in the root of the manual. This function strips out the subdirectory part and returns the file from the _static directory in the root of the manual. This seems like a Sphinx bug: the generated html file should not reference a _static in the current directory unless there actually is a _static directory there. TODO: Determine if the reference to a _static in the current directory is a bug in Sphinx, and file a report or see if it has already been fixed upstream. """ from flask.helpers import send_file filename = os.path.join(DOC, manual, '_static', filename) return send_file(filename)
def mp3(): collected_mp3s = Content.query.all() my_mp3s = {} for c in collected_mp3s: my_mp3s[c.c_mp3] = str("/mp3/" + str(c.c_id)) form = DownloadForm() if form.validate_on_submit(): sb = form.sb.data mp3 = "" content = Content.query.filter_by(c_shebang=sb).first() if content is not None: mp3 = content.c_mp3 else: mp3 = service.get_mp3(sb) content = Content(sb, mp3) db.add(content) db.commit() return send_file("../upload/"+mp3, mimetype="audio/mp3", as_attachment=True, attachment_filename=mp3) return render_template("mp3.html", title="Download MP3", form=form, my_mp3s=my_mp3s)
def test(): data = request.args.get('data') error_correction = request.args.get('errors') if error_correction == 'L': error_correction_code = qrcode.constants.ERROR_CORRECT_L elif error_correction == 'M': error_correction_code = qrcode.constants.ERROR_CORRECT_M elif error_correction == 'Q': error_correction_code = qrcode.constants.ERROR_CORRECT_Q elif error_correction == 'H': error_correction_code = qrcode.constants.ERROR_CORRECT_H else: error_correction_code = DEFAULT_ERROR_CORRECTION img = qrcode.make(data, error_correction=error_correction_code, image_factory=PymagingImage) output = StringIO() img.save(output) output.seek(0) return send_file(output, mimetype='image/png')
def sendReport(analysisKey, module): db = mongo_client.minecraft all_mods = db.mods.find({'file_hash':analysisKey}) if all_mods.count() == 0: return 'No such record' #TODO: handle multiple records. for now, just take the first mod = all_mods[0] if module not in mod.keys(): return 'No such module' if mod[module]['finished'] == 'False': return 'Anslysis not finished' fd, path = tempfile.mkstemp() try: with open(path, 'w') as tmp: file_data = mod[module]['report'] data = base64.b64decode(file_data) report_name = mod['file_name']+module+".tar.bz2" tmp.write(data) return send_file(path, as_attachment=True, attachment_filename=report_name) finally: os.remove(path)
def mp3_load(id): mp3 = Content.query.filter_by(c_id=id).first() if mp3 is not None: mp3 = mp3.c_mp3 return send_file("../upload/"+mp3, mimetype="audio/mp3", as_attachment=True, attachment_filename=mp3) return redirect("mp3")
def pdf(): return send_file(generate_pdf(pages, nav['reference']))
def pdf(): return send_file(generate_pdf(pages, get_nav()['reference']))
def pdf_ko(): return send_file(generate_pdf_ko(pages, get_nav()['reference_ko']))
def respond_with_package_list(page_path): file_path = path.join(root_folder, 'api', page_path) if not path.exists(file_path): return make_response("package-list not found", 404) return send_file(file_path, mimetype="text/plain")
def favicon(): from flask.helpers import send_file return send_file(os.path.join(DATA, 'sage', 'images', 'favicon.ico'))
def doc_live(filename): filename = os.path.join(DOC, filename) from flask.helpers import send_file return send_file(filename)