def return_iiif_content(barcode, rest, person): '''Return the manifest file for a given item.''' item = Item.get(Item.barcode == barcode) loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname) if loan and loan.state == 'active': record_request(barcode) url = _IIIF_BASE_URL + '/' + urls_restored(rest, barcode) if url in _IIIF_CACHE: content, ctype = _IIIF_CACHE[url] data = BytesIO(content) log(f'returning cached /iiif/{barcode}/{rest} for {person.uname}') return send_file(data, ctype = ctype, size = len(content)) # Read the data from our IIIF server instance & send it to the client. log(f'getting /iiif/{barcode}/{rest} from server') response, error = net('get', url) if not error: if url.endswith('json'): # Always rewrite URLs in any JSON files we send to the client. content = urls_rerouted(response.text, barcode).encode() ctype = 'application/json' else: content = response.content ctype = 'image/jpeg' _IIIF_CACHE[url] = (content, ctype) data = BytesIO(content) log(f'returning content of /iiif/{barcode}/{rest} for {person.uname}') return send_file(data, ctype = ctype, size = len(content)) else: log(f'error {str(error)} accessing {url}') return else: log(f'{person.uname} does not have {barcode} loaned out') redirect(f'{dibs.base_url}/notallowed')
def download(db): key = request.params.dict.get('Key') if key: key = key[0] if not key: return HTTPError(400, 'File Key is required') else: return HTTPError(400, 'File Key is required') for name in glob.glob( os.path.join(settings.STATIC_PATH, request.params.dict.get('token')[0], '*', '%s_*.zip' % key)): zf = zipfile.ZipFile(name) unp = list({name: zf.read(name) for name in zf.namelist()}.items())[0] cur_date = dt.datetime.utcnow() db.execute( 'INSERT INTO access_log (file_key, access_date) VALUES (?, ?)', (key, cur_date)) db.execute( 'UPDATE access_log SET last_access_date =\n' '(SELECT MAX(access_date) FROM access_log WHERE file_key = ?)\n' 'WHERE file_key = ?', (key, key)) # TODO: Use SQLAlchemy instead of raw SQL queries return send_file(BytesIO(unp[1]), filename=unp[0], attachment=True) return HTTPError(400, 'Wrong File Key')
def album(albumname, filename): filepath = "images/"+albumname+"/"+filename size = os.path.getsize(filepath) mtime = os.path.getmtime(filepath) fd = open(filepath, 'rb') return send_file(fd, ctype='image/jpeg', size=size, timestamp=mtime)
def album(albumname, filename): filepath = "images/" + albumname + "/" + filename size = os.path.getsize(filepath) mtime = os.path.getmtime(filepath) fd = open(filepath, 'rb') return send_file(fd, ctype='image/jpeg', size=size, timestamp=mtime)
def image_proxy(url): from get_sonarr_settings import get_sonarr_settings url_sonarr_short = get_sonarr_settings()[1] img_pil = Image.open( BytesIO(requests.get(url_sonarr_short + '/' + url).content)) img_buffer = BytesIO() img_pil.tobytes() img_pil.save(img_buffer, img_pil.format) img_buffer.seek(0) return send_file(img_buffer, ctype=img_pil.format)
def send_app_file(appid, path='index.html'): appdir = request.app.config['content.appdir'] app_path = os.path.join(appdir, appid + '.zip') if path.startswith('/'): path = path[1:] if not os.path.exists(appdir): abort(404) try: metadata, content = apps.extract_file(app_path, path, no_read=True) except KeyError as err: logging.error("<%s> Coult not extract '%s': %s", app_path, path, err) abort(404) filename = os.path.basename(path) return send_file(content, filename, metadata.file_size, os.stat(app_path)[stat.ST_MTIME])
def send_diags(): platform = request.app.config['platform.name'] timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') diag_file_name = 'diags_{}_{}.log.txt'.format(platform, timestamp) syslog_path = request.app.config['logging.syslog'] log_path = request.app.config['logging.output'] fsal_path = request.app.config['logging.fsal_log'] ondd_socket = request.app.config.get('ondd.socket') diag_data = generate_report(syslog_path, log_path, fsal_path, ondd_socket) return send_file(StringIO(diag_data), filename=diag_file_name, ctype='text/plain', attachment=True, charset='utf-8')
def index(): pages = get_request_int('pages',1) rows = get_request_int('rows',0) data = load_files(min(pages,100)) # max 100 pages if rows: data = data[:rows,:] H = np.array(data) H = np.log(H) fig = plt.figure() plt.imshow(H) sio = cStringIO.StringIO() plt.savefig(sio, format="png") response.set_header('Pragma', 'no-cache') response.set_header('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate') response.set_header('Expires', 'Thu, 01 Dec 1994 16:00:00 GMT') sio.seek(0) return send_file(sio, filename="chart.png", ctype="image/png")
def get(self): platform = self.config['platform.name'] timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') diag_file_name = 'diags_{}_{}.log.txt'.format(platform, timestamp) # gather log file paths that should be present in the report syslog_path = self.config['logging.syslog'] log_path = self.config['logging.output'] fsal_path = self.config['logging.fsal_log'] ondd_socket = self.config.get('ondd.socket') # prepare diag report from the gathered log files diag_data = generate_report(syslog_path, log_path, fsal_path, ondd_socket) return send_file(StringIO(diag_data), filename=diag_file_name, ctype='text/plain', attachment=True, charset='utf-8')
def content_file(content_id, filename): """ Serve file from zipball with specified id """ content_dir = request.app.config['content.contentdir'] zippath = downloads.get_zip_path(content_id, content_dir) try: metadata, content = downloads.get_file(zippath, filename, no_read=True) except downloads.ContentError as err: logging.error(err) abort(404) size = metadata.file_size timestamp = os.stat(zippath)[stat.ST_MTIME] archive = open_archive() if filename.endswith('.html') and archive.needs_formatting(content_id): logging.debug("Patching HTML file '%s' with Librarian stylesheet" % ( filename)) size, content = patch_content.patch(content.read()) content = StringIO(content.encode('utf8')) return send_file(content, filename, size, timestamp)
def send_app_file(appid, path='index.html'): appdir = request.app.config['content.appdir'] app_path = os.path.join(appdir, appid + '.zip') if path.startswith('/'): path = path[1:] if not os.path.exists(appdir): abort(404) try: content = zipballs.get_file(app_path, path) except zipballs.ValidationError as exc: logging.error("<{0}> Coult not extract '{1}': {2}".format(app_path, path, exc)) abort(404) else: filename = os.path.basename(path) timestamp = os.stat(app_path).st_mtime content_file = zipballs.StringIO(content) return send_file(content_file, filename, len(content), timestamp)
def return_iiif_manifest(barcode, person): '''Return the manifest file for a given item.''' item = Item.get(Item.barcode == barcode) loan = Loan.get_or_none(Loan.item == item, Loan.user == person.uname) if loan and loan.state == 'active': manifest_file = join(_MANIFEST_DIR, f'{barcode}-manifest.json') if not exists(manifest_file): log(f'{manifest_file} does not exist') return record_request(barcode) with open(manifest_file, 'r') as mf: adjusted_content = urls_rerouted(mf.read(), barcode) data = BytesIO(adjusted_content.encode()) size = len(adjusted_content) log(f'returning manifest for {barcode} for {person.uname}') return send_file(data, ctype = 'application/json', size = size) else: log(f'{person.uname} does not have {barcode} loaned out') redirect(f'{dibs.base_url}/notallowed') return
def do_download(): record = int(request.forms.get('record')) conn = sqlite3.connect('blob.db') c = conn.cursor() c.execute("select id, name, type, size, file from blob where id==?", (record, )) a = c.fetchone() conn.commit() c.close() # Took a hint here from https://github.com/morpheus65535/oscarr/blob/master/oscarr.py # Where he took an image file and wrote it first to bytes. Note sure seek is needed temp = BytesIO(a[4]) temp.seek(0) return send_file(BytesIO(a[4]), filename=a[1], ctype=a[2], size=a[3], attachment=True)
def downloadalbum(albumname, userkey, dummy): db = get_db() cur = db.cursor() cur.execute("SELECT name, url FROM album WHERE url=?", (albumname, )) album_info = cur.fetchone() if album_info is None: raise "album not existing" if check_user_on_album(userkey, albumname) is None: raise "user not on album" album_path = './images/' + albumname + '/' zip_file_path = zip_album(album_path, albumname) size = os.path.getsize(zip_file_path) mtime = os.path.getmtime(zip_file_path) fd = open(zip_file_path, 'rb') return send_file(fd, filename=albumname+'.zip', ctype='application/zip', size=size, timestamp=mtime)
def content_zipball(content_id): """ Serve zipball with specified id """ zball = zipballs.StringIO(prepare_zipball(content_id)) filename = '{0}.zip'.format(content_id) return send_file(zball, filename, attachment=True)
def get(self): device_id_file = self.config['analytics.device_id_file'] db = exts.databases.librarian _, payload = get_payload(db, device_id_file, limit=None) filename = '{}.stats'.format(utcnow().isoformat()) return send_file(StringIO(payload), filename, attachment=True)