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