本文整理汇总了Python中werkzeug.http.parse_options_header函数的典型用法代码示例。如果您正苦于以下问题:Python parse_options_header函数的具体用法?Python parse_options_header怎么用?Python parse_options_header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_options_header函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_attachment
def test_attachment(self, catch_deprecation_warnings):
app = flask.Flask(__name__)
with catch_deprecation_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f, as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
rv.close()
# mimetypes + etag
assert len(captured) == 2
with app.test_request_context():
assert options['filename'] == 'index.html'
rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.html'
rv.close()
with app.test_request_context():
rv = flask.send_file(StringIO('Test'), as_attachment=True,
attachment_filename='index.txt',
add_etags=False)
assert rv.mimetype == 'text/plain'
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.txt'
rv.close()
示例2: test_parse_options_header
def test_parse_options_header(self):
assert http.parse_options_header('something; foo="other\"thing"') == \
('something', {'foo': 'other"thing'})
assert http.parse_options_header('something; foo="other\"thing"; meh=42') == \
('something', {'foo': 'other"thing', 'meh': '42'})
assert http.parse_options_header('something; foo="other\"thing"; meh=42; bleh') == \
('something', {'foo': 'other"thing', 'meh': '42', 'bleh': None})
示例3: test_attachment
def test_attachment(self):
app = flask.Flask(__name__)
with catch_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, "static/index.html"))
rv = flask.send_file(f, as_attachment=True)
value, options = parse_options_header(rv.headers["Content-Disposition"])
self.assert_equal(value, "attachment")
rv.close()
# mimetypes + etag
self.assert_equal(len(captured), 2)
with app.test_request_context():
self.assert_equal(options["filename"], "index.html")
rv = flask.send_file("static/index.html", as_attachment=True)
value, options = parse_options_header(rv.headers["Content-Disposition"])
self.assert_equal(value, "attachment")
self.assert_equal(options["filename"], "index.html")
rv.close()
with app.test_request_context():
rv = flask.send_file(StringIO("Test"), as_attachment=True, attachment_filename="index.txt", add_etags=False)
self.assert_equal(rv.mimetype, "text/plain")
value, options = parse_options_header(rv.headers["Content-Disposition"])
self.assert_equal(value, "attachment")
self.assert_equal(options["filename"], "index.txt")
rv.close()
示例4: test_parse_options_header_value_with_quotes
def test_parse_options_header_value_with_quotes(self):
assert http.parse_options_header(
'form-data; name="file"; filename="t\'es\'t.txt"'
) == ('form-data', {'name': 'file', 'filename': "t'es't.txt"})
assert http.parse_options_header(
'form-data; name="file"; filename*=UTF-8\'\'"\'🐍\'.txt"'
) == ('form-data', {'name': 'file', 'filename': u"'🐍'.txt"})
示例5: test_attachment
def test_attachment(self, app, req_ctx):
with open(os.path.join(app.root_path, 'static/index.html')) as f:
rv = flask.send_file(f, as_attachment=True,
attachment_filename='index.html')
value, options = \
parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.html'
assert 'filename*' not in rv.headers['Content-Disposition']
rv.close()
rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.html'
rv.close()
rv = flask.send_file(StringIO('Test'), as_attachment=True,
attachment_filename='index.txt',
add_etags=False)
assert rv.mimetype == 'text/plain'
value, options = parse_options_header(rv.headers['Content-Disposition'])
assert value == 'attachment'
assert options['filename'] == 'index.txt'
rv.close()
示例6: test_attachment
def test_attachment(self):
app = flask.Flask(__name__)
with catch_warnings() as captured:
with app.test_request_context():
f = open(os.path.join(app.root_path, 'static/index.html'))
rv = flask.send_file(f, as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
# mimetypes + etag
self.assert_equal(len(captured), 2)
with app.test_request_context():
self.assert_equal(options['filename'], 'index.html')
rv = flask.send_file('static/index.html', as_attachment=True)
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
self.assert_equal(options['filename'], 'index.html')
with app.test_request_context():
rv = flask.send_file(StringIO('Test'), as_attachment=True,
attachment_filename='index.txt',
add_etags=False)
self.assert_equal(rv.mimetype, 'text/plain')
value, options = parse_options_header(rv.headers['Content-Disposition'])
self.assert_equal(value, 'attachment')
self.assert_equal(options['filename'], 'index.txt')
示例7: test_parse_options_header_value_with_quotes
def test_parse_options_header_value_with_quotes(self):
assert http.parse_options_header(
'form-data; name="file"; filename="t\'es\'t.txt"'
) == ("form-data", {"name": "file", "filename": "t'es't.txt"})
assert http.parse_options_header(
"form-data; name=\"file\"; filename*=UTF-8''\"'🐍'.txt\""
) == ("form-data", {"name": "file", "filename": u"'🐍'.txt"})
示例8: generate_formdata
def generate_formdata(req, resp, params):
"""sets prarams['form'] to pass to every endpoint.
"""
#print "here"
form = dict()
files = dict()
if req.method == 'GET':
di = parse_query_string(req.query_string)
form = dict(di)
params['form'], params['files'] = dict(form), dict(files)
else:
if 'json' in req.get_header('content-type', None):
form = json.load(req.stream)
params['form'], params['files'] = dict(form), dict(files)
else:
mimetype, options = parse_options_header(req.get_header('content-type'))
data = req.stream.read()
environ = {'wsgi.input': StringIO(data),
'CONTENT_LENGTH': str(len(data)),
'CONTENT_TYPE': req.get_header('content-type'),
'REQUEST_METHOD': 'POST'}
stream, tempform, tempfiles = parse_form_data(environ)
for item in tempform:
form[item] = tempform[item]
di = parse_query_string(req.query_string)
for item in di:
form[item] = di[item]
for item in tempfiles:
files[item] = tempfiles[item]
params['form'], params['files'] = dict(form), dict(files)
return True
示例9: _set_charset
def _set_charset(self, charset):
header = self.headers.get('content-type')
ct, options = parse_options_header(header)
if not ct:
raise TypeError('Cannot set charset if Content-Type header is missing.')
options['charset'] = charset
self.headers['Content-Type'] = dump_options_header(ct, options)
示例10: decode_json
def decode_json(response):
if not response.error:
content_type = parse_options_header(
response.headers.get('Content-Type', 'application/octet-stream'))
assert content_type[0] == 'application/json'
return json.loads(response.body)
return None
示例11: parse_form_data
def parse_form_data(environ, stream_factory = None, charset = 'utf-8', errors = 'ignore', max_form_memory_size = None, max_content_length = None, cls = None, silent = True):
content_type, extra = parse_options_header(environ.get('CONTENT_TYPE', ''))
try:
content_length = int(environ['CONTENT_LENGTH'])
except (KeyError, ValueError):
content_length = 0
if cls is None:
cls = MultiDict
if max_content_length is not None and content_length > max_content_length:
raise RequestEntityTooLarge()
stream = _empty_stream
files = ()
if content_type == 'multipart/form-data':
try:
form, files = parse_multipart(environ['wsgi.input'], extra.get('boundary'), content_length, stream_factory, charset, errors, max_form_memory_size=max_form_memory_size)
except ValueError as e:
if not silent:
raise
form = cls()
else:
form = cls(form)
elif content_type == 'application/x-www-form-urlencoded' or content_type == 'application/x-url-encoded':
if max_form_memory_size is not None and content_length > max_form_memory_size:
raise RequestEntityTooLarge()
form = url_decode(environ['wsgi.input'].read(content_length), charset, errors=errors, cls=cls)
else:
form = cls()
stream = LimitedStream(environ['wsgi.input'], content_length)
return (stream, form, cls(files))
示例12: handle_upload
def handle_upload():
"""Handles the result of the upload.
At this point in time, the file has already been uploaded by the Google App
Engine API. All we have to do is return some response to the end user. This
is why we never actually call something to save the file into a blobstore.
"""
# Verify that the file has actually been uploaded.
# 'filedata' is the id of the DOM element containing the file.
filedata = request.files['filedata']
if not filedata:
return json.dumps({'message' : "No file."}), 400
# The blob-key of the newly stored file is stored inside the header of the
# file.
header = filedata.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
# Check for the file size, if it's too big, then Google App Engine can't
# even return it, so we need to display an error message.
# We will also delete the blob, in order to save storage space.
blob = fileprocessor.get_blob(blob_key)
if blob.size > MAX_FILE_SIZE:
fileprocessor.delete_file(blob_key)
return json.dumps({'message' : "Upload must be smaller than 30MB."}), 400
# Save the blob key in a datastore so we can order any information we need.
# save_file returns the base58 datastore key
data_id = fileprocessor.save_file(blob_key)
# Return a formatted url of the location of the file
address = request.host_url + data_id
return json.dumps({'data_id': data_id})
示例13: _set_charset
def _set_charset(self, charset):
header = self.headers.get("content-type")
ct, options = parse_options_header(header)
if not ct:
raise TypeError("Cannot set charset if Content-Type " "header is missing.")
options["charset"] = charset
self.headers["Content-Type"] = dump_options_header(ct, options)
示例14: parse
def parse(self, stream, content_type, content_length, context=None):
"""Parse the `stream` as a multipart encoded form.
:param stream: the stream to be parsed.
:param content_type: the content type of the request payload.
:param content_length: the content length of the request payload.
:param context: a dictionary containing extra context data
that can be useful for parsing.
"""
if content_length is None:
raise BadRequest('MultiPartParser.parse() requires '
'`content_length` argument')
_, options = parse_options_header(content_type)
boundary = options.get('boundary')
if boundary is None:
raise BadRequest('Multipart data missing boundary '
'in Content-Type header')
boundary = boundary.encode('ascii')
parser = WerkzeugMultiPartParser(default_stream_factory)
try:
form, files = parser.parse(stream, boundary, content_length)
return form.to_dict(), files.to_dict()
except ValueError:
raise BadRequest('Multipart data is invalid')
示例15: manager_humans_create
def manager_humans_create():
form = HumansForm()
upload_url = blobstore.create_upload_url('/manager/humans/create/')
if request.method == 'POST':
if form.validate_on_submit():
blob_key = None
f = request.files['photo']
if f:
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
humans = Humans(
text=form.text.data,
q_month=form.q_month.data,
photo=blob_key
)
db.session.add(humans)
db.session.commit()
flash(u'게시글을 작성하였습니다.', 'success')
return redirect(url_for('humans_list'))
return render_template('manager/create.html', form=form, upload_url=upload_url)