コード例 #1
0
ファイル: views.py プロジェクト: hm1021/webbattle
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)
コード例 #2
0
ファイル: flask_tests.py プロジェクト: dharmeshpatel/flask
    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'
コード例 #3
0
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'))
コード例 #4
0
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
コード例 #5
0
ファイル: client.py プロジェクト: archerhu/flask-oauthlib
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()
コード例 #6
0
ファイル: views.py プロジェクト: JustinLardinois/pcrpdev
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")
コード例 #7
0
ファイル: resource.py プロジェクト: alpocr/gae-init-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
コード例 #8
0
ファイル: flask_rauth.py プロジェクト: underdogio/flask-rauth
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
コード例 #9
0
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
コード例 #10
0
ファイル: main.py プロジェクト: neilengineer/frog
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')
コード例 #11
0
ファイル: resource.py プロジェクト: jkothari18/upup
def resource_db_from_upload():
    try:
        uploaded_file = flask.request.files['file']
    except:
        return None

    bucket_name, origin_dir, object_name = extract_cloud_storage_meta_data(
        uploaded_file)
    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)

    gcs_object_path = "{}/{}/{}".format(bucket_name, origin_dir, object_name)
    image_url = None
    public_url = None
    if blob_info.content_type.startswith('image'):
        try:
            image_url = images.get_serving_url(blob_info.key(),
                                               secure_url=True)
        except:
            pass
    else:
        response = storage.objects().patch(
            bucket=bucket_name,
            object="{}/{}".format(origin_dir, object_name),
            body={
                'acl': [{
                    "entity": "project-owners-825037505474",
                    "role": "OWNER"
                }, {
                    "entity": "project-editors-825037505474",
                    "role": "OWNER"
                }, {
                    "entity": "project-viewers-825037505474",
                    "role": "READER"
                }, {
                    "entity": "allUsers",
                    "role": "READER"
                }]
            }).execute()
        public_url = "https://storage.googleapis.com/{}?content_type={}".format(
            gcs_object_path, blob_info.content_type)

    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,
        public_url=public_url,
        bucket_name=get_bucket_and_path_name() or None,
        gcs_object_path=gcs_object_path,
    )
    resource_db.put()
    return resource_db
コード例 #12
0
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)
コード例 #13
0
ファイル: flask_oauth.py プロジェクト: bjourne/flask-oauth
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()
コード例 #14
0
ファイル: main.py プロジェクト: keirwl/Threads
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"])
コード例 #15
0
ファイル: tfg_server.py プロジェクト: gualdras/tfg_server
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)
コード例 #16
0
ファイル: views.py プロジェクト: ssb402/Vote-or-Skip-Web-App
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)
コード例 #17
0
def send_into_blobstore_handler():

    blob = request.files.values()[0]

    blob_key = parse_options_header(
        blob.headers['Content-Type'])[1]['blob-key']

    return jsonify({
        'status': 'OK',
        'filename': blob.filename,
        'blob_key': blob_key
    })
コード例 #18
0
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)
コード例 #19
0
ファイル: resource.py プロジェクト: manshar/birwaz
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)

    logging.info('Photo Info')
    logging.info('blob_info.size: {}'.format(blob_info.size))
    logging.info('blob_info.md5_hash: {}'.format(blob_info.md5_hash))
    logging.info('blob_info.creation: {}'.format(blob_info.creation))
    image_obj = images.Image(blob_key=blob_info.key())
    # image_obj.im_feeling_lucky()
    image_obj.resize(width=100)
    output = image_obj.execute_transforms(parse_source_metadata=True)
    logging.info('image_obj.width: {}'.format(image_obj.width))
    logging.info('image_obj.height: {}'.format(image_obj.height))

    metadata = image_obj.get_original_metadata()
    logging.info('metadata: {}'.format(metadata))
    logging.info('type(metadata): {}'.format(type(metadata)))

    image_url = None
    if blob_info.content_type.startswith('image'):
        try:
            image_url = images.get_serving_url(blob_info.key(),
                                               secure_url=True)
        except:
            pass

    taken_at = metadata.get('DateTimeOriginal')
    if taken_at:
        taken_at = datetime.datetime.fromtimestamp(float(taken_at))
    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,
        metadata=metadata,
        taken_at=taken_at,
        camera_make=metadata.get('Make'),
        camera_model=metadata.get('Model'),
        md5_hash=blob_info.md5_hash,
        width=metadata.get('ImageWidth') or image_obj.width,
        height=metadata.get('ImageLength') or image_obj.height,
        bucket_name=config.CONFIG_DB.bucket_name or None,
    )
    resource_db.put()
    return resource_db
