本文整理汇总了Python中werkzeug.Headers.add方法的典型用法代码示例。如果您正苦于以下问题:Python Headers.add方法的具体用法?Python Headers.add怎么用?Python Headers.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.Headers
的用法示例。
在下文中一共展示了Headers.add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_pdf
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例2: match_download
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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
示例3: admin_download_benchmark
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例4: no_cache_js
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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
示例5: _output
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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
示例6: json_response
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例7: configuration_runs
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例8: json_response
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例9: json_response
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例10: download_file
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例11: identifier_list
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例12: send_file
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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:
#.........这里部分代码省略.........
示例13: send_file
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)
示例14: send_file
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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
#.........这里部分代码省略.........
示例15: captcha
# 需要导入模块: from werkzeug import Headers [as 别名]
# 或者: from werkzeug.Headers import add [as 别名]
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)