本文整理汇总了Python中werkzeug.parse_options_header函数的典型用法代码示例。如果您正苦于以下问题:Python parse_options_header函数的具体用法?Python parse_options_header怎么用?Python parse_options_header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_options_header函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: 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'])
assert value == 'attachment'
# 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'
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'
开发者ID:dharmeshpatel,项目名称:flask,代码行数:26,代码来源:flask_tests.py
示例2: post_comment
def post_comment(key):
battle = Battle.get(key)
now = datetime.now()
if request.form.has_key('leftbox'):
comment = request.form.get('leftbox')
left_comment = Comment(parent=battle, comment=comment, author=users.get_current_user(), side="left", when=now)
if request.files['left_image']:
image_file = request.files['left_image']
headers = image_file.headers['Content-Type']
blob_key = parse_options_header(headers)[1]['blob-key']
left_comment.blob_key = blob_key
left_comment.image_url = images.get_serving_url(blob_key)
left_comment.put()
send_emails(key, comment)
elif request.form.has_key('rightbox'):
comment = request.form.get('rightbox')
right_comment = Comment(parent=battle, comment=comment, author=users.get_current_user(), side="right", when=now)
if request.files['right_image']:
image_file = request.files['right_image']
headers = image_file.headers['Content-Type']
blob_key = parse_options_header(headers)[1]['blob-key']
right_comment.blob_key = blob_key
right_comment.image_url = images.get_serving_url(blob_key)
right_comment.put()
send_emails(key, comment)
return left_right(key)
开发者ID:hm1021,项目名称:webbattle,代码行数:26,代码来源:views.py
示例3: parse_response
def parse_response(resp, content, strict=False, content_type=None):
"""
Parse the response returned by :meth:`OAuthRemoteApp.http_request`.
"""
ct = resp.headers.get('content-type')
if not ct and content.lower().strip().startswith('callback('):
ct = 'application/json'
if not ct:
ct = content_type
if not ct:
ct = 'application/json'
ct, options = parse_options_header(ct)
if ct in ('application/json', 'text/javascript'):
if content.lower().strip().startswith('callback('):
content = content.strip().replace('callback(', '', 1).strip("); ")
return json.loads(content)
if ct in ('application/xml', 'text/xml'):
return get_etree().fromstring(content)
if ct != 'application/x-www-form-urlencoded' and strict:
return content
charset = options.get('charset', 'utf-8')
return url_decode(content, charset=charset).to_dict()
开发者ID:archerhu,项目名称:flask-oauthlib,代码行数:25,代码来源:client.py
示例4: paper_upload_view
def paper_upload_view():
# big thanks to Stack Overflow user Koffee for explaining how this works
# http://stackoverflow.com/a/18073466/2752467
f = request.files['file']
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = blobstore.BlobKey(parsed_header[1]['blob-key'])
paper_key = request.args.get("id")
paper = ndb.Key(urlsafe=paper_key).get()
blob_stream = blobstore.BlobReader(blob_key)
if not is_pdf(blob_stream):
blob_stream.close()
blobstore.delete(blob_key)
return redirect(url_rule["paper"] + "?id=" + paper_key
+ "&ispdf=false")
blob_stream.close()
# sanity check: file is associated with a paper owned by the current user
if paper and paper.author == \
lookup_user(users.get_current_user().user_id()).key:
if paper.file != None:
# prevent old versions of file from being orphaned
blobstore.delete(paper.file)
paper.file = blob_key
paper.put()
# paper_view_get() will handle most error scenarios
return redirect(url_rule["paper"] + "?id=" + paper_key
+ "&update=success")
开发者ID:JustinLardinois,项目名称:pcrpdev,代码行数:31,代码来源:views.py
示例5: resource_db_from_upload
def resource_db_from_upload():
try:
uploaded_file = flask.request.files['file']
except:
return None
headers = uploaded_file.headers['Content-Type']
blob_info_key = werkzeug.parse_options_header(headers)[1]['blob-key']
blob_info = blobstore.BlobInfo.get(blob_info_key)
image_url = None
if blob_info.content_type.startswith('image'):
try:
image_url = images.get_serving_url(blob_info.key())
except:
pass
resource_db = model.Resource(
user_key=auth.current_user_key(),
blob_key=blob_info.key(),
name=blob_info.filename,
content_type=blob_info.content_type,
size=blob_info.size,
image_url=image_url,
bucket_name=config.CONFIG_DB.bucket_name or None,
)
resource_db.put()
return resource_db
开发者ID:alpocr,项目名称:gae-init-upload,代码行数:27,代码来源:resource.py
示例6: parse_response
def parse_response(resp):
'''
Inspects a :class:`requests.Response` object and returns the content in a
more usable form. The following parsing checks are done:
1. JSON, using the `json` attribute.
2. XML, using :func:`get_etree`.
3. RSS or Atom, using :mod:`feedparser`, if available.
4. Query string, using :func:`parse_utf8_qsl`.
5. If all else fails the plain-text `content` is returned.
:param resp: A `requests.Response` object.
'''
if resp.json is not None:
return resp.json
ct, _ = parse_options_header(resp.headers.get('content-type'))
if ct in ('application/xml', 'text/xml'):
etree = get_etree()
if etree is not None:
return etree.fromstring(resp.content)
if ct in ('application/atom+xml', 'application/rss+xml'):
try:
import feedparser
return feedparser.parse(resp.content)
except:
pass
if isinstance(resp.content, basestring):
return parse_utf8_qsl(resp.content)
return resp.content
开发者ID:underdogio,项目名称:flask-rauth,代码行数:34,代码来源:flask_rauth.py
示例7: cfg_upload_bg
def cfg_upload_bg():
u, u_i = checkUserLoggedIn()
if u and u_i:
usr = sp_data.ExternalUser.query()
us = [u for u in usr if str(u.source)==str(u_i['source']) and str(u.userID)==u_i['userID']]
if len(us)>0:
user = us[0]
image=request.files["filename"]
header = image.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
l = images.get_serving_url(blob_key)
user.backgroundImageURL = l
user.backgroundImageKey=BlobKey(blob_key)
#import datetime
#user.imgUrl="http://startpage-1072.appspot.com/img/{0}/{1}/{2}".format(us[0].source,us[0].userID,datetime.datetime.now())
user.put()
if request.cookies.has_key('first-login') and request.cookies.get('first-login')==str(True):
return redirect(url_for('setup_three'))
else:
return redirect(url_for('edit',message="Success! Your startpage's got a new background image.")+"#image")
else:
return jsonResponse({'status':'error'})
else:
return redirect(url_for('login'))
开发者ID:Robotguy27,项目名称:that-startpage-rocks,代码行数:26,代码来源:main.py
示例8: results_leasingfinder
def results_leasingfinder():
if request.method == 'POST':
month_list_entity = ds.get_saved_months('month_list_leasing')
if month_list_entity != None:
tmp_months_to_show = month_list_entity.month_list_leasing
leasingfinder_data_final = []
one_entry_dict = {}
f = request.files['file']
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
blob_info = blobstore.get(blob_key)
blob_data = blob_info.open().read()
if blob_info.content_type == 'application/json':
leasingfinder_data = leasingfinder.parse_csv_or_json(json.load(StringIO.StringIO(blob_data)))
elif blob_info.content_type == 'text/csv' or blob_info.content_type == 'application/octet-stream':
leasingfinder_data = leasingfinder.parse_csv_or_json(csv.DictReader(StringIO.StringIO(blob_data)))
elif blob_info.content_type == 'text/html':
leasingfinder_data = leasingfinder.parse_html_hertz(blob_data)
else:
blobstore.delete(blob_key)
return "Error, not able to parse the file uploaded, file format: %s not supported."%blob_info.content_type
for i in leasingfinder_data:
entry_key = str(i['year'])+str(i['brand'])+str(i['name'])+str(i['price_date'])
if int(i['leasing_months']) != 0:
i['average leasing'] = (int(i['leasing_months'])*int(i['lease'])+int(i['due_at_signing']))/int(i['leasing_months'])
if int(i['hwy_mpg']) != 0:
i['average mpg'] = (int(i['hwy_mpg'])+int(i['city_mpg']))/2
i['price_date'] = i['price_date'][:6]
ds.save_general_entity(entry_key, i)
# leasingfinder_data_final.append(json.dumps(i))
# one_entry_dict = {}
#use orderdict!
# for j,key in enumerate(i.keys()):
# one_entry_dict['index'+str(j)] = i[key]
# index_nums = one_entry_dict.keys()
# leasingfinder_data_final_keys = i.keys()
# str_to_index_mapping = dict(zip(leasingfinder_data_final_keys, index_nums))
tmp_month = i['price_date']
if tmp_month not in tmp_months_to_show:
for i,m in enumerate(tmp_months_to_show):
if int(tmp_month) > int(m):
tmp_months_to_show.insert(i, tmp_month)
ds.save_updated_months('month_list_leasing', tmp_months_to_show)
blobstore.delete(blob_key)
#new URL for next upload
# upload_url = blobstore.create_upload_url('/leasingfinder/results')
# print leasingfinder_data_final
# my_title = "Yeah! Totally %d cars found. Check out the lower left corner ones!"%len(leasingfinder_data_final)
# return render_template('leasing_finder_show.html', uploadurl=upload_url,
# leasingfinder_data = leasingfinder_data_final, my_title = my_title)
return redirect('leasingfinder')
开发者ID:neilengineer,项目名称:frog,代码行数:56,代码来源:main.py
示例9: parse_response
def parse_response(resp, content, strict=False):
ct, options = parse_options_header(resp['content-type'])
if ct in ('application/json', 'text/javascript'):
return json.loads(content)
elif ct in ('application/xml', 'text/xml'):
return get_etree().fromstring(content)
elif ct != 'application/x-www-form-urlencoded':
if strict:
return content
charset = options.get('charset', 'utf-8')
return url_decode(content, charset=charset).to_dict()
开发者ID:bjourne,项目名称:flask-oauth,代码行数:11,代码来源:flask_oauth.py
示例10: upload_photo
def upload_photo():
f = request.files['file']
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
image = Image(blobKey=blob_key, id=blob_key)
image.put()
return make_response(blob_key, http.CREATED)
开发者ID:gualdras,项目名称:tfg_server,代码行数:11,代码来源:tfg_server.py
示例11: check_file_upload
def check_file_upload(request):
# This can later be expanded to check file size, type, etc.
"Checks if a file was uploaded. Returns the BlobKey if so or None if not."
try:
blob_file = request.files["file"]
except BadRequestKeyError:
return None
else:
# Copied with little understanding from https://gist.github.com/merqurio/c0b62eb1e1769317907f
headers = parse_options_header(blob_file.headers["Content-Type"])
return blobstore.BlobKey(headers[1]["blob-key"])
开发者ID:keirwl,项目名称:Threads,代码行数:11,代码来源:main.py
示例12: add_icon
def add_icon():
domainlist = request.form.get('domains')
image = request.files.get('icon')
header = image.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
theKey =BlobKey(blob_key)
theDomains = domainlist.split(',')
newDomain = sp_data.appIconProposed(domains=domainlist, imageKey=theKey, imageURL=images.get_serving_url(blob_key))
newDomain.put()
return redirect(url_for('icons'))
开发者ID:Robotguy27,项目名称:that-startpage-rocks,代码行数:12,代码来源:main.py
示例13: saveimage
def saveimage(key):
category = Category.get(key)
items = Item.all().ancestor(category)
item = Item.all().ancestor(category).filter("title =", request.form.get("items")).get()
if request.method == "POST":
image_file = request.files["image"]
headers = image_file.headers["Content-Type"]
blob_key = parse_options_header(headers)[1]["blob-key"]
item.blob_key = blob_key
item.image_url = images.get_serving_url(blob_key)
item.put()
return redirect("edit/images/" + key)
开发者ID:ssb402,项目名称:Vote-or-Skip-Web-App,代码行数:12,代码来源:views.py
示例14: userprofilephotoconfirm
def userprofilephotoconfirm():
member = MemberInfo()
#this will cause an ugly key error if we don't handle it properly
try:
inputUploadedPictureFile = request.files['inputProfilepicture']
if inputUploadedPictureFile:
header = inputUploadedPictureFile.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
except:
#no need to log this error output
dummyvariable = ""
#a user is uploading a picture, either new if they did not have one prior, or uploaded a new one which would delete the old one
if inputUploadedPictureFile:
if member.pictureblobstorekey:
blobstore.delete(member.pictureblobstorekey)
images.delete_serving_url(member.pictureblobstorekey)
member.pictureservingurl = images.get_serving_url(blob_key)
member.pictureblobstorekey = blob_key
member.put()
return render_template('userprofilephotosaved.html', member=member)
except:
try:
#If you couldn't complete the user save, be sure to delete the photo from the blobstore or re-use it later (to avoid a lost child hanging around)
inputUploadedPictureFile = request.files['inputProfilepicture']
if inputUploadedPictureFile:
header = inputUploadedPictureFile.headers['Content-Type']
parsed_header = parse_options_header(header)
blob_key = parsed_header[1]['blob-key']
blobstore.delete(blob_key)
except:
#no need to log this error output
dummyvariable = ""
#Create a new form POST URL for the blobstore
userprofilephoto_form_url = blobstore.create_upload_url('/userprofilephotoconfirm')
return render_template('userprofilephoto.html', member=member, userprofilephoto_form_url=userprofilephoto_form_url, user_profilepicturesrc=user_profilepicturesrc, alertmessage='Oops!', userprofilephoto_form_url=userprofilephoto_form_url, user_profilepicturesrc=user_profilepicturesrc)
开发者ID:scottsappen,项目名称:PayMySitter,代码行数:39,代码来源:main.py
示例15: 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"])
assert value == "attachment"
# 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"
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"
开发者ID:smalls,项目名称:flask,代码行数:24,代码来源:flask_tests.py
示例16: parse_response
def parse_response(resp, content, strict=False):
ct, options = parse_options_header(resp['content-type'])
if ct == 'application/json':
return json.loads(content)
elif ct in ('application/xml', 'text/xml'):
# technically, text/xml is ascii based but because many
# implementations get that wrong and utf-8 is a superst
# of utf-8 anyways, there is not much harm in assuming
# utf-8 here
charset = options.get('charset', 'utf-8')
return get_etree().fromstring(content.decode(charset))
elif ct != 'application/x-www-form-urlencoded':
if strict:
return content
charset = options.get('charset', 'utf-8')
return url_decode(content, charset=charset).to_dict()
开发者ID:bradfordbarr,项目名称:flask-oauth,代码行数:16,代码来源:oauth.py
示例17: upload
def upload():
if request.method == 'POST':
file = request.files['file']
# Creates the options for the file
header = file.headers['Content-Type']
parsed_header = parse_options_header(header)
# IF everything is OK, save the file
if file:
try:
blob_key = parsed_header[1]['blob-key']
return get_serving_url(blob_key, size=IMG_SIZE)
except Exception as e:
logging.exception(e)
return 'http://placehold.it/500&text="No file uploaded :("'
else:
logging.exception('Not file, mate :(')
开发者ID:gitter-badger,项目名称:kolore,代码行数:17,代码来源:controllers.py
示例18: uploadfb
def uploadfb():
""" Parse the form data for inserting a facebook graph node """
msg = request.form['descriptionfb']
# retrieve the blob key for the uploaded file
f = request.files['filefb']
bkey = None
if f is not None:
# parse blob key from the incoming HTTP header
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
bkey = parsed_header[1]['blob-key']
return fb_publish(bkey, msg)
开发者ID:GoogleJump,项目名称:ninja,代码行数:17,代码来源:views.py
示例19: parse_response
def parse_response(resp, content, strict=False, content_type=None):
"""
Parse the response returned by :meth:`make_request`.
"""
if not content_type:
content_type = resp.headers.get('content-type', 'application/json')
ct, options = parse_options_header(content_type)
if ct in ('application/json', 'text/javascript'):
return json.loads(content)
if ct in ('application/xml', 'text/xml'):
return get_etree().fromstring(content)
if ct != 'application/x-www-form-urlencoded' and strict:
return content
charset = options.get('charset', 'utf-8')
return url_decode(content, charset=charset).to_dict()
开发者ID:rizarsyi,项目名称:flask-oauthlib,代码行数:18,代码来源:client.py
示例20: upload
def upload():
""" Parse the form data for inserting a moment """
title = request.form['title']
msg = request.form['description']
# retrieve the blob key for the uploaded file
f = request.files['file']
bkey = None
if f is not None:
# parse blob key from the incoming HTTP header
header = f.headers['Content-Type']
parsed_header = parse_options_header(header)
bkey = parsed_header[1]['blob-key']
return create_moment(title, bkey, msg)
开发者ID:GoogleJump,项目名称:ninja,代码行数:18,代码来源:views.py
注:本文中的werkzeug.parse_options_header函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论