コード例 #20
0
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'))
コード例 #21
0
ファイル: flask_tests.py プロジェクト: cat-train/flask
    def test_attachment(self):
        app = flask.Flask(__name__)
        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'

        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')
            assert rv.mimetype == 'text/plain'
            value, options = parse_options_header(rv.headers['Content-Disposition'])
            assert value == 'attachment'
            assert options['filename'] == 'index.txt'
コード例 #22
0
ファイル: main.py プロジェクト: scottsappen/PayMySitter
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)
コード例 #23
0
ファイル: flask_tests.py プロジェクト: smalls/flask
    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"
コード例 #24
0
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()
コード例 #25
0
ファイル: oauth.py プロジェクト: bradfordbarr/flask-oauth
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()
コード例 #26
0
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)
コード例 #27
0
ファイル: controllers.py プロジェクト: gitter-badger/kolore
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 :(')
コード例 #28
0
ファイル: views.py プロジェクト: GoogleJump/ninja
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)
コード例 #29
0
ファイル: views.py プロジェクト: GoogleJump/ninja
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)
コード例 #30
0
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)
コード例 #31
0
ファイル: client.py プロジェクト: rizarsyi/flask-oauthlib
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()
コード例 #32
0
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'):
        charset = options.get('charset', 'utf-8')
        return get_etree().fromstring(content.decode(charset))

    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()
コード例 #33
0
ファイル: blueprint.py プロジェクト: brunoripa/flask-kibble
def upload(gcs_bucket=None):
    payload = {}

    for field, filedata in flask.request.files.iteritems():
        parsed_header = parse_options_header(filedata.content_type)

        blobkey = parsed_header[1]['blob-key']
        blobinfo = blobstore.BlobInfo.get(blobkey)
        if not flask.g.kibble.auth.can_upload_file(blobinfo):
            blobinfo.delete()
            payload[field] = {
                'error': 'permission denied',
            }
        else:
            payload[field] = {
                'blobkey': blobkey,
                'filename': filedata.filename,
            }

    return flask.jsonify(payload)
コード例 #34
0
ファイル: resource.py プロジェクト: tiberiucorbu/av-website
def resource_db_from_upload():
    try:
        uploaded_file = flask.request.files["file"]
    except:
        return None

    image_thumb_data_url = util.param("image-thumb-data-url", str)
    image_average_color = util.param("image-average-color", str)
    image_size_w = util.param("image-size-w", float)
    image_size_h = util.param("image-size-h", float)
    name = util.param("name", str)

    headers = uploaded_file.headers["Content-Type"]
    parsedOptionHeader = werkzeug.parse_options_header(headers)[1]
    blob_info_key = parsedOptionHeader["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(),
        file_name=blob_info.filename,
        name=name,
        content_type=blob_info.content_type,
        size=blob_info.size,
        image_url=image_url,
        bucket_name=config.CONFIG_DB.bucket_name or None,
        image_thumb_data_url=image_thumb_data_url,
        image_average_color=image_average_color,
        image_size_w=image_size_w,
        image_size_h=image_size_h,
    )
    resource_db.put()
    return resource_db
