本文整理汇总了Python中google.appengine.ext.blobstore.BlobInfo类的典型用法代码示例。如果您正苦于以下问题:Python BlobInfo类的具体用法?Python BlobInfo怎么用?Python BlobInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BlobInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: action_edit
def action_edit(self):
if self.section.handler.request.get('submit'):
self.SITE_HEADER = self.section.handler.request.get('SITE_HEADER')
self.SITE_SUB_HEADER = self.section.handler.request.get('SITE_SUB_HEADER')
self.DEFAULT_THEME = self.section.handler.request.get('DEFAULT_THEME')
self.GOOGLE_ANALYTICS_UA = self.section.handler.request.get('GOOGLE_ANALYTICS_UA')
self.ROBOTS_TXT = self.section.handler.request.get('ROBOTS_TXT')
if self.section.handler.request.get('FAVICON_ICO'):
if self.FAVICON_ICO:
BlobInfo.get(self.FAVICON_ICO).delete()
data = self.section.handler.request.get('FAVICON_ICO')
handle = files.blobstore.create(mime_type='image/x-icon', _blobinfo_uploaded_filename='favicon.ico')
with files.open(handle, 'a') as f: f.write(data)
files.finalize(handle)
self.FAVICON_ICO = files.blobstore.get_blob_key(handle)
self.ENABLE_THEME_PREVIEW = self.section.handler.request.get('ENABLE_THEME_PREVIEW') != ''
self.DEBUG_MODE = self.section.handler.request.get('DEBUG_MODE') != ''
cache.delete(CACHE_KEY)
self.update()
raise Exception('Redirect', self.section.action_redirect_path)
f = form(self.section, self.section.full_path)
f.add_control(control(self.section, 'text', 'SITE_HEADER', self.SITE_HEADER, 'Site header', 50))
f.add_control(control(self.section, 'text', 'SITE_SUB_HEADER', self.SITE_SUB_HEADER, 'Site sub-header', 50))
combined_themes = get_local_theme_namespaces() + get_custom_theme_namespaces()
f.add_control(selectcontrol(self.section, 'DEFAULT_THEME', combined_themes, self.DEFAULT_THEME if self.DEFAULT_THEME else DEFAULT_LOCAL_THEME_TEMPLATE, 'Default theme'))
f.add_control(control(self.section, 'text', 'GOOGLE_ANALYTICS_UA', self.GOOGLE_ANALYTICS_UA, 'Google analytics UA'))
f.add_control(control(self.section, 'file', 'FAVICON_ICO', label='favicon.ico'))
f.add_control(textareacontrol(self.section, 'ROBOTS_TXT', self.ROBOTS_TXT, 'robots.txt', 90, 5))
f.add_control(checkboxcontrol(self.section, 'ENABLE_THEME_PREVIEW', self.ENABLE_THEME_PREVIEW, 'Enable theme preview'))
f.add_control(checkboxcontrol(self.section, 'DEBUG_MODE', self.DEBUG_MODE, 'Debug mode'))
f.add_control(control(self.section, 'submit', 'submit', 'Submit'))
return '<h2>Edit configuration</h2>%s' % unicode(f)
示例2: start_batch
def start_batch(key, bid):
try:
reader = BlobReader(BlobKey(key))
except:
return 'failed to find key: please re-upload.'
newest_date = branch_newest_date(bid)
dic = {}
for line in reader:
line = line.strip()
try:
game_date = valid(line)
if game_date < newest_date:
game_date = newest_date
except:
continue
if util.tomorrow(util.today()) < game_date:
continue
if game_date not in dic:
dic[game_date] = []
dic[game_date].append(','.join(line.split(',')[:8]))
for key_date in sorted(dic.keys()):
qs = QueueScore(
bid=bid, game_date=key_date, body=(
'\n'.join(reversed(dic[key_date]))
))
qs.put()
BlobInfo.get(key).delete()
return 'upload succeeded!'
示例3: image_manager
def image_manager(page):
"""
GET --> The main image manager page
POST --> Delete requested file(s)
:param page: The requested page
"""
if request.method == 'POST':
img_ref_key = request.get_json()
# Delete the img from ndb
for img_ref in img_ref_key['objects']:
img_inst = ndb.Key(ImageReference, int(img_ref))
img = img_inst.get()
blob_key = img.blob
# Delete img and blob
img_inst.delete()
BlobInfo.get(blob_key).delete()
logging.info("Delete image: {}".format(img_ref))
return "true"
offset = (page-1)*IMAGES_PER_PAGE
images = ImageReference.query().order(-ImageReference.date)
pagination = Pagination(page, IMAGES_PER_PAGE, images.count())
query = images.fetch(IMAGES_PER_PAGE, offset=offset)
return render_template('image-manager/admin-manager-images.html',
keys=query,
pagination=pagination)
示例4: update_background
def update_background(self, full, thumb):
station = self.station
old_full_blob_key = None
old_thumb_blob_key = None
m1 = re.match(r"/picture/([^/]+)?/view", station.full)
m2 = re.match(r"/picture/([^/]+)?/view", station.thumb)
if m1 and m2:
logging.info("Background is a blob")
old_full_blob_key = m1.group(1)
old_thumb_blob_key = m2.group(1)
else:
logging.info("Background is a static file")
station.full = full
station.thumb = thumb
station.put()
logging.info("Station updated in datastore")
memcache.set(self._memcache_station_id, station)
logging.info("Station updated in memcache")
# Update in runtime
self._station = station
if old_full_blob_key and old_thumb_blob_key:
old_full = BlobInfo.get(old_full_blob_key)
old_full.delete()
logging.info("Old full size background removed from blobstore")
old_thumb = BlobInfo.get(old_thumb_blob_key)
old_thumb.delete()
logging.info("Old thumbnail removed from blobstore")
示例5: delete_blob
def delete_blob(key):
try:
BlobInfo.get(key).delete()
except:
return 'failed'
else:
return 'succeeded'
示例6: delete
def delete(self, **kwargs):
if self.imageid:
b = BlobInfo.get(self.imageid.split('.')[0])
if b:
b.delete()
if self.apkkey:
b = BlobInfo.get(self.apkkey)
if b:
b.delete()
for imguri in self.imagelist:
b = BlobInfo.get(imguri.split('.')[0])
if b:
b.delete()
super(Plugin, self).delete(**kwargs)
pluginCount = PluginCount.get_or_insert('plugin_count')
pluginCount.num -= 1
pluginCount.put()
memcache.delete('allplugincount')
memcache.delete('appnamelist')
memcache.delete('pluginid%s' % self.key().id())
memcache.delete('user_applist_%s' % (self.username))
l = []
for i in range(0, pluginCount.num % 30):
l.append('applist__%s' % i)
l.append('applist__%s' % len(l))
memcache.delete_multi(l)
示例7: get
def get(self):
query_params = {'blob_prop':str(urllib.unquote(self.request.get('blob_key')))}
file = object_query(Blob, query_params).get()
blob = BlobInfo(file.blob_key)
blob.delete()
file.key.delete()
time.sleep(TIME_SLEEP)
self.redirect('/files/view_list')
示例8: delete_all_images
def delete_all_images():
k = ndb.Key("Firm", "frl")
for img in Image.query(ancestor=k).iter():
print img.key.id()
for bk in [img.small_blob_key, img.large_blob_key]:
if BlobInfo.get(bk):
BlobInfo.get(bk).delete()
img.key.delete()
示例9: test_remove_image_with_only_original_blob
def test_remove_image_with_only_original_blob(self):
content_type = 'image/jpeg'
blob_key = self.make_blob(content_type, 'dummy')
self.assertTrue(BlobInfo.get(blob_key),
'Should be able to load BlobInfo for key.')
image = ae_image.core.Image(blob_key, content_type)
image.remove()
self.assertFalse(BlobInfo.get(blob_key),
'Should no longer be able to load BlobInfo for key.')
示例10: serve_file
def serve_file(request, blob_key_or_info, as_download=False, content_type=None, filename=None, offset=None, size=None):
"""
Serves a file from the blobstore, reads most of the data from the blobinfo by default but you can override stuff
by passing kwargs.
You can also pass a Google Cloud Storage filename as `blob_key_or_info` to use Blobstore API to serve the file:
https://cloud.google.com/appengine/docs/python/blobstore/#Python_Using_the_Blobstore_API_with_Google_Cloud_Storage
"""
if isinstance(blob_key_or_info, BlobKey):
info = BlobInfo.get(blob_key_or_info)
blob_key = blob_key_or_info
elif isinstance(blob_key_or_info, basestring):
info = BlobInfo.get(BlobKey(blob_key_or_info))
blob_key = BlobKey(blob_key_or_info)
elif isinstance(blob_key_or_info, BlobInfo):
info = blob_key_or_info
blob_key = info.key()
else:
raise ValueError("Invalid type %s" % blob_key_or_info.__class__)
if info == None:
# Lack of blobstore_info means this is a Google Cloud Storage file
if has_cloudstorage:
info = cloudstorage.stat(blob_key_or_info)
info.size = info.st_size
blob_key = create_gs_key('/gs{0}'.format(blob_key_or_info))
else:
raise ImportError("To serve a Cloud Storage file you need to install cloudstorage")
response = HttpResponse(content_type=content_type or info.content_type)
response[BLOB_KEY_HEADER] = str(blob_key)
response['Accept-Ranges'] = 'bytes'
http_range = request.META.get('HTTP_RANGE')
if offset or size:
# Looks a little bonkers, but basically create the HTTP range string, we cast to int first to make sure
# nothing funky gets into the headers
http_range = "{}-{}".format(
str(int(offset)) if offset else "",
str(int(offset or 0) + size) if size else ""
)
if http_range is not None:
response[BLOB_RANGE_HEADER] = http_range
if as_download:
response['Content-Disposition'] = smart_str(
u'attachment; filename="%s"' % (filename or info.filename)
)
elif filename:
raise ValueError("You can't specify a filename without also specifying as_download")
if info.size is not None:
response['Content-Length'] = info.size
return response
示例11: upload_post_processing
def upload_post_processing():
file = request.files.data.filename
# validate file is image format
if mimetypes.guess_type(file)[0].split('/')[0] != 'image':
# delete non-image file types
BlobInfo.gql("WHERE filename = :fname", fname=file).get().delete()
return template('upload_error.html')
response.set_cookie('img', file, path='/')
redirect('/upload_success')
示例12: __init__
def __init__(self, **kwargs):
gs_object_name = kwargs.pop('gs_object_name', None)
blob_key = kwargs.pop('blob_key', None)
if gs_object_name:
self.blobstore_info = CloudStorageInfo(gs_object_name)
elif blob_key:
self.blobstore_info = BlobInfo(blob_key)
else:
raise ValueError('A gs_object_name or blob_key is required.')
super(AppEngineUploadedFile, self).__init__(self.blobstore_info.open(), **kwargs)
示例13: on_remove
def on_remove(self):
for i in range(len(self.theme_namespaces)):
# This can be done more efficiently via GQL
theme = self.get_theme(self.theme_namespaces[i])
cache.delete(CACHE_KEY_PREPEND + self.theme_namespaces[i])
for key in theme.image_keys:
cache.delete(CACHE_KEY_PREPEND + str(key))
BlobInfo.get(key).delete()
theme.key.delete()
del self.theme_keys[i]
del self.theme_namespaces[i]
self.update()
示例14: post
def post(self):
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
# Resize the image
image = images.Image(blob_key=blob_info.key())
image.resize(width=WOOF_FEED_ITEM_IMAGE_MAX_WIDTH, height=WOOF_FEED_ITEM_IMAGE_MAX_HEIGHT)
thumbnail = image.execute_transforms(output_encoding=images.JPEG)
# Save Resized Image back to blobstore
file_name = files.blobstore.create(mime_type='image/jpeg')
with files.open(file_name, 'a') as f:
f.write(thumbnail)
files.finalize(file_name)
# Remove the original image
blobstore.delete(blob_info.key())
blob_key = files.blobstore.get_blob_key(file_name)
# New FeedImage
feed_image = FeedImage()
feed_image.data = BlobInfo.get(blob_key)
feed_image.width = image.width
feed_image.height = image.height
feed_image.put()
# Create new FeedItem
feed_item = FeedItem()
feed_item.text = self.request.get("text")
feed_item.image = feed_image
feed_item.put()
self.redirect('/')
示例15: returnAllJSON
def returnAllJSON(self):
results = []
fils = BlobInfo.all()
for record in fils:
blob_key = str(record.key())
result = {}
result['key'] = blob_key
result['name'] = record.filename
result['type'] = record.content_type
result['size'] = record.size
result['deleteType'] = 'DELETE'
result['deleteUrl'] = self.request.host_url +'/?key=' + urllib.quote(blob_key, '')
if (IMAGE_TYPES.match(result['type'])):
try:
result['url'] = images.get_serving_url(blob_key, size=1024, crop=True, secure_url=None)
result['thumbnailUrl'] = images.get_serving_url(blob_key, size=240, crop=True, secure_url=None)
result['thumbnailUrl2'] = images.get_serving_url(blob_key, size=120, crop=True, secure_url=None)
except: # Could not get an image serving url
pass
if not 'url' in result:
result['url'] = self.request.host_url +\
'/' + blob_key + '/' + urllib.quote(
result['name'].encode('utf-8'), '')
results.append(result)
#result = {'files': results}
s = json.dumps(results, separators=(',', ':'))
redirect = self.request.get('redirect')
if redirect:
return self.redirect(str(
redirect.replace('%s', urllib.quote(s, ''), 1)
))
if 'application/json' in self.request.headers.get('Accept'):
self.response.headers['Content-Type'] = 'application/json'
self.response.write(s)