def ugcfile(_id): _ugcfile = UGCFile.query.filter(UGCFile.id == _id).first() if not _ugcfile: _ugcfile = UGCFile(_id) # Only save if we actually have data if _ugcfile.url: db.session.add(_ugcfile) db.session.commit() # If we already have on disk, serve it. if os.path.exists(_ugcfile.local_uri): return send_file(_ugcfile.local_uri) # Otherwise fetch, save to disk, then serve it. if _ugcfile.url: with open(_ugcfile.local_uri, "w") as f: req = requests.get(_ugcfile.url, stream=True) if req.ok: for block in req.iter_content(1024): f.write(block) return send_file(_ugcfile.local_uri) # If all of the above fails, throw 404. abort(404)
def test_static_file(self): app = flask.Flask(__name__) # default cache timeout is 12 hours with app.test_request_context(): # Test with static file handler. rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 12 * 60 * 60) # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 12 * 60 * 60) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 with app.test_request_context(): # Test with static file handler. rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 3600) # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 3600) class StaticFileApp(flask.Flask): def get_send_file_max_age(self, filename): return 10 app = StaticFileApp(__name__) with app.test_request_context(): # Test with static file handler. rv = app.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 10) # Test again with direct use of send_file utility. rv = flask.send_file('static/index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 10)
def cover_art(): status, res = get_entity(request, Folder) if not status: return res if not res.has_cover_art or not os.path.isfile(os.path.join(res.path, 'cover.jpg')): return request.error_formatter(70, 'Cover art not found') size = request.values.get('size') if size: try: size = int(size) except: return request.error_formatter(0, 'Invalid size value') else: return send_file(os.path.join(res.path, 'cover.jpg')) im = Image.open(os.path.join(res.path, 'cover.jpg')) if size > im.size[0] and size > im.size[1]: return send_file(os.path.join(res.path, 'cover.jpg')) size_path = os.path.join(config.get('webapp', 'cache_dir'), str(size)) path = os.path.join(size_path, str(res.id)) if os.path.exists(path): return send_file(path) if not os.path.exists(size_path): os.makedirs(size_path) im.thumbnail([size, size], Image.ANTIALIAS) im.save(path, 'JPEG') return send_file(path)
def test_attachment(self): app = flask.Flask(__name__) with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, "static/index.html")) rv = flask.send_file(f, as_attachment=True) value, options = parse_options_header(rv.headers["Content-Disposition"]) self.assert_equal(value, "attachment") rv.close() # mimetypes + etag self.assert_equal(len(captured), 2) with app.test_request_context(): self.assert_equal(options["filename"], "index.html") rv = flask.send_file("static/index.html", as_attachment=True) value, options = parse_options_header(rv.headers["Content-Disposition"]) self.assert_equal(value, "attachment") self.assert_equal(options["filename"], "index.html") rv.close() with app.test_request_context(): rv = flask.send_file(StringIO("Test"), as_attachment=True, attachment_filename="index.txt", add_etags=False) self.assert_equal(rv.mimetype, "text/plain") value, options = parse_options_header(rv.headers["Content-Disposition"]) self.assert_equal(value, "attachment") self.assert_equal(options["filename"], "index.txt") rv.close()
def test_attachment(self): app = flask.Flask(__name__) with catch_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f, as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') # mimetypes + etag self.assert_equal(len(captured), 2) with app.test_request_context(): self.assert_equal(options['filename'], 'index.html') rv = flask.send_file('static/index.html', as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') self.assert_equal(options['filename'], 'index.html') with app.test_request_context(): rv = flask.send_file(StringIO('Test'), as_attachment=True, attachment_filename='index.txt', add_etags=False) self.assert_equal(rv.mimetype, 'text/plain') value, options = parse_options_header(rv.headers['Content-Disposition']) self.assert_equal(value, 'attachment') self.assert_equal(options['filename'], 'index.txt')
def file(recid, filename): """Serve attached documents.""" from invenio.modules.documents import api record = get_record(recid) duuids = [uuid for (k, uuid) in record.get('_documents', []) if k == filename] error = 404 for duuid in duuids: document = api.Document.get_document(duuid) if not document.is_authorized(current_user): current_app.logger.info( "Unauthorized access to /{recid}/files/{filename} " "({document}) by {current_user}".format( recid=recid, filename=filename, document=document, current_user=current_user)) error = 401 continue # TODO add logging of downloads if document.get('linked', False): if document.get('uri').startswith('http://') or \ document.get('uri').startswith('https://'): return redirect(document.get('uri')) # FIXME create better streaming support file_ = cStringIO.StringIO(document.open('rb').read()) file_.seek(0) return send_file(file_, mimetype='application/octet-stream', attachment_filename=filename) return send_file(document['uri']) abort(error)
def test_send_file_object(self): app = flask.Flask(__name__) with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) with app.open_resource('static/index.html') as f: assert rv.data == f.read() assert rv.mimetype == 'text/html' app.use_x_sendfile = True with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f) assert rv.mimetype == 'text/html' assert 'x-sendfile' in rv.headers assert rv.headers['x-sendfile'] == \ os.path.join(app.root_path, 'static/index.html') app.use_x_sendfile = False with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) assert rv.data == 'Test' assert rv.mimetype == 'application/octet-stream' f = StringIO('Test') rv = flask.send_file(f, mimetype='text/plain') assert rv.data == 'Test' assert rv.mimetype == 'text/plain' app.use_x_sendfile = True with app.test_request_context(): f = StringIO('Test') rv = flask.send_file(f) assert 'x-sendfile' not in rv.headers
def tsung(): reqs = '' #request preview tabs = {} #report table values form = TsungForm() if form.validate_on_submit(): if request.form['button'] == 'Generate and Launch': CreateXML(form.gentype.data, form.dtime.data, form.rate.data, form.loop.data, form.rtype.data, form.qtype.data, form.pquery.data) CreateASG(form.instnum.data) if form.gentype.data == 1: subprocess.Popen('scripts/tsung_script.sh') elif form.gentype.data == 2: subprocess.Popen('scripts/tsung_dist2.sh') elif form.gentype.data == 3: subprocess.Popen('scripts/tsung_dist3.sh') else: subprocess.Popen(['scripts/tsung_fulldist.sh',str(form.gentype.data)]) return redirect('chaosm') elif request.form['button'] == 'Preview Load': reqs = str(form.dtime.data*form.rate.data*form.loop.data*60) elif request.form['button'] == 'CPU-Graph': return send_file(Plot()) elif request.form['button'] == 'Requests-Graph': #eturn send_file('../data/config.xml') return send_file('../data/logs/images/graphes-HTTP_CODE-rate.png') elif request.form['button'] == 'Report': tabs = Tables(tabs) return render_template('tsung.html',form=form,reqs=reqs,tabs=tabs)
def post(self): userid = SessionUtil.get_user_id(request.form['session']) if not userid: return {'status': ServerConstants.STATUS_INVALID_SESSION} eventid = request.form['eventid'] with closing(ServerConstants.mysql_pool.get_connection()) as db: with closing(db.cursor()) as cursor: sql = "SELECT filename, type FROM `events` WHERE id='{}'".format(eventid) cursor.execute(sql) rows = cursor.fetchall() if rows: filename = ServerConstants.STORAGE_DIR+rows[0][0] event_type = rows[0][1] if event_type == 'jpeg': #output = StringIO() #img = Image.open(filename) #img.save(output, 'JPEG') #output.seek(0) #return send_file(output, mimetype='image/jpeg') return send_file(filename, mimetype='image/jpeg') elif event_type == 'ogg': return send_file(filename, mimetype='audio/ogg') elif event_type == 'h264': return send_file(filename, mimetype='video/h264')
def test_send_file_object_without_mimetype(self, app, req_ctx): with pytest.raises(ValueError) as excinfo: flask.send_file(StringIO("LOL")) assert 'Unable to infer MIME-type' in str(excinfo) assert 'no filename is available' in str(excinfo) flask.send_file(StringIO("LOL"), attachment_filename='filename')
def test_attachment(self, app, req_ctx): with open(os.path.join(app.root_path, 'static/index.html')) as f: rv = flask.send_file(f, as_attachment=True, attachment_filename='index.html') value, options = \ parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' assert 'filename*' not in rv.headers['Content-Disposition'] rv.close() rv = flask.send_file('static/index.html', as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' rv.close() rv = flask.send_file(StringIO('Test'), as_attachment=True, attachment_filename='index.txt', add_etags=False) assert rv.mimetype == 'text/plain' value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.txt' rv.close()
def report(survey_id): survey = Survey.objects.get_or_404(id=survey_id) filename = "sanap-%s-%s.pdf" % (survey.country, datetime.now().strftime("%Y-%m-%d %H.%M")) pdf_file = export_pdf(survey) zip_file = NamedTemporaryFile(suffix=".zip") tmp_name = zip_file.name zip_obj = zipfile.ZipFile(zip_file, "w") zip_obj.write(pdf_file.name, filename) zip_required = False for filefield in FILE_FIELDS: for fileinstance in getattr(survey, filefield): zip_required = True abspath = files.path(fileinstance) arcname = "uploads/%s" % abspath.rsplit(os.sep, 1)[-1] zip_obj.write(abspath, arcname) zip_obj.close() if not zip_required: response = send_file(pdf_file.name, mimetype="application/pdf") pdf_file.close() response.headers["Content-Disposition"] = 'attachment; filename="%s"' % filename else: pdf_file.close() response = send_file(tmp_name, mimetype="application/zip") response.headers["Content-Disposition"] = ("attachment; " 'filename="%s-full-report.zip"') % survey.country return response
def _send_image(self, im): if self._get_format() == self.FORMAT_EPD: sio = epd.convert(im) return send_file(sio, mimetype='image/epd') else: sio = self._stream_image(im) return send_file(sio, mimetype='image/png')
def get(self, auxComp): if not aux.check(auxComp): response = jsonify({'Status': 'Parameter error', 'Message': 'Unsupported Parameter' + auxComp}) app.logger.warning('[%s] : [WARN] Unsupported parameter: %s', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(auxComp)) response.status_code = 400 return response if auxComp == 'collectd': try: clog = open(collectdlog, 'w+') except Exception as inst: app.logger.error('[%s] : [ERROR] Opening collectd log with %s and %s', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), type(inst), inst.args) response = jsonify({'Status': 'File Error', 'Message': 'Cannot open log file'}) response.status_code = 500 return response return send_file(clog, mimetype='text/plain', as_attachment=True) if auxComp == 'lsf': try: clog = open(lsflog, 'w+') except Exception as inst: app.logger.error('[%s] : [ERROR] Opening lsf log with %s and %s', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), type(inst), inst.args) response = jsonify({'Status': 'File Error', 'Message': 'Cannot open log file'}) response.status_code = 500 return response return send_file(clog, mimetype='text/plain', as_attachment=True) else: response = jsonify({'Status': 'Unsupported comp' + auxComp}) response.status_code = 400 return response
def get(self, auxComp): if not aux.check(auxComp): response = jsonify({'Status': 'Parameter error', 'Message': 'Unsupported Parameter' + auxComp}) app.logger.warning('[%s] : [WARN] Unsupported parameter: %s', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(auxComp)) response.status_code = 400 return response if auxComp == 'collectd': try: cConf = open(collectdConf, 'r') except Exception as inst: # print >> sys.stderr, type(inst) # print >> sys.stderr, inst.args app.logger.error('[%s] : [ERROR] Opening collectd conf file', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) return send_file(cConf, mimetype='text/plain', as_attachment=True) if auxComp == 'lsf': try: lConf = open(lsfConf, 'r') except Exception as inst: # print >> sys.stderr, type(inst) # print >> sys.stderr, inst.args app.logger.error('[%s] : [ERROR] Opening logstash-forwarder conf file', datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) return send_file(lConf, mimetype='application/json', as_attachment=True) else: response = jsonify({'Status': 'Unsupported comp' + auxComp}) response.status_code = 400 return response
def path(path): if path == 'atom.xml': return send_file('build/atom.xml/index.html', mimetype="application/atom+xml", cache_timeout=60) return send_file('build/%s/index.html' % path, cache_timeout=60)
def file_(): is_valid = validate_request() if is_valid is not True: return make_response(is_valid, 400) data = clean_request() content_auth = ContentAuth(data['username'], data['password']) opener = content_auth.opener(data['url']) if 'range' in request.headers: file_request = urllib2.Request(data['url'], headers={ 'Range': request.headers['range'], }) is_error, file_response = handle_error(opener, file_request) if is_error: return make_response(file_response.read(), file_response.code) response = send_file(file_response, add_etags=False) response.status_code = 206 else: is_error, file_response = handle_error(opener, data['url']) if is_error: return make_response(file_response.read(), file_response.code) response = send_file(file_response, add_etags=False) add_content_headers(response, file_response) response.headers['Accept-Ranges'] = 'bytes' return response
def pdf_endpoint(doc_id): base64, fn = get_file(doc_id) b = base64.decode('base64') mimetype = magic.from_buffer(b, mime=True) if mimetype == 'application/pdf': return send_file(io.BytesIO(b), as_attachment=True, attachment_filename=fn) else: fd, fname = tempfile.mkstemp(prefix=tmp_dir) stream = os.fdopen(fd, 'wb') stream.write(b) out_fname = fname + '.out' stream.close() os.chmod(fname, 0777) try: subprocess.check_output(['unoconv', '-o', out_fname, fname], stderr=subprocess.STDOUT) with open(out_fname, 'rb') as converted_stream: out = send_file(out_fname, as_attachment=True, attachment_filename=fn + '.pdf') except subprocess.CalledProcessError as e: print e.output # Return error pdf out = "no pdf available" os.remove(fname) os.remove(out_fname) return out
def Download(name , semester, filename): checkoutformat = re.search(fileformat,filename) if checkoutformat.group(2) in ['jpg','jpeg','png','bmp']: # surely there will be a pdf download_file = checkoutformat.group(1)+'.pdf' #updated_file = files.query.filter_by(filename = filename).first() if name is not None and semester is not None: updated_file = files.query.filter(and_(files.department.like(name), files.semester.like(int(semester)), files.filename.like(filename))).scalar() else: updated_file = files.query.filter(files.filename.like(filename)).scalar() updated_file.downloads += 1 db.session.commit() return send_file("../tmp/" + download_file, attachment_filename=download_file, as_attachment=True) else: download_file = filename if name is not None and semester is not None: updated_file = files.query.filter(and_(files.department.like(name), files.semester.like(int(semester)), files.filename.like(filename))).scalar() else: updated_file = files.query.filter(files.filename.like(filename)).scalar() updated_file.downloads += 1 db.session.commit() return send_file("../tmp/" + download_file, attachment_filename=download_file, as_attachment=True)
def cover_art(): res = get_entity(Folder) if not res.cover_art or not os.path.isfile(os.path.join(res.path, res.cover_art)): raise NotFound('Cover art') cover_path = os.path.join(res.path, res.cover_art) size = request.values.get('size') if size: size = int(size) else: return send_file(cover_path) im = Image.open(cover_path) if size > im.width and size > im.height: return send_file(cover_path) size_path = os.path.join(current_app.config['WEBAPP']['cache_dir'], str(size)) path = os.path.abspath(os.path.join(size_path, str(res.id))) if os.path.exists(path): return send_file(path, mimetype = 'image/' + im.format.lower()) if not os.path.exists(size_path): os.makedirs(size_path) im.thumbnail([size, size], Image.ANTIALIAS) im.save(path, im.format) return send_file(path, mimetype = 'image/' + im.format.lower())
def download(uuid, filename): jobdir = get_job_folder(uuid) if not os.path.exists(jobdir): abort(404) if filename: filename = os.path.join(jobdir, os.path.basename(filename)) if not os.path.exists(filename): abort(404) fp = open(filename) if filename.endswith("gif"): return send_file(fp, as_attachment=False, attachment_filename=os.path.basename(filename)) return send_file(fp, as_attachment=True, attachment_filename=os.path.basename(filename)) else: import tarfile import StringIO, glob fp = StringIO.StringIO() tar = tarfile.open(fileobj=fp, mode="w:gz") excludes = ["taskmanager.py", "err", "out", "run.pbs"] for f in glob.glob("%s/*" % jobdir): if os.path.basename(f) in excludes: continue tar.add(f, arcname="anmpathway/%s" % os.path.basename(f)) tar.close() fp.seek(0) return send_file(fp, mimetype="application/x-gzip", as_attachment=True, attachment_filename="anmpathway.tar.gz")
def test_attachment(self, catch_deprecation_warnings): app = flask.Flask(__name__) with catch_deprecation_warnings() as captured: with app.test_request_context(): f = open(os.path.join(app.root_path, 'static/index.html')) rv = flask.send_file(f, as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' rv.close() # mimetypes + etag assert len(captured) == 2 with app.test_request_context(): assert options['filename'] == 'index.html' rv = flask.send_file('static/index.html', as_attachment=True) value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.html' rv.close() with app.test_request_context(): rv = flask.send_file(StringIO('Test'), as_attachment=True, attachment_filename='index.txt', add_etags=False) assert rv.mimetype == 'text/plain' value, options = parse_options_header(rv.headers['Content-Disposition']) assert value == 'attachment' assert options['filename'] == 'index.txt' rv.close()
def get_project_image(project_id): project = Project.query.get(project_id) if project.image: return send_file(BytesIO(project.image), mimetype='image/jpg') else: # return default image return send_file('web/static/img/image_not_found.jpg', mimetype='image/jpg')
def post_convert(): cmds = g.cmds if 'file' in request.files: f = request.files['file'] fname = os.path.join(current_app.config['UPLOAD_FOLDER'], secure_filename(f.filename)) # Restricting file mimetypes to prevent XSS if not allowed_file(fname): err_msg = {"client_error": "File type not supported.", "more_info": "/#convert"} return error_response(400, err_msg) f.save(fname) res = process_file('%s %s' % (cmds, fname)) if isinstance(res, Response): return res else: # Optionally place processed file in LOBCDER destination path dest = request.values.get('dest', '') if len(dest): # err_res = put_lob_file(f, dest) err_res = put_lob_file(fname, dest) if err_res: return err_res # else if 'format' in g.params: fret = fname.rsplit('.', 1)[0] + '.' + g.params['format'] else: fret = fname return send_file(fret) else: return send_file(fname) else: err_msg = {"client_error": "File not posted.", "more_info": "/#convert"} return error_response(400, err_msg)
def get_image(): try: filename = "qrcode/" + request.args.get('id') if os.path.isfile(filename): return send_file(filename, mimetype='image/png') except: return send_file("bug.png", mimetype='image/png')
def cover_art(): # Use the track id to get the file path. # TODO: support for multiple query types is a matter of a few case statements status, res = get_entity(request, Track) if not status: return res res = res.folder if not res.has_cover_art or not os.path.isfile(os.path.join(res.path, 'cover.jpg')): return request.error_formatter(70, 'Cover art not found') size = request.args.get('size') if size: try: size = int(size) except: return request.error_formatter(0, 'Invalid size value') else: return send_file(os.path.join(res.path, 'cover.jpg')) im = Image.open(os.path.join(res.path, 'cover.jpg')) if size > im.size[0] and size > im.size[1]: return send_file(os.path.join(res.path, 'cover.jpg')) size_path = os.path.join(config.get('base', 'cache_dir'), str(size)) path = os.path.join(size_path, str(res.id)) if os.path.exists(path): return send_file(path) if not os.path.exists(size_path): os.makedirs(size_path) im.thumbnail([size, size], Image.ANTIALIAS) im.save(path, 'JPEG') return send_file(path, mimetype='image/jpeg;base64')
def admin(): if not g.user.is_admin(): log.warning(g.user.f_name + " tried to login as admin") abort(401) if request.args.get(CREATE_BILLS) is not None and request.args.get(CREATE_BILLS) == "1": if os.path.isfile("Ubersichten.zip"): os.remove("Ubersichten.zip") zipf = zipfile.ZipFile("Ubersichten.zip", "w", zipfile.ZIP_DEFLATED) for family in Familys.query.all(): f = pdfservice.generate_bill(family.f_name, COST_PER_PERSON) zipf.write(f, os.path.basename(f)) zipf.close() return send_file(os.path.abspath("Ubersichten.zip"), mimetype="zip", as_attachment=True) elif request.args.get(CREATE_TEILNEHMER) is not None and request.args.get(CREATE_TEILNEHMER) == "1": return send_file(pdfservice.generate_teilnehmerliste(), mimetype="text", as_attachment=True) else: form = FamilyLookupForm() form.familys.choices = [(family.f_name, family.f_name) for family in Familys.query.all()] # form.emailtype.choices = [(INVITE, INVITE), (REMEMBER, REMEMBER), (VERBINDLICH, VERBINDLICH)] form.emailtype.choices = [(INVITE, INVITE),(REMEMBER, REMEMBER), (VERBINDLICH, VERBINDLICH)] if form.validate_on_submit(): for family in request.form.getlist("familys"): fam = Familys.query.filter_by(f_name=family).first() emailtemplate = form.emailtype.data email = emailservice.create_mail("Hallo Familie " + fam.f_name + "!", fam.f_token, "http://holzner-web.net", "email-templates/"+emailtemplate+".template") emailservice.sendmail(fam.f_email, emailtemplate, email) flash("Emails sent") return redirect("admin") else: print(form.errors) return render_template("admin.html", title="Admin", CREATE_BILLS=CREATE_BILLS, CREATE_TEILNEHMER=CREATE_TEILNEHMER, form=form)
def get_project_image(project_id): project = Project.query.get(project_id) if project.image: return send_file(BytesIO(project.image), mimetype='image/jpg') else: # return default image for a project return send_file('static/img/project_default.jpg', mimetype='image/jpg')
def route_download(id, type): keys = os.path.join(os.path.split(__file__)[0], "purchases") with open(keys, "r") as keyfile: keys = map(lambda x: x.strip(), keyfile.readlines()) keys = map(lambda x: x.split(" "), keys) keys = set( [ key[1] for key in keys if (datetime.datetime.now() - datetime.datetime.strptime(key[0], "%Y-%m-%d-%H:%M:%S")) < datetime.timedelta(days=60) ] ) if id in keys: if type == "epub": return send_file("BuildYourOwnLisp.epub", mimetype="application/epub+zip") elif type == "mobi": return send_file("BuildYourOwnLisp.mobi", mimetype="application/x-mobipocket-ebook") elif type == "pdf": return send_file("BuildYourOwnLisp.pdf", mimetype="application/pdf") elif type == "tar": return send_file("BuildYourOwnLisp.tar.gz", mimetype="application/x-gtar") else: return redirect(url_for("route_page", page="invalid")) else: return redirect(url_for("route_page", page="invalid"))
def tiles(zoom, y, x): default = './data/JTileDownloader/USA/5/4/13.png' filename = './data/JTileDownloader/USA/%s/%s/%s.png' % (zoom, x, y) if os.path.isfile(filename): return send_file(filename) else: return send_file(default)
def topics(username): #个人博客列表 return send_file('templates/list.html')
def get(self): return send_file('report.txt', attachment_filename='report.txt')
def export_ratings(dataset=None): """Page to configure and download a report of ratings.""" # TODO: Check if add imgtype columns = [["Image", 1, 0], ["Subject", 0, 0], ["Session", 0, 0], ["Cohort", 0, 0], ["Rater", 0, 0], ["Rating", 1, 0], ["Comments", 0, 0], ["Timestamp", 0, 0]] form = ExportRatingsForm() public_ds = Dataset.query.filter_by(private=False) private_ds = Dataset.query.filter(Dataset.viewers.contains(current_user)) form.dataset.choices = [ds.name for ds in public_ds.union(private_ds)] # id, name, activated, read-only form.columns.choices = [[i, column[0], column[1], column[2]] for i, column in enumerate(columns)] # All raters all_raters = request.args.get('all_raters', 0, type=int) not_subs, not_sess, not_cohorts, not_comms = False, False, False, False if dataset is not None: ds_model = Dataset.query.filter_by(name=dataset).first_or_404() file_name = f'{ds_model.name}' form.columns.choices[1][3] = 0 \ if sum([bool([i.subject for i in ds_model.images])]) else 1 form.columns.choices[2][3] = 0 \ if sum([bool([i.session for i in ds_model.images])]) else 1 form.columns.choices[3][3] = 0 \ if sum([bool([i.cohort for i in ds_model.images])]) else 1 comm = [bool(r.comment) for r in ds_model.images.join(Rating).add_columns(Rating.comment)] subr = [bool(r.subratings.all()) for r in Rating.query.join(Image).filter(Image.dataset == ds_model)] form.columns.choices[6][3] = 0 if (sum(comm) or sum(subr)) else 1 if form.validate_on_submit(): query = Rating.query.\ join(Image).\ filter(Image.dataset_id == ds_model.id).\ order_by(Image.id.asc()).\ add_columns(Image.name, Rating.rating) rating_dict = OrderedDict() col_order = [int(order) for order in form.order.data] for col_name in [[val[1] for val in form.columns.choices][order] for order in col_order]: rating_dict[col_name] = None if "Subject" in rating_dict.keys(): query = query.add_columns(Image.subject) if "Session" in rating_dict.keys(): query = query.add_columns(Image.session) if "Cohort" in rating_dict.keys(): query = query.add_columns(Image.cohort) if "Rater" in rating_dict.keys(): query = query.join(Rater).add_columns(Rater.username) if "Comments" in rating_dict.keys(): query = query.add_columns(Rating.comment) if "Timestamp" in rating_dict.keys(): query = query.add_columns(Rating.timestamp) if int(form.rater_filter.data): query = query.filter(Rating.rater_id == current_user.id) file_name = f'{file_name}_{current_user.username}' else: file_name = f'{file_name}_all-raters' ratings = [] rating_codes = {0: 'Pending', 1: 'Pass', 2: 'Warning', 3: 'Fail'} for rating in query.all(): if "Image" in rating_dict.keys(): rating_dict['Image'] = rating.name if "Subject" in rating_dict.keys(): rating_dict['Subject'] = rating.subject if "Session" in rating_dict.keys(): rating_dict['Session'] = rating.session if "Cohort" in rating_dict.keys(): rating_dict['Cohort'] = rating.cohort if "Rating" in rating_dict.keys(): rating_dict['Rating'] = rating_codes[rating.rating] if "Rater" in rating_dict.keys(): rating_dict['Rater'] = rating.username if "Comments" in rating_dict.keys(): rating_dict['Comments'] = rating.comment if "Timestamp" in rating_dict.keys(): rating_dict['Timestamp'] = rating.timestamp.isoformat() + 'Z' ratings.append({k: v for k, v in rating_dict.items()}) path = os.path.join(current_app.config['ABS_PATH'], 'static/reports') if not os.path.isdir(path): os.makedirs(path) if form.file_type.data == "CSV": file = ('static/reports/' f'{file_name}_{datetime.now().date().isoformat()}.csv') with open(f'app/{file}', 'w', newline='') as csv_file: writer = csv.DictWriter(csv_file, rating_dict.keys()) writer.writerows(ratings) else: file = ('static/reports/' f'{file_name}_{datetime.now().date().isoformat()}.json') with open(f'app/{file}', 'w', newline='') as json_file: json.dump(ratings, json_file, indent=4) return send_file(file, as_attachment=True) return render_template('export_ratings.html', form=form, dataset=dataset, nsub=not_subs, nsess=not_sess, ncohort=not_cohorts, ncomms=not_comms, all_raters=all_raters, title='Downlad Ratings')
def index(): return flask.send_file('static/index.html', conditional=True)
def index(): file = io.BytesIO(b'somethingsomething') return flask.send_file(file, attachment_filename='filename', conditional=True)
def index(): return flask.send_file(StringIO("party like it's"), last_modified=last_modified, mimetype='text/plain')
def topics_detail(username, t_id): #博客内容详情 return send_file('templates/detail.html')
def change_info(username): #修改个人信息 return send_file('templates/change_info.html')
def cart(): #购物车页面 return send_file('templates/cart.html')
def topic_release(username): #发表博客 return send_file('templates/release.html')
def login(): #登录 return send_file('templates/login.html')
def login_callback(): #购物车页面 return send_file('templates/login_callback.html')
def snacks(): # 零食主页 return send_file('templates/snacks.html')
def register(): #注册 return send_file('templates/register.html')
def get_static(file): return send_file(f"users/static/{file}")
def info(): # 商品详情页 return send_file('templates/info.html')
def index(): return send_file(current_app.open_instance_resource('trees/index.html'))
def index(): #首页 return send_file('templates/index.html')
def apple_touch(): return send_file("assets/images/govuk-apple-touch-icon.png")
def get_video_thumbs(video_id): zipbuffer = VideoManager.get_instance().zip_video_thumbs(video_id=video_id) return send_file(zipbuffer, mimetype='application/zip'), 200
def cached_file(file_id): # 不考虑压缩文件的话,这里调用get file photo_file = get_pic_from_comress(file_id) file_name = photo_file['name'] ptype = file_name.split('.')[-1] file_path = photo_file['path'] img_open = photo_file['file'] if photo_file[ 'file'] is not None else file_path if file_ex2type(file_name) == 'video': return get_cover_for_video(file_name, file_path) if file_ex2type(file_name) == 'music': return send_file(file_path, mimetype=mimetypes.guess_type(file_name)[0], as_attachment=True, conditional=True) cn = hashlib.md5(file_path.encode()).hexdigest() cache = PHOTO_CATCH + f"/{cn}.{ptype}" if not os.path.exists(cache): img = Image.open( photo_file['file'] ) if photo_file['file'] is not None else Image.open(img_open) img.compression_quality = 50 width, height = img.size widpct = width * 1.0 / 480 heightpct = height * 1.0 / 640 dest_pct = max([widpct, heightpct]) resized_im = img.resize( (int(width / dest_pct), int(height / dest_pct)), Image.HAMMING) try: resized_im.save(cache) except: resized_im = resized_im.convert("RGB") resized_im.save(cache) resized_im.close() img.close() if cached_photo: return file_name, cache else: ''' 对于非缓存类型,也进行压缩,减小其大小 压缩为高度1024的图片 ''' re_cache = PHOTO_CATCH + f"/{cn}.1024.{ptype}" if not os.path.exists(re_cache): img = Image.open( photo_file['file'] ) if photo_file['file'] is not None else Image.open(img_open) img.compression_quality = 50 width, height = img.size dest_pct = height * 1.0 / 1024 resized_im = img.resize( (int(width / dest_pct), int(height / dest_pct)), Image.HAMMING) try: resized_im.save(re_cache) except: resized_im = resized_im.convert("RGB") resized_im.save(re_cache) resized_im.close() img.close() return file_name, re_cache
def apple_touch_152(): return send_file("assets/images/govuk-apple-touch-icon-152x152.png")
def humans(): return send_file("./static/humans.txt")
def favicon(): return send_file("assets/images/favicon.ico")
def test_api(): #测试 return send_file('templates/test_api.html')
def photo(file_id): ''' 对于需要缩略图的情况,这里先查找缓存,如果缓存未命中,生成缩略图后返回 缩略图为240*320 如果纵横比变化,取最大值 ''' cached_photo = request.args.get('cache', 'true') == 'true' if file_id == 0: return not_found() def cached_file(file_id): # 不考虑压缩文件的话,这里调用get file photo_file = get_pic_from_comress(file_id) file_name = photo_file['name'] ptype = file_name.split('.')[-1] file_path = photo_file['path'] img_open = photo_file['file'] if photo_file[ 'file'] is not None else file_path if file_ex2type(file_name) == 'video': return get_cover_for_video(file_name, file_path) if file_ex2type(file_name) == 'music': return send_file(file_path, mimetype=mimetypes.guess_type(file_name)[0], as_attachment=True, conditional=True) cn = hashlib.md5(file_path.encode()).hexdigest() cache = PHOTO_CATCH + f"/{cn}.{ptype}" if not os.path.exists(cache): img = Image.open( photo_file['file'] ) if photo_file['file'] is not None else Image.open(img_open) img.compression_quality = 50 width, height = img.size widpct = width * 1.0 / 480 heightpct = height * 1.0 / 640 dest_pct = max([widpct, heightpct]) resized_im = img.resize( (int(width / dest_pct), int(height / dest_pct)), Image.HAMMING) try: resized_im.save(cache) except: resized_im = resized_im.convert("RGB") resized_im.save(cache) resized_im.close() img.close() if cached_photo: return file_name, cache else: ''' 对于非缓存类型,也进行压缩,减小其大小 压缩为高度1024的图片 ''' re_cache = PHOTO_CATCH + f"/{cn}.1024.{ptype}" if not os.path.exists(re_cache): img = Image.open( photo_file['file'] ) if photo_file['file'] is not None else Image.open(img_open) img.compression_quality = 50 width, height = img.size dest_pct = height * 1.0 / 1024 resized_im = img.resize( (int(width / dest_pct), int(height / dest_pct)), Image.HAMMING) try: resized_im.save(re_cache) except: resized_im = resized_im.convert("RGB") resized_im.save(re_cache) resized_im.close() img.close() return file_name, re_cache file_name, file_path = cached_file(file_id) ''' 这里是直接获取原始文件的api影片播放页数从这个路径走 ''' if request.args.get('cache', 'true') == 'origin': photo_file = get_pic_from_comress(file_id) file_name = photo_file['name'] file_path = photo_file['path'] img_open = photo_file['file'] if photo_file[ 'file'] is not None else file_path mtype = mimetypes.guess_type( file_name)[0] if not file_name.endswith('flv') else 'video/x-flv' ''' 这里需要处理不支持的格式,目前暂时考虑使用ffmpeg转码输出 ''' return send_file(img_open, attachment_filename=file_name, mimetype=mtype, as_attachment=True, conditional=True) return send_file(file_path, mimetype=mimetypes.guess_type(file_name)[0], as_attachment=True, conditional=True)
def info(username): #个人信息 return send_file('templates/user_info.html')
def arbitrary_style_grpc(): # 1. Load Image filestr = flask.request.files.to_dict()['content_img'].read() npimg = np.fromstring(filestr, np.uint8) content_img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED) filestr = flask.request.files.to_dict()['style_img'].read() npimg = np.fromstring(filestr, np.uint8) style_img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED) # 2. Image Preprocess content_img = img_resize(content_img) style_img = img_resize(style_img) print("content_img size:", content_img.shape) print("style_img size:", style_img.shape) content_img_np = np.array(content_img).astype(np.float32) content_img_np = np.expand_dims( content_img_np, axis=0) # float32, (1, h, w, 3) representaiton style_img_np = np.array(style_img).astype(np.float32) style_img_np = np.expand_dims( style_img_np, axis=0) # float32, (1, h, w, 3) representaiton # 3. Prepare & Send Request interceptors = (RetryOnRpcErrorClientInterceptor( max_attempts=4, sleeping_policy=ExponentialBackoff(init_backoff_ms=100, max_backoff_ms=1600, multiplier=2), status_for_retry=(grpc.StatusCode.UNAVAILABLE, ), ), ) ip_port = "35.232.203.191:8500" channel_opt = [('grpc.max_send_message_length', 512 * 1024 * 1024), ('grpc.max_receive_message_length', 512 * 1024 * 1024)] channel = grpc.insecure_channel(ip_port, options=channel_opt) stub = prediction_service_pb2_grpc.PredictionServiceStub( grpc.intercept_channel(channel, *interceptors)) request = predict_pb2.PredictRequest() request.model_spec.name = "arbitary_style" # TODO change this to the model you're using request.model_spec.signature_name = "predict_images" request.inputs["content_img"].CopyFrom( tf.make_tensor_proto(content_img_np, shape=list(content_img_np.shape))) request.inputs["style_img"].CopyFrom( tf.make_tensor_proto(style_img_np, shape=list(style_img_np.shape))) response = stub.Predict( request, 200.0) # TODO change the request timeout, default is 10s # 4. Image Postprocess output_img = tf.make_ndarray( response.outputs['output_img'] ) # value range : [0-1], dtype float32, (1, H, W, 3) # output_img = output_img * 255 output_img = output_img.astype( np.uint8) # value range : [0-255], dtype : uint8, (1, H, W, 3) output_img = Image.fromarray(output_img[0]) output_img.save('test_gRPC_img2.jpg') # create file-object in memory file_object = io.BytesIO() # write PNG in file-object output_img.save(file_object, 'PNG') # move to beginning of file so `send_file()` it will read from start file_object.seek(0) return flask.send_file(file_object, mimetype='image/PNG')
def login_callback(): #授权登录 return send_file('templates/oauth_callback.html')
def change_password(username): #修改密码 return send_file('templates/change_password.html')