コード例 #35
0
ファイル: views.py プロジェクト: GoogleJump/ninja
def upload2():
    # Make twitter User from database entry
    key = request.form['KEY']
    key = ndb.Key(urlsafe=key)
    user = key.get()

    User = make_twit(user.twitter_key1, user.twitter_key2)

    # retrieve the title
    title = request.form['title']

    if title == '':
        return redirect('/moment')

    # retrieve the blob key for the uploaded file

    if request.files['file']:
        f = request.files['file']
        header = f.headers['Content-Type']
        parsed_header = parse_options_header(header)
        bkey = parsed_header[1]['blob-key']
        imges = StringIO(blobstore.get(bkey).open().read())

    if request.form['urls']:
        email = request.form['urls']
        if mail.is_email_valid(email):
            sender = '*****@*****.**'
            subject = title
            body = str(url_for('img',blob_key=bkey,_external=TRUE))
            mail.send_mail(sender,email,subject,body)


    # retrieve the text message
    msg = request.form['description']



    User.update_status_with_media(status = str(msg), media=imges)

    return img(bkey)
コード例 #36
0
 def better_parse_response(resp, content, strict=False):
     ct, options = parse_options_header(resp['content-type'])
     if ct in ('application/json', 'text/javascript'):
         try:
             return json.loads(content)
         # handle json decode errors from parse_response
         # this is useful in the identify call because the response is
         # 'application/json' but the content is encoded
         except:
             return 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 superset
         # of utf-8 anyways, so 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()
コード例 #37
0
ファイル: client.py プロジェクト: jn7163/flask-oauthlib
def parse_response(resp, content, strict=False, content_type=None):
    """Parse the response returned by :meth:`OAuthRemoteApp.http_request`.

    :param resp: response of http_request
    :param content: content of the response
    :param strict: strict mode for form urlencoded content
    :param content_type: assign a content type manually
    """
    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()
コード例 #38
0
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(',')
    theParsedDomains = []
    from plugins import domains
    for dom in theDomains:
        newdo = domains.parseDomain(dom)
        if newdo!=None and newdo!=' ' and newdo!='\n':
            theParsedDomains.append(newdo)
    if len(theParsedDomains)>0:
        domainslist = ""
        for do in theParsedDomains:
            domainslist+=do+","
        newDomain = sp_data.appIconProposed(domains=domainslist[:-1], imageKey=theKey, imageURL=images.get_serving_url(blob_key))
        newDomain.put()
        return redirect(url_for('icons'))
    else:
        return redirect(url_for('icons'))
コード例 #39
0
def upload2():
    # Make twitter User from database entry
    key = request.form['KEY']
    key = ndb.Key(urlsafe=key)
    user = key.get()

    User = make_twit(user.twitter_key1, user.twitter_key2)

    # retrieve the title
    title = request.form['title']

    if title == '':
        return redirect('/moment')

    # retrieve the blob key for the uploaded file

    if request.files['file']:
        f = request.files['file']
        header = f.headers['Content-Type']
        parsed_header = parse_options_header(header)
        bkey = parsed_header[1]['blob-key']
        imges = StringIO(blobstore.get(bkey).open().read())

    if request.form['urls']:
        email = request.form['urls']
        if mail.is_email_valid(email):
            sender = '*****@*****.**'
            subject = title
            body = str(url_for('img', blob_key=bkey, _external=TRUE))
            mail.send_mail(sender, email, subject, body)

    # retrieve the text message
    msg = request.form['description']

    User.update_status_with_media(status=str(msg), media=imges)

    return img(bkey)
コード例 #40
0
def _parse_content_type(properties):
    return werkzeug.parse_options_header(properties.content_type)
コード例 #41
0
ファイル: blobstore_utils.py プロジェクト: nimnull/gaejstable
def get_blob_key(field_name, blob_key=None):
    upload_file = request.files[field_name]
    header = upload_file.headers['Content-Type']
    parsed_header = parse_options_header(header)
    blob_key = parsed_header[1]['blob-key']
    return blob_key
コード例 #42
0
 def content_type(self):
     content_type, options = parse_options_header(
         self.headers.get('content-type', 'text/plain; charset=us-ascii'))
     charset = options.get('charset', '')
     return content_type, charset