def static_handler(request): path = request.urlmatch.group('static') # TODO: fix security checks, maybe preload static? target_path = os.path.normpath(os.path.join(request.store.root, path)) app = FileApp(target_path) app.cache_control(public=True, max_age=3600) return request.wsgi_pass(app)
def __call__(self, environ, start_response): request_path = environ.get('PATH_INFO', '') app = self.cached_apps.get(request_path) if app: return app(environ, start_response) if not request_path.endswith('/'): relative_request_path = request_path.lstrip('/') for root_dir, max_cache in self.path_items: file_asset_path = normcase(join(root_dir, relative_request_path)) if isfile(file_asset_path): content_type, _ = guess_type(file_asset_path) if content_type in self.utf8_mimetypes: content_type += '; charset=utf-8' app = FileApp(file_asset_path, content_type=content_type) if max_cache: app.cache_control(max_age=max_cache) else: app.cache_control(max_age=0) self.cached_apps[request_path] = app return app(environ, start_response) return self.app(environ, start_response)
def __call__(self, environ, start_response): request_path = environ.get('PATH_INFO', '') # check if the request is for static files at all path_parts = request_path.strip('/').split('/', 2) if len(path_parts) == 3 and path_parts[0] in ['play', 'game-meta']: slug = path_parts[1] game = self.game_list.get_by_slug(slug) if game and game.path.is_set(): asset_path = path_parts[2] file_asset_path = normpath(join(get_absolute_path(game.path), asset_path)) def build_file_iter(f, block_size): return StaticFileIter(file_asset_path, normpath(join(slug, asset_path)), f, block_size) def remove_ranges_start_response(status, headers, exc_info=None): if status == '200 OK': headers = [t for t in headers if t[0] != 'Accept-Ranges' and t[0] != 'Content-Range'] return start_response(status, headers, exc_info) # check if the request is already cached app = self.cached_apps.get(request_path) if app: environ['wsgi.file_wrapper'] = build_file_iter try: return app(environ, remove_ranges_start_response) except OSError as e: LOG.error(e) elif access(file_asset_path, R_OK): content_type, _ = guess_type(file_asset_path) if content_type in self.utf8_mimetypes: content_type += '; charset=utf-8' app = FileApp(file_asset_path, content_type=content_type) if asset_path.startswith('staticmax'): app.cache_control(max_age=self.staticmax_max_age) else: app.cache_control(max_age=0) self.cached_apps[request_path] = app environ['wsgi.file_wrapper'] = build_file_iter return app(environ, remove_ranges_start_response) start_response( '404 Not Found', [('Content-Type', 'text/html; charset=UTF-8'), ('Content-Length', '0')] ) return [''] return self.app(environ, start_response)
def __init__(self, rootpath, bundle, filenames, ignores): # Let FileApp determine content_type and encoding based on bundlename. FileApp.__init__(self, bundle) self.filenames = [] for filename in filenames: fullpath = os.path.join(rootpath, filename) if not os.path.normpath(fullpath).startswith(rootpath): # Raising forbidden here would expose private information. raise webob.exc.HTTPNotFound() # pragma: no cover if not os.path.exists(fullpath): raise webob.exc.HTTPNotFound() self.filenames.append(fullpath)
def __init__(self, path, digest, filename=None): h = {} if not filename is None: (type, encoding) = mimetypes.guess_type(filename) if not type is None: h['Content-Type'] = type #if not encoding is None: # h['Content-Encoding'] = encoding expires = datetime.datetime.now() + datetime.timedelta(seconds = int(config['app_conf']['expires.archive.file'])) h['Expires'] = wsgiref.handlers.format_date_time( time.mktime( expires.timetuple() )) h['Cache-Control'] = 'public, max-age=%d'%int(config['app_conf']['expires.archive.file']) FileApp.__init__(self, path, **h) self.digest = digest
def make_app(self, filename): # set headers so that static content can be cached headers = [ ("Cache-Control", "public,max-age=%d" % int(60 * 60 * 24 * 365)), ("Vary", "Accept-Encoding"), ] return FileApp(filename, headers)#, content_type='application/octetstream')
def preview(self, model_uniq, args): class_id = int(args.get('class', -1)) sample_id = int(args.get('sample', -1)) log.debug('Preview model %s, class_id %s, sample_id %s', model_uniq, class_id, sample_id) # if class_id < 0: # response.headers['Content-Type'] = 'text/xml' # return '<model />' # if sample_id < 0: # response.headers['Content-Type'] = 'text/xml' # return '<class />' # if asking for a sample from a specific class if class_id >= 0 and sample_id >= 0: # load thumbnail for requested class and sample_id model = self.get_model(model_uniq) path = os.path.join(model.path, 'class_{0:05d}'.format(class_id)) thumbnail = os.path.join(path, 'sample_{0:05d}.png'.format(sample_id)) if not os.path.exists(thumbnail): _mkdir(path) model.cache_sample_preview(class_id, sample_id, thumbnail) # if asking for a model's thumbnail elif class_id < 0 or sample_id < 0: model = self.get_model(model_uniq) thumbnail = '%s/thumbnail.svg' % model.path return forward( FileApp( thumbnail, content_type='image/png', #content_disposition=disposition, ).cache_control(max_age=60 * 60 * 24 * 7 * 6)) # 6 weeks
def return_from_workdir(self, table, resource_list): """ Returns a hdf5 file from the workdir @param: table - workdir table object that allows access to the workdir table created by the feature service @param: resource_list - the resource lists object containing all the resources proccessed on during the request @yield: fileapp object with path set to the hdf5 file in the feature workdir """ # since the uncached table is already saved in the workdir the file is just # returned try: disposition = 'attachment; filename="%s"' % ( table.filename).encode('ascii') except UnicodeEncodeError: disposition = 'attachment; filename="%s"; filename*="%s"' % ( (table.filename).encode('utf8'), (table.filename).encode('utf8')) #waits table that is being constructed with Locks(table.path): pass return forward( FileApp(table.path, allowed_methods=('GET', 'POST'), content_type=self.content_type, content_disposition=disposition))
def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO', '') script_name = environ.get('SCRIPT_NAME', '') for filename in ['bell-ascending.png', 'bell-descending.png']: if path_info == '/.cowbell/'+ filename: app = FileApp(os.path.join(os.path.dirname(__file__), filename)) return app(environ, start_response) type = [] body = [] def repl_start_response(status, headers, exc_info=None): ct = header_value(headers, 'content-type') if ct and ct.startswith('text/html'): type.append(ct) remove_header(headers, 'content-length') start_response(status, headers, exc_info) return body.append return start_response(status, headers, exc_info) app_iter = self.app(environ, repl_start_response) if type: # Got text/html body.extend(app_iter) body = ''.join(body) body = insert_head(body, self.javascript.replace('__SCRIPT_NAME__', script_name)) body = insert_body(body, self.resources.replace('__SCRIPT_NAME__', script_name)) return [body] else: return app_iter
def generate_download_link(self, content, filename, extension): """Generate the header and the download link for the new translated file. This allows the user to download the new file directly without store the file into the database. """ # Set the folder for the temporary file tmp_file_url = '/tmp/' + filename # Decode the content of the new translated file decoded_content = base64.b64decode(content) # Generate the new file in the tmp folder file = open(tmp_file_url, "wb") file.write(decoded_content) file.close() # Set the content of the header to return the download link headers = [ ('Content-Disposition', 'attachment; filename=\"' + filename + '\"'), ] if extension == 'csv': headers.append(('Content-Type', 'text/csv')) elif extension == 'json': headers.append(('Content-Type', 'application/json')) elif extension == 'xml': headers.append(('Content-Type', 'application/xml')) else: headers.append(('Content-Type', 'text/plain')) # Generate the response to download the new file into the web browser fapp = FileApp(tmp_file_url, headers=headers) return fapp(request.environ, self.start_response)
def serve_entry_point(self, node, default='Entry point was not found...', **kw): """Provide a general way to serve an entry point""" log.debug('Serving entry point: %s', node) if isinstance(node, str) is True: node = self.module_xml.xpath(node) text = default if len(node) > 0: # Found at least one xpath match node = node[0] log.debug('Node: %s', etree.tostring(node)) type = node.get('type', None) if type == 'file': path = self.filepath(node.get('value')) log.debug('Serving file: %s', path) if os.path.exists(path): return forward( FileApp(path).cache_control(max_age=60 * 60 * 24 * 7 * 6)) else: text = node.get('value', None) if node.get('value', None) is None: # Using a <value><![CDATA]</value> text = (node[0].text) if text is None: abort(404) return text
def help(self): ''' This downloads the Manual The filename will be the 3. part,ID https://172.16.200.6/manage/help/somehelp.pdf The file is downloaded through pylons! ''' try: directory = config.get("linotpManual.Directory", "/usr/share/doc/linotp") default_filename = config.get("linotpManual.File", "LinOTP_Manual-en.pdf") headers = [] route_dict = request.environ.get('pylons.routes_dict') filename = route_dict.get('id') if not filename: filename = default_filename + ".gz" headers = [('content-Disposition', 'attachment; filename=\"' + default_filename + '\"'), ('content-Type', 'application/x-gzip') ] from paste.fileapp import FileApp wsgi_app = FileApp("%s/%s" % (directory, filename), headers=headers) Session.commit() return wsgi_app(request.environ, self.start_response) except Exception as e: log.exception("[help] Error loading helpfile: %r" % e) Session.rollback() return sendError(response, e) finally: Session.close()
def serve_arpa(self, id): """Serve the generated ARPA file of the morpheme language model. :URL: ``PUT /morphemelanguagemodels/serve_arpa/id`` :param str id: the ``id`` value of a morpheme language model. :returns: a stream of bytes -- the ARPA file of the LM. """ lm = Session.query(MorphemeLanguageModel).get(id) if lm: arpa_path = lm.get_file_path('arpa') if os.path.isfile(arpa_path): if authorized_to_access_arpa_file(session['user'], lm): return forward( FileApp(arpa_path, content_type='text/plain')) else: response.status_int = 403 return json.dumps(h.unauthorized_msg) else: response.status_int = 404 return json.dumps({ 'error': 'The ARPA file for morpheme language model %s has not been compiled yet.' % id }) else: response.status_int = 404 return json.dumps({ 'error': 'There is no morpheme language model with id %s' % id })
def file(self, label): exists = self.ofs.exists(BUCKET, label) if not exists: # handle erroneous trailing slash by redirecting to url w/o slash if label.endswith('/'): label = label[:-1] # This may be best being cached_url until we have moved it into # permanent storage file_url = h.url_for('storage_file', label=label) h.redirect_to(file_url) else: abort(404) file_url = self.ofs.get_url(BUCKET, label) if file_url.startswith("file://"): metadata = self.ofs.get_metadata(BUCKET, label) filepath = file_url[len("file://"):] headers = { # 'Content-Disposition':'attachment; filename="%s"' % label, 'Content-Type': metadata.get('_format', 'text/plain') } fapp = FileApp(filepath, headers=None, **headers) return fapp(request.environ, self.start_response) else: h.redirect_to(file_url.encode('ascii', 'ignore'))
def servefile(self, id, file_id): """Return the corpus as a file in the format specified in the URL query string. :URL: ``PUT /corpora/id/servefile/file_id``. :param str id: the ``id`` value of the corpus. :param str file_id: the ``id`` value of the corpus file. :returns: the file data """ corpus = Session.query(Corpus).get(id) if corpus: try: corpus_file = filter(lambda cf: cf.id == int(file_id), corpus.files)[0] corpus_file_path = os.path.join(get_corpus_dir_path(corpus), '%s.gz' % corpus_file.filename) if authorized_to_access_corpus_file(session['user'], corpus_file): return forward( FileApp(corpus_file_path, content_type='application/x-gzip')) else: response.status_int = 403 return json.dumps(h.unauthorized_msg) except Exception: response.status_int = 400 return json.dumps({ 'error': 'Unable to serve corpus file %d of corpus %d' % (file_id, id) }) else: response.status_int = 404 return json.dumps({'error': 'There is no corpus with id %s' % id})
def job_export(request): id = request.matchdict['job'] session = DBSession() job = session.query(Job).get(id) import shapefile w = shapefile.Writer(shapefile.POLYGON) w.field('checkin', 'N', 1, 0) for tile in job.tiles: polygon = tile.to_polygon(4326) coords = polygon.exterior.coords parts = [[[x, y] for (x, y) in coords]] w.poly(parts=parts) w.record(tile.checkin) # FIXME we should a temp directory w.save('/tmp/tiles') import zipfile myzip = zipfile.ZipFile('/tmp/tiles.zip', 'w', zipfile.ZIP_DEFLATED) myzip.write('/tmp/tiles.shp', job.title + '/tiles.shp') myzip.write('/tmp/tiles.dbf', job.title + '/tiles.dbf') myzip.write('/tmp/tiles.shx', job.title + '/tiles.shx') myzip.close() content_disposition = 'attachment; filename=export.zip' return request.get_response( FileApp('/tmp/tiles.zip', **{"Content-Disposition": content_disposition}))
def servecompiled(self, id): """Serve the compiled foma script of the morphophonology FST of the morphological parser. :URL: ``PUT /morphologicalparsers/servecompiled/id`` :param str id: the ``id`` value of a morphological parser. :returns: a stream of bytes -- the compiled morphological parser script. """ parser = Session.query(MorphologicalParser).get(id) if parser: if h.foma_installed(): binary_path = parser.get_file_path('binary') if os.path.isfile(binary_path): return forward(FileApp(binary_path)) else: response.status_int = 400 return json.dumps({ 'error': 'The morphophonology foma script of ' 'MorphologicalParser %d has not been compiled yet.' % parser.id }) else: response.status_int = 400 return json.dumps( {'error': 'Foma and flookup are not installed.'}) else: response.status_int = 404 return json.dumps( {'error': 'There is no morphological parser with id %s' % id})
def serve_file(id, reduced=False): """Serve the content (binary data) of a file. :param str id: the ``id`` value of the file whose file data will be served. :param bool reduced: toggles serving of file data or reduced-size file data. """ file = Session.query(File).options(subqueryload(File.parent_file)).get(id) if getattr(file, 'parent_file', None): file = file.parent_file elif getattr(file, 'url', None): response.status_int = 400 return json.dumps({'error': u'The content of file %s is stored elsewhere at %s' % (id, file.url)}) if file: files_dir = h.get_OLD_directory_path('files', config=config) if reduced: filename = getattr(file, 'lossy_filename', None) if not filename: response.status_int = 404 return json.dumps({'error': u'There is no size-reduced copy of file %s' % id}) file_path = os.path.join(files_dir, 'reduced_files', filename) else: file_path = os.path.join(files_dir, file.filename) unrestricted_users = h.get_unrestricted_users() if h.user_is_authorized_to_access_model(session['user'], file, unrestricted_users): return forward(FileApp(file_path)) else: response.status_int = 403 return json.dumps(h.unauthorized_msg) else: response.status_int = 404 return json.dumps({'error': 'There is no file with id %s' % id})
def proxy_to_file(self, request, dest): """Handle local ``file:`` URLs""" orig_base = request.application_url ## FIXME: security restrictions here? assert dest.startswith('file:') if '?' in dest: dest = dest.split('?', 1)[0] filename = url_to_filename(dest) rest = posixpath.normpath(request.path_info) proxied_url = dest.lstrip('/') + '/' + urllib.parse.quote( rest.lstrip('/')) ## FIXME: handle /->/index.html filename = filename.rstrip('/') + '/' + rest.lstrip('/') if os.path.isdir(filename): if not request.path.endswith('/'): new_url = request.path + '/' if request.query_string: new_url += '?' + request.query_string resp = exc.HTTPMovedPermanently(location=new_url) return resp, orig_base, dest, proxied_url ## FIXME: configurable? StaticURLParser? for base in ['index.html', 'index.htm']: if os.path.exists(os.path.join(filename, base)): filename = os.path.join(filename, base) break else: resp = exc.HTTPNotFound( "There was no index.html file in the directory") if not os.path.exists(filename): resp = exc.HTTPNotFound("The file %s could not be found" % filename) else: app = FileApp(filename) resp = request.get_response(app) return resp, orig_base, dest, proxied_url
def guess_type(self): # add UTF-8 by default to text content-types guess = PasteFileApp.guess_type(self) content_type = guess[0] if content_type and "text/" in content_type and "charset=" not in content_type: content_type += "; charset=UTF-8" return (content_type, guess[1])
def __call__(self, environ, start_response): path = [ part for part in environ.get('PATH_INFO', '').split('/') if part ] if len(path) > 2: raise ValueError, "too many components in url" if len(path) > 0 and path[-1] == 'index.html': path.pop() path_len = len(path) if path_len == 0: filename = self.checkBaseIndex() elif path_len == 1: if path[0] == "favicon.ico": return HTTPNotFound()(environ, start_response) filename = self.checkPackageIndex(path[0]) else: filename = self.checkEggFor(path[0], path[1]) if filename is None: return HTTPNotFound()(environ, start_response) return FileApp(filename)(environ, start_response)
def _download_file(self, res, label): # We need this as a resource object to check access so create a dummy # obj and trick CKAN resource = model.Resource() for k in res.keys(): setattr(resource, k, res[k]) context = {'model': model, 'session': model.Session, 'user': c.user or c.author, 'for_view': True, 'auth_user_obj': c.userobj, 'resource': resource} data_dict = {'id': resource.id} try: logic.check_access('resource_show', context, data_dict) except logic.NotAuthorized: redirect_url = h.url_for(controller='user', action='login', came_from=resource.url) r = generate_response(303, u'Not authorized to read file ' + resource.id, other_headers={'Location': redirect_url, 'X-CKAN-Error': '403 Access Denied'}) return r exists = self.ofs.exists(BUCKET, label) if not exists: # handle erroneous trailing slash by redirecting to url w/o slash if label.endswith('/'): label = label[:-1] # This may be best being cached_url until we have moved it into # permanent storage file_url = h.url_for('storage_file', label=label) h.redirect_to(file_url) else: # abort(404) r = generate_response(404, u'File not found') return r file_url = self.ofs.get_url(BUCKET, label) if file_url.startswith("file://") or file_url.endswith('xlsx'): metadata = self.ofs.get_metadata(BUCKET, label) filepath = file_url[len("file://"):] headers = { # 'Content-Disposition':'attachment; filename="%s"' % label, 'Pragma': 'no-cache', 'Cache-Control': 'max-age=0, no-store, no-cache', 'Content-Type': metadata.get('_format', 'text/plain')} if resource.name: res_name = resource.name.replace('"', '_') res_name_encoded = res_name.encode('utf-8', 'ignore') file_name, file_extension = os.path.splitext(res_name_encoded) if file_extension == '' and resource.format: file_name = file_name + '.' + resource.format else: file_name = res_name_encoded headers[ 'Content-Disposition'] = 'inline; filename="{}"'.format(file_name) fapp = FileApp(filepath, headers=None, **headers) return fapp(request.environ, self.start_response) else: h.redirect_to(file_url.encode('ascii', 'ignore'))
def retrieve_temp(self, path): """retrieve_temp action is referenced by the <a> button rendered in /derived/file/export.html. """ path = os.path.join(config['app_conf']['temporary_store'], path) app = FileApp(path) return forward(app)
def retrieve(self, path): """retrieve action is referenced by the <a>, <img>, <audio>, <video>, <embed>, etc. tags. """ path = os.path.join(config['app_conf']['permanent_store'], path) app = FileApp(path) return forward(app)
def archivefile(self, repo_name, fname): fileformat = None revision = None ext = None subrepos = request.GET.get('subrepos') == 'true' for a_type, ext_data in settings.ARCHIVE_SPECS.items(): archive_spec = fname.split(ext_data[1]) if len(archive_spec) == 2 and archive_spec[1] == '': fileformat = a_type or ext_data[1] revision = archive_spec[0] ext = ext_data[1] try: dbrepo = RepoModel().get_by_repo_name(repo_name) if dbrepo.enable_downloads is False: return _('downloads disabled') if c.rhodecode_repo.alias == 'hg': # patch and reset hooks section of UI config to not run any # hooks on fetching archives with subrepos for k, v in c.rhodecode_repo._repo.ui.configitems('hooks'): c.rhodecode_repo._repo.ui.setconfig('hooks', k, None) cs = c.rhodecode_repo.get_changeset(revision) content_type = settings.ARCHIVE_SPECS[fileformat][0] except ChangesetDoesNotExistError: return _('Unknown revision %s') % revision except EmptyRepositoryError: return _('Empty repository') except (ImproperArchiveTypeError, KeyError): return _('Unknown archive type') fd, _archive_name = tempfile.mkstemp(suffix='rcarchive') with open(_archive_name, 'wb') as f: cs.fill_archive(stream=f, kind=fileformat, subrepos=subrepos) content_disposition = 'attachment; filename=%s-%s%s' \ % (repo_name, revision[:12], ext) content_length = os.path.getsize(_archive_name) headers = [('Content-Disposition', str(content_disposition)), ('Content-Type', str(content_type)), ('Content-Length', str(content_length))] class _DestroyingFileWrapper(_FileIter): def close(self): self.file.close os.remove(self.file.name) request.environ['wsgi.file_wrapper'] = _DestroyingFileWrapper fapp = FileApp(_archive_name, headers=headers) return fapp(request.environ, self.start_response)
def public(self, *path, **kw): """Deliver static content for the Module""" log.debug("in Static path=%s kw=%s", path, kw) static_path = os.path.join(self.path, 'public', *path) if os.path.exists(static_path): return forward( FileApp(static_path).cache_control(max_age=60 * 60 * 24 * 7 * 6)) raise abort(404)
def as_text(cls, slug, username, key): filepath = join(cls.datapath, slug, username, '%s.txt' % key) headers = [('Content-Type', 'text/plain'), ('Content-Disposition', 'attachment; filename=%s' % key)] try: text = forward(FileApp(filepath, headers)) except OSError: abort(404, 'Game does not exist: %s' % slug) else: return text
def download_mapfile(self, id): map = self._get_map_from_user_by_id(c.user, id) if map is None: abort(404) filename = os.path.join(config['mapfiles_dir'], map.filepath) fapp = FileApp( filename, **{ "content_type": "text/plain", "Content-Disposition": "attachment; filename=" + filename }) return fapp(request.environ, self.start_response)
def statistics_csv_view(request): statistics_folder = get_setting(request.context, 'statistics_folder') csv_file = request.matchdict.get('csv_file') if not csv_file.endswith('.csv'): raise NotFound() path = os.path.join(statistics_folder, csv_file) if not os.path.exists(path): raise NotFound() return request.get_response(FileApp(path).get)
def _serve_file(self, filepath): user_filename = filepath.split('/')[-1].encode('ascii', 'ignore') file_size = os.path.getsize(filepath) headers = [('Content-Disposition', 'attachment; filename=\"%s\"' % user_filename), ('Content-Type', 'text/plain'), ('Content-Length', str(file_size))] fapp = FileApp(filepath, headers=headers) return fapp(request.environ, self.start_response)
def resource_download(self, id, resource_id): """ Download file """ from paste.fileapp import FileApp from paste.fileapp import DataApp import urllib # TODO: Remove this from here fpath = '/srv/ckan-data/files' context = { 'model': model, 'session': model.Session, 'user': c.user or c.author } try: c.resource = get_action('resource_show')(context, { 'id': resource_id }) c.package = get_action('package_show')(context, {'id': id}) # required for nav menu c.pkg = context['package'] c.resource_json = json.dumps(c.resource) c.pkg_dict = c.package except NotFound: abort(404, _('Resource not found')) except NotAuthorized: abort(401, _('Unauthorized to read resource %s') % id) elastic_search = self.before_view_resource(c.pkg_dict['name'], c.resource['name']) if 'arquivo' not in elastic_search: # Not found. Return an error message abort(404, _('Resource not found')) filename = '%s/%s' % (fpath, elastic_search['arquivo']) file_size = os.path.getsize(filename) headers = [(str('Content-Disposition'), str('attachment; filename=\"' + elastic_search['arq_original'] + '\"')), (str('Content-Type'), str('text/plain')), (str('Content-Length'), str(file_size))] '''fapp = FileApp(filename, headers=headers) return fapp(request.environ, self.start_response)''' url = 'http://www.aquabarra.com.br/artigos/treinamento/Antropometria.pdf' filename, headers2 = urllib.urlretrieve(url) fapp = FileApp(filename, headers) return fapp(request.environ, self.start_response)
def __call__(self, environ, start_response): request_path = environ.get('PATH_INFO', '') app = self.cached_apps.get(request_path) if app: return app(environ, start_response) if not request_path.endswith('/'): relative_request_path = request_path.lstrip('/') for root_dir, max_cache in self.path_items: file_asset_path = normcase( join(root_dir, relative_request_path)) if isfile(file_asset_path): content_type, _ = guess_type(file_asset_path) if content_type in self.utf8_mimetypes: content_type += '; charset=utf-8' app = FileApp(file_asset_path, content_type=content_type) if max_cache: app.cache_control(max_age=max_cache) else: app.cache_control(max_age=0) self.cached_apps[request_path] = app return app(environ, start_response) return self.app(environ, start_response)
def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO', '') if not path_info: # See if this is a static file hackishly mapped. if os.path.exists(self.directory) and os.path.isfile(self.directory): app = FileApp(self.directory) if self.cache_seconds: app.cache_control(max_age=int(self.cache_seconds)) return app(environ, start_response) return self.add_slash(environ, start_response) if path_info == '/': # @@: This should obviously be configurable filename = 'index.html' else: filename = request.path_info_pop(environ) full = os.path.join(self.directory, filename) if not os.path.exists(full): return self.not_found(environ, start_response) if os.path.isdir(full): # @@: Cache? return self.__class__(full)(environ, start_response) if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/': return self.error_extra_path(environ, start_response) if_none_match = environ.get('HTTP_IF_NONE_MATCH') if if_none_match: mytime = os.stat(full).st_mtime if str(mytime) == if_none_match: headers = [] ETAG.update(headers, mytime) start_response('304 Not Modified', headers) return [''] # empty body app = FileApp(full) if self.cache_seconds: app.cache_control(max_age=int(self.cache_seconds)) return app(environ, start_response)
def getfile_(appid, breadid=None): h.logm("DBG",5,"ACTION "+ h.getcalled()); filename = getfilepath(appid, breadid); h.logm("INF",5, 'filename %s' % filename); headers = [('Content-Disposition', 'attachment; filename=\"' + filename + '\"'), ('Content-Type', 'application/octet-stream'), ('Content-Length', str(os.path.getsize(filename)))]; h.logm("INF",5, 'headers ' + str(headers)); # return FileApp(filename, headers=headers); return FileApp(filename, headers=headers)
def _send_file_response(self, filepath, resource_name): user_filename = '_'.join(filepath.split('/')[-2:]) file_size = os.path.getsize(filepath) headers = [('Content-Disposition', 'attachment; filename=\"exported_geometry.zip\"'),#Avoid unicode issues: + resource_name + '.zip\"'), ('Content-Type', 'text/plain'), ('Content-Length', str(file_size))] from paste.fileapp import FileApp fapp = FileApp(filepath, headers=headers) return fapp(request.environ, self.start_response)
def download(self): file = request.params['file'] filename = os.path.join( config['app_conf']['uploads_dir'], os.path.basename(file) ) if not os.path.exists(filename): abort(404) response.headers['Content-Disposition'] = 'attachment; filename="%s"'%( str(file) ) wsgi_app = FileApp(filename) return wsgi_app(request.environ, self.start_response)