def send_pdf(): h = Headers() h.add('Content-type', 'application/pdf', charset='utf8') h.add('Content-disposition', 'attachment', filename='martin_fierro.pdf') with open(os.path.join(os.path.dirname(__file__), 'static', 'martin_fierro.pdf'), 'r') as f: data = f.read() return Response(data, headers=h)
def match_download(id): match = model.Match.get_by_id(id) match_data = model.MatchData.get_by_id(id) abort_if(not match) abort_if(not match_data) data = match_data.raw_data abort_if(not data) print len(data) from werkzeug import Headers import time headers = Headers() headers.add('Content-Disposition', 'attachment', filename=match.filename) rv = current_app.response_class( data, mimetype='application/octet-stream', headers=headers, direct_passthrough=True, ) rv.cache_control.public = True rv.cache_control.max_age = 86400 rv.expires = int(time.time() + 86400) return rv
def admin_download_benchmark(database, category, user_dir, filename): directory = os.path.join(config.UPLOAD_FOLDER, database) import mimetypes headers = Headers() headers.add('Content-Type', mimetypes.guess_type(filename)) headers.add('Content-Disposition', 'attachment', filename=secure_filename(filename)) return Response(response=open(os.path.join(directory, category, user_dir, filename), 'rb'), headers=headers)
def no_cache_js(): h = Headers() h.add('Content-type', 'application/javascript') response = Response(open(os.path.join(os.path.dirname(__file__), 'static', 'mootools.js'), 'r'), headers=h) etag = hashlib.sha1(str(random.randint(0,100000))).hexdigest() response.set_etag(etag) return response
def _output(content, serve=True): """Output the content in the datastore as a HTTP Response""" headers = Headers() if content.content_type: headers['Content-Type'] = content.content_type last_modified = content.last_modified.strftime(HTTP_DATE_FMT) headers.add('Last-Modified', last_modified) for header in content.headers: key, value = header.split(':', 1) headers[key] = value.strip() if serve: response = Response(content.body, content_type=content.content_type, headers=headers, status=content.status) else: response = Response(status=304) return response
def __init__(self, resp, content): #: a :class:`~werkzeug.Headers` object with the response headers #: the application sent. self.headers = Headers(resp) #: the raw, unencoded content from the server self.raw_data = content #: the parsed content from the server self.data = parse_response(resp, content, strict=True)
def json_response(self): serializer = Serializer() prepared_query = self.prepare_query() def generate(): i = prepared_query.count() yield '[\n' for obj in prepared_query: i -= 1 yield json.dumps(serializer.serialize_object(obj, prepared_query.query)) if i > 0: yield ',\n' yield '\n]' headers = Headers() headers.add('Content-Type', 'application/javascript') headers.add('Content-Disposition', 'attachment; filename=export.json') return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def configuration_runs(database, experiment_id): db = models.get_database(database) or abort(404) experiment = db.session.query(db.Experiment).get(experiment_id) or abort(404) if not experiment.configuration_scenario: abort(404) solver_configs = [sc for sc in experiment.solver_configurations if sc.solver_binary == experiment.configuration_scenario.solver_binary] solver_config_ids = [sc.idSolverConfig for sc in solver_configs] configurable_parameters = [p.parameter for p in experiment.configuration_scenario.parameters if p.configurable and p.parameter.name not in ('instance', 'seed')] configurable_parameters_ids = [p.idParameter for p in configurable_parameters] parameter_instances = db.session.query(db.ParameterInstance).options(joinedload('parameter')).filter( db.ParameterInstance.SolverConfig_idSolverConfig.in_(solver_config_ids)).all() instances_by_id = dict((i.idInstance, i) for i in experiment.get_instances(db)) instance_properties = [p for p in db.session.query(db.Property) if p.is_instance_property()] parameter_values = dict() for pv in parameter_instances: if pv.Parameters_idParameter not in configurable_parameters_ids: continue if pv.SolverConfig_idSolverConfig not in parameter_values: parameter_values[pv.SolverConfig_idSolverConfig] = dict() parameter_values[pv.SolverConfig_idSolverConfig][pv.Parameters_idParameter] = pv.value results, _, _ = experiment.get_result_matrix(db, experiment.solver_configurations, experiment.get_instances(db), cost=experiment.defaultCost) csv_response = StringIO.StringIO() csv_writer = csv.writer(csv_response) csv_writer.writerow( [p.name for p in configurable_parameters] + [p.name for p in instance_properties] + ['par1', 'censored']) for idInstance in results: for idSolverConfig in results[idInstance]: for run in results[idInstance][idSolverConfig]: csv_writer.writerow( [parameter_values[idSolverConfig].get(p.idParameter, '') for p in configurable_parameters] + \ [instances_by_id[idInstance].get_property_value(p.idProperty, db) for p in instance_properties] + \ [run.penalized_time1, 1 if run.censored else 0]) csv_response.seek(0) headers = Headers() headers.add('Content-Type', 'text/csv') headers.add('Content-Disposition', 'attachment', filename=secure_filename(experiment.name) + "_configuration_runs.csv") return Response(response=csv_response.read(), headers=headers)
def json_response(self): serializer = Serializer() prepared_query = self.prepare_query() def generate(): i = prepared_query.count() yield "[\n" for obj in prepared_query: i -= 1 yield json.dumps(serializer.serialize_object(obj, prepared_query.query)) if i > 0: yield ",\n" yield "\n]" headers = Headers() headers.add("Content-Type", "application/javascript") headers.add("Content-Disposition", "attachment; filename=export.json") return Response(generate(), mimetype="text/javascript", headers=headers, direct_passthrough=True)
def json_response(self, filename='export.json'): serializer = Serializer() prepared_query = self.prepare_query() field_dict = {} for field in prepared_query._select: field_dict.setdefault(field.model_class, []) field_dict[field.model_class].append(field.name) def generate(): i = prepared_query.count() yield '[\n' for obj in prepared_query: i -= 1 yield json.dumps(serializer.serialize_object(obj, field_dict)) if i > 0: yield ',\n' yield '\n]' headers = Headers() headers.add('Content-Type', 'application/javascript') headers.add('Content-Disposition', 'attachment; filename=%s' % filename) return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def download_file(vault_name): """ Download a file if the link is available... """ handler = get_handler() region = handler.region.name vault = Vault.query.filter_by(name=vault_name,region=region).first() if vault is None: abort(401) #Need to get the archive too... if 'archive_id' not in request.args: abort(401) archive = Archive.query.filter_by(archive_id=request.args['archive_id']).first() if archive is None: abort(401) if archive.filename!="NOT_GIVEN": fname=archive.filename else: fname=app.config["UNKNOWN_FILENAME"] #Are we serving from cache? #cache = archive.cached() #if cache==1: # print "Serving from cache." # return send_from_directory(os.path.join(app.config["LOCAL_CACHE"],region,vault.name),archive.archive_id,attachment_filename=fname,as_attachment=True) #Is there a finished job knocking about? job=archive.jobs.filter_by(action='download',completed=True,live=True,status_message="Succeeded").first() if job is None: abort(401) #OK, everything exists, go ahead... if False and cache==2: #Save to cache whilst serving f = open(os.path.join(app.config["LOCAL_CACHE"],region,vault.name,archive.archive_id),'wb') else: #Don't add to cache, just serve f = None h=Headers() h.add("Content-Disposition",'attachment;filename="'+fname+'"') return Response(stream_with_context(job.stream_output(file_handler=f)),headers=h)
def identifier_list(): search_fields = [grid_field(f) for f in request.args.iterkeys() if f not in grid_params] fq = ''.join('&fq=' + quote('%s:(%s)' % i) for i in search_fields) q = '*:*' url_params = fq def get_results(): rows = 1000 ret = search(q, url_params, rows=rows, fl=['identifier']) num = ret['results']['response']['numFound'] for doc in ret['results']['response']['docs']: yield doc['identifier'].encode('utf-8') + '\r\n' for start in range(rows, num, rows): ret = search(q, url_params, rows=rows, fl=['identifier']) for doc in ret['results']['response']['docs']: yield doc['identifier'].encode('utf-8') + '\r\n' headers = Headers() headers.add("Content-Type", 'text/plain; charset=utf-8') headers.add("Content-Disposition", "attachment; filename=results.txt") return Response(get_results(), headers=headers, direct_passthrough=True)
class OAuthResponse(object): """Contains the response sent back from an OAuth protected remote application. """ def __init__(self, resp, content): #: a :class:`~werkzeug.Headers` object with the response headers #: the application sent. self.headers = Headers(resp) #: the raw, unencoded content from the server self.raw_data = content #: the parsed content from the server self.data = parse_response(resp, content, strict=True) @property def status(self): """The status code of the response.""" return self.headers.get('status', type=int)
def test_gzipped_response(self): # Create test file filename = 'payment/assets/dist/gzip-test.css' file_contents = "* { content: 'Test. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip.'; }" # noqa: E501 with open(filename, 'w+') as test_file: test_file.write(file_contents) response = self.client.get('/ui/gzip-test.css', headers=Headers([('Accept-encoding', 'gzip') ])) # Check the response reports itself as gzip self.assertEqual(response.content_encoding, 'gzip') # And that we haven't just received the original contents self.assertNotEqual(response.data, file_contents) # Unzip it, check the contents is the same as the original self.assertEqual( gzip.decompress(response.data).decode('utf-8'), file_contents) response.close() os.remove(filename)
def json_response(self): serializer = Serializer() prepared_query = self.prepare_query() def generate(): i = prepared_query.count() yield '[\n' for obj in prepared_query: i -= 1 yield json.dumps( serializer.serialize_object(obj, prepared_query.query)) if i > 0: yield ',\n' yield '\n]' headers = Headers() headers.add('Content-Type', 'application/javascript') headers.add('Content-Disposition', 'attachment; filename=export.json') return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def __init__(self, parsed_url, timeout=30, method=None): URLHandler.__init__(self, parsed_url, timeout) self.headers = Headers() self._state = self.STATE_IDLE self._method = method
assert False except HTTPException as e: eq_(e.code, 405) @inrequest('/foo', method='POST') def test_view_callstack_with_post(): methods_called = [] class TestView(View): def post(self): methods_called.append('post') TestView({}).process() eq_(methods_called, ['post']) ajax_headers = Headers() ajax_headers.add('X-Requested-With', 'XMLHttpRequest') @inrequest('/foo', method='POST', headers=ajax_headers) def test_view_callstack_with_ajax(): methods_called = [] class TestView(View): def xhr(self): methods_called.append('xhr') def post(self): methods_called.append('post') TestView({}).process() eq_(methods_called, ['xhr'])
class HTTPHandler(URLHandler): """Opens HTTP connections.""" default_port = 80 http_version = "1.1" STATE_IDLE, STATE_SENDING, STATE_SENT = range(3) def __init__(self, parsed_url, timeout=30, method=None): URLHandler.__init__(self, parsed_url, timeout) self.headers = Headers() self._state = self.STATE_IDLE self._method = method @property def method(self): return self._method or "GET" def send(self, data): if self._state == self.STATE_IDLE: self._state = self.STATE_SENDING return URLHandler.send(self, data) def send_request(self, data): path = self.parsed_url.path or "/" if self.parsed_url.query: path += "?" + self.parsed_url.query self.send_buffered("%s %s HTTP/%s\r\n" % (self._method, str(path), self.http_version)) self.send_buffered("\r\n".join("%s: %s" % item for item in self.headers.to_list()) + "\r\n\r\n") if isinstance(data, basestring): self.send_buffered(data) data = None self.send(data) self._state = self.STATE_SENT def open(self, data=None): # if no method is set switch between GET and POST based on # the data. This is for example the case if the URL was # opened with open_url(). if self._method is None: if data is not None: self._method = "POST" else: self._method = "GET" if self._state != self.STATE_IDLE: raise CannotSendRequest() if self.http_version == "1.1": if "host" not in self.headers: self.headers["Host"] = self.host_string if "accept-encoding" not in self.headers: self.headers["Accept-Encoding"] = "identity" if "content-length" not in self.headers: content_length = get_content_length(data) if content_length is not None: self.headers["Content-Length"] = content_length self.send_request(data) return HTTPResponse(self)
def send_file(): h = Headers() h.add("Content-type", "application/octet-stream", charset="utf8") h.add("Content-disposition", "attachment", filename="name.tar.gz") return Response(open(os.path.join(os.path.dirname(__file__), "static", "foo.tar.gz"), "r"), headers=h)
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. """ if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, 'name', None) if filename is not None: filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') data = wrap_file(request.environ, file) return Response(data, mimetype=mimetype, headers=headers, direct_passthrough=True)
def captcha(key): global all_keys img = get_captcha_image(all_keys[key]) headers = Headers() headers.add("Content-Type", "image/jpeg") return Response(img, headers=headers)
def send_file(filename=None, file=None, mimetype=None, as_attachment=False, attachment_filename=None, mtime=None, cache_timeout=60 * 60 * 12, add_etags=True, etag=None, conditional=False): """Sends the contents of a file to the client. A file can be either a filesystem file or a file-like object (this code is careful about not assuming that every file is a filesystem file). This will use the most efficient method available, configured and possible (for filesystem files some more optimizations may be possible that for file-like objects not having a filesystem filename). By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. send_file will try to guess some stuff for you if you do not provide them: * mimetype (based on filename / attachment_filename) * mtime (based on filesystem file's metadata) * etag (based on filename, mtime, filesystem file size) If you do not provide enough information, send_file might raise a TypeError. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) :param filename: the filesystem filename of the file to send (relative to the :attr:`~Flask.root_path` if a relative path is specified). If you just have an open filesystem file object f, give `f.name` here. If you don't have a filesystem file nor a filesystem file name, but just a file-like obj, don't use this argument. :param file: a file (or file-like) object, you may give it if you either do not have a filesystem filename or if you already have an open file anyway. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens based on the filename or attachment_filename. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the filename argument. :param mtime: the modification time of the file if provided, otherwise it will be determined automatically for filesystem files :param cache_timeout: the timeout in seconds for the headers. :param conditional: set to `True` to enable conditional responses. :param add_etags: set to `False` to disable attaching of etags. :param etag: you can give an etag here, None means to try to compute the etag from the file's filesystem metadata (the latter of course only works for filesystem files). If you do not give a filename, but you use add_etags, you must explicitely provide the etag as it can't compute it for that case. """ if filename and not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() # We must compute size the smart way rather than letting # werkzeug turn our iterable into an in-memory sequence # See `_ensure_sequence` in werkzeug/wrappers.py if filename: fsize = os.path.getsize(filename) elif file and hasattr(file, 'seek') and hasattr(file, 'tell'): fsize = None # be extra careful as some file-like objects (like zip members) have a seek # and tell methods, but they just raise some exception (e.g. UnsupportedOperation) # instead of really doing what they are supposed to do (or just be missing). try: file.seek(0, 2) # seek to EOF try: fsize = file.tell() # tell position except Exception: pass file.seek(0, 0) # seek to start of file except Exception: pass else: fsize = None if fsize is not None: headers.add('Content-Length', fsize) if as_attachment: if attachment_filename is None: if not filename: raise TypeError('filename unavailable, required for sending as attachment') attachment_filename = os.path.basename(filename) # Note: we only give filename* param, not filename param, hoping that a user agent that # does not support filename* then falls back into using the last URL fragment (and decodes # that correctly). See there for details: http://greenbytes.de/tech/tc2231/ headers.add('Content-Disposition', 'attachment; filename*={0}'.format(encode_rfc2231(attachment_filename))) if current_app.use_x_sendfile and filename: if file: file.close() headers['X-Sendfile'] = filename data = None else: if filename: if not file: file = open(filename, 'rb') if mtime is None: mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # current time to better support conditional requests. Werkzeug # as of 0.6.1 will override this value however in the conditional # response with the current time. This will be fixed in Werkzeug # with a new release, however many WSGI servers will still emit # a separate date header. if mtime is not None: rv.date = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags: if etag is None and filename: etag = 'flask-{0}-{1}-{2}'.format( mtime or os.path.getmtime(filename), os.path.getsize(filename), adler32(filename) & 0xffffffff ) if etag is None: raise TypeError("can't determine etag - please give etag or filename") rv.set_etag(etag) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. """ if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, "name", None) if filename is not None: filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = "application/octet-stream" headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError("filename unavailable, required for " "sending as attachment") attachment_filename = os.path.basename(filename) headers.add("Content-Disposition", "attachment", filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers["X-Sendfile"] = filename data = None else: if file is None: file = open(filename, "rb") data = wrap_file(request.environ, file) return Response(data, mimetype=mimetype, headers=headers, direct_passthrough=True)
class HTTPHandler(URLHandler): """Opens HTTP connections.""" default_port = 80 http_version = '1.1' STATE_IDLE, STATE_SENDING, STATE_SENT = range(3) def __init__(self, parsed_url, timeout=30, method=None): URLHandler.__init__(self, parsed_url, timeout) self.headers = Headers() self._state = self.STATE_IDLE self._method = method @property def method(self): return self._method or 'GET' def send(self, data): if self._state == self.STATE_IDLE: self._state = self.STATE_SENDING return URLHandler.send(self, data) def send_request(self, data): path = self.parsed_url.path or '/' if self.parsed_url.query: path += '?' + self.parsed_url.query self.send_buffered('%s %s HTTP/%s\r\n' % (self._method, str(path), self.http_version)) self.send_buffered('\r\n'.join('%s: %s' % item for item in self.headers.to_list()) + '\r\n\r\n') if isinstance(data, basestring): self.send_buffered(data) data = None self.send(data) self._state = self.STATE_SENT def open(self, data=None): # if no method is set switch between GET and POST based on # the data. This is for example the case if the URL was # opened with open_url(). if self._method is None: if data is not None: self._method = 'POST' else: self._method = 'GET' if self._state != self.STATE_IDLE: raise CannotSendRequest() if self.http_version == '1.1': if 'host' not in self.headers: self.headers['Host'] = self.host_string if 'accept-encoding' not in self.headers: self.headers['Accept-Encoding'] = 'identity' if 'content-length' not in self.headers: content_length = get_content_length(data) if content_length is not None: self.headers['Content-Length'] = content_length self.send_request(data) return HTTPResponse(self)
def test_request_user_junk_token(self): request = MockRequest( Headers([('x-annotator-auth-token', 'foo.bar.baz')])) assert_equal(self.auth.request_user(request), None)
def send_file( filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False, ): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, "name", None) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = "application/octet-stream" headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError("filename unavailable, required for " "sending as attachment") attachment_filename = os.path.basename(filename) headers.add("Content-Disposition", "attachment", filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers["X-Sendfile"] = filename data = None else: if file is None: file = open(filename, "rb") mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # current time to better support conditional requests. Werkzeug # as of 0.6.1 will override this value however in the conditional # response with the current time. This will be fixed in Werkzeug # with a new release, however many WSGI servers will still emit # a separate date header. if mtime is not None: rv.date = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag( "flask-%s-%s-%s" % (os.path.getmtime(filename), os.path.getsize(filename), adler32(filename) & 0xFFFFFFFF) ) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop("x-sendfile", None) return rv
def _prepare_header(): if not hasattr(local, "override_headers"): local.override_headers = Headers()
def send_file(): h = Headers() h.add('Content-type', 'application/octet-stream', charset='utf8') h.add('Content-disposition', 'attachment', filename='name.tar.gz') return Response(open(os.path.join(os.path.dirname(__file__), 'static', 'foo.tar.gz'), 'r'), headers=h)
def configuration_runs(database, experiment_id): db = models.get_database(database) or abort(404) experiment = db.session.query( db.Experiment).get(experiment_id) or abort(404) if not experiment.configuration_scenario: abort(404) solver_configs = [ sc for sc in experiment.solver_configurations if sc.solver_binary == experiment.configuration_scenario.solver_binary ] solver_config_ids = [sc.idSolverConfig for sc in solver_configs] configurable_parameters = [ p.parameter for p in experiment.configuration_scenario.parameters if p.configurable and p.parameter.name not in ('instance', 'seed') ] configurable_parameters_ids = [ p.idParameter for p in configurable_parameters ] parameter_instances = db.session.query(db.ParameterInstance).options( joinedload('parameter')).filter( db.ParameterInstance.SolverConfig_idSolverConfig.in_( solver_config_ids)).all() instances_by_id = dict( (i.idInstance, i) for i in experiment.get_instances(db)) instance_properties = [ p for p in db.session.query(db.Property) if p.is_instance_property() ] parameter_values = dict() for pv in parameter_instances: if pv.Parameters_idParameter not in configurable_parameters_ids: continue if pv.SolverConfig_idSolverConfig not in parameter_values: parameter_values[pv.SolverConfig_idSolverConfig] = dict() parameter_values[pv.SolverConfig_idSolverConfig][ pv.Parameters_idParameter] = pv.value results, _, _ = experiment.get_result_matrix( db, experiment.solver_configurations, experiment.get_instances(db), cost=experiment.defaultCost) csv_response = StringIO.StringIO() csv_writer = csv.writer(csv_response) csv_writer.writerow([p.name for p in configurable_parameters] + [p.name for p in instance_properties] + ['par1', 'censored']) for idInstance in results: for idSolverConfig in results[idInstance]: for run in results[idInstance][idSolverConfig]: csv_writer.writerow( [parameter_values[idSolverConfig].get(p.idParameter, '') for p in configurable_parameters] + \ [instances_by_id[idInstance].get_property_value(p.idProperty, db) for p in instance_properties] + \ [run.penalized_time1, 1 if run.censored else 0]) csv_response.seek(0) headers = Headers() headers.add('Content-Type', 'text/csv') headers.add('Content-Disposition', 'attachment', filename=secure_filename(experiment.name) + "_configuration_runs.csv") return Response(response=csv_response.read(), headers=headers)
def index(key=None): mode = "" req = {} if request.path.find(':') > -1: prefix = request.path.split(':')[0][1:].upper() if not request.args == None: req = dict(request.args) if "mode" in req.keys(): mode = str(req["mode"][0]) req.pop("mode") if mode == "html": pass else: mode="json" else: mode = "json" keys = req.keys() data = {} if prefix.lower() == "dbp": from LODproxy import dbpedia data["data"] = {} key = key.replace(' ','_') dbp = dbpedia.DBPedia(key) data["record"] = dbp.parse() if prefix.lower() == "geo": from LODproxy import geonames geo = geonames.GEOnames(key) data["record"] = geo.parse() if prefix.lower() == "googleisbn": from LODproxy import googleisbn gisbn = googleisbn.GOOGLEisbn(key) data["record"] = gisbn.parse() if prefix.lower() == "sameas": from LODproxy import sameas key = key.replace('http:/', 'http://') same = sameas.SAMEas(key) data["record"] = same.parse() if len(keys) > 0: data["data"] = {} for item in keys[0].split(','): if not item in ("listkeys", "mode"): if item in data["record"].keys(): data["data"][item] = "" data["data"][item] = data["record"][item] if item == "listkeys": for item in data["record"].keys(): data["data"] = {} data["data"]["keys"]=data["record"].keys() break else: data["data"] = data["record"] if mode == "html": return('ok') else: h = Headers() h.add('Content-Type',"application/json") return(Response(json.dumps(data["data"]), headers=h)) else: return (render_template('index.html', baseurl=g.BASEURL, modules=g.modules))
eq_(e.code, 405) @inrequest('/foo', method='POST') def test_view_callstack_with_post(): methods_called = [] class TestView(View): def post(self): methods_called.append('post') TestView({}).process() eq_(methods_called, ['post']) ajax_headers = Headers() ajax_headers.add('X-Requested-With', 'XMLHttpRequest') @inrequest('/foo', method='POST', headers=ajax_headers) def test_view_callstack_with_ajax(): methods_called = [] class TestView(View): def xhr(self): methods_called.append('xhr') def post(self): methods_called.append('post') TestView({}).process()
def get(self, item_id): if item_id is None: # Use request.args.get(key, default) to get the filtering arguments # scholarships = [ # { # "name": "Frank F. Conlon Fellowship", # "deadline": "1/15/2016", # "amount": 8000, # "url": "http://southasia.washington.edu/students/funding/#Conlon" # }, # { # "name": "WAVA Phyllis Lawson Scholarship Award", # "deadline": "1/31/2016", # "amount": 1000, # "url": "TBD" # }, # { # "name": "Mount Baker Community Club MLK Scholarship", # "deadline": "1/15/2016", # "amount": 10000, # "url": "http://www.mountbaker.org/scholarship/" # }, # { # "name": "Annual Arevalo Scholarship", # "deadline": "3/14/2016", # "amount": 1000, # "url": "http://www.ewu.edu/Documents/CSBSSW/Chicano%20Ed/Scholarships%202015-16/Arrevalo%20Scholarship%202015.pdf" # }, # { # "name": "Orgullo Latino(a) University Scholarship", # "deadline": "3/14/2016", # "amount": 1000, # "url": "http://www.fastweb.com/college-scholarships/scholarships/19801-orgullo-latino-university-scholarship" # }, # { # "name": "Bernie Minsk Scholarship", # "deadline": "3/1/2016", # "amount": 30000, # "url": "http://www.berniescholarships.org/Apply.html" # }, # { # "name": "Walter H. Meyer - Garry L. White Memorial Scholarship", # "deadline": "3/1/2016", # "amount": 5000, # "url": "http://www.collegeplan.org/cpnow/pnwguide/onlineaps/mwonap.htm" # }, # { # "name": "Yuri and Tatsuo Nakata Scholarship", # "deadline": "3/1/2016", # "amount": 2500, # "url": "http://www.washboard.org/ScholarshipDetails/The+Seattle+Foundation/2016-2017/Yuri+and+Tatsuo+Nakata+Scholarship" # } # ] scholarships = map(lambda s: s.short_dict(), Scholarship.query.all()) response = { 'scholarships': scholarships, 'page_info': { 'page_size': len(scholarships), 'page_num': 0, 'more_pages': False } } headers = Headers() headers.add('Access-Control-Allow-Origin', '*') return create_response(pretty=('pretty' in request.args), **response) else: # TODO: Be more robust handling invalid id scholarship = db.session.query(Scholarship).filter_by( id=item_id)[0].full_dict() return create_response(scholarship=scholarship)
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a `filename` or an `attachment_filename` to be provided. Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. .. versionchanged:: 0.7 mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. Make sure that the file pointer is positioned at the start of data to send before calling :func:`send_file`. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: from warnings import warn file = filename_or_fp filename = getattr(file, 'name', None) # XXX: this behaviour is now deprecated because it was unreliable. # removed in Flask 1.0 if not attachment_filename and not mimetype \ and isinstance(filename, basestring): warn(DeprecationWarning('The filename support for file objects ' 'passed to send_file is now deprecated. Pass an ' 'attach_filename if you want mimetypes to be guessed.'), stacklevel=2) if add_etags: warn(DeprecationWarning('In future flask releases etags will no ' 'longer be generated for file objects passed to the send_file ' 'function because this behaviour was unreliable. Pass ' 'filenames instead if possible, otherwise attach an etag ' 'yourself based on another value'), stacklevel=2) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # the time of the last modification. if mtime is not None: rv.last_modified = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag('flask-%s-%s-%s' % ( os.path.getmtime(filename), os.path.getsize(filename), adler32( filename.encode('utf8') if isinstance(filename, unicode) else filename ) & 0xffffffff )) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, 'name', None) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # current time to better support conditional requests. Werkzeug # as of 0.6.1 will override this value however in the conditional # response with the current time. This will be fixed in Werkzeug # with a new release, however many WSGI servers will still emit # a separate date header. if mtime is not None: rv.date = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag('flask-%s-%s-%s' % (os.path.getmtime(filename), os.path.getsize(filename), adler32(filename) & 0xffffffff)) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a `filename` or an `attachment_filename` to be provided. Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. .. versionchanged:: 0.7 mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. Make sure that the file pointer is positioned at the start of data to send before calling :func:`send_file`. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: from warnings import warn file = filename_or_fp filename = getattr(file, 'name', None) # XXX: this behaviour is now deprecated because it was unreliable. # removed in Flask 1.0 if not attachment_filename and not mimetype \ and isinstance(filename, basestring): warn(DeprecationWarning('The filename support for file objects ' 'passed to send_file is not deprecated. Pass an ' 'attach_filename if you want mimetypes to be guessed.'), stacklevel=2) if add_etags: warn(DeprecationWarning('In future flask releases etags will no ' 'longer be generated for file objects passed to the send_file ' 'function because this behaviour was unreliable. Pass ' 'filenames instead if possible, otherwise attach an etag ' 'yourself based on another value'), stacklevel=2) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # the time of the last modification. if mtime is not None: rv.last_modified = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag('flask-%s-%s-%s' % ( os.path.getmtime(filename), os.path.getsize(filename), adler32(filename) & 0xffffffff )) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def make_request(consumer, obj=None): obj = obj or {} obj.update({'consumerKey': consumer.key}) return MockRequest( Headers([('x-annotator-auth-token', auth.encode_token(obj, consumer.secret))]))
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """JSON based public APIs for the amaGama translation memory server""" from json import dumps from flask import Blueprint, abort, current_app, request from werkzeug import Headers # Let's encourage caching for an hour: cache_headers = Headers() cache_headers['Cache-Control'] = "max-age=3600, public" # Create the blueprints. read_api = Blueprint('read_api', __name__) write_api = Blueprint('write_api', __name__) @read_api.route('/<slang>/<tlang>/unit/', methods=('GET', )) def translate_unit_get(slang, tlang): return get_uid_and_call(translate_unit, slang, tlang) @write_api.route('/<slang>/<tlang>/unit/', methods=('POST', )) def update_unit_get(slang, tlang): return get_uid_and_call(update_unit, slang, tlang)
def test_gzip_cache_key_format(self): with app.test_request_context('/foo?cachebuster=123'): response = mock.MagicMock(headers=Headers([('ETag', 'bar')])) key = gzip_cache_key(response) self.assertEqual(key, '/foobar')