本文整理汇总了Python中mkt.site.storage_utils.public_storage.open函数的典型用法代码示例。如果您正苦于以下问题:Python open函数的具体用法?Python open怎么用?Python open使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了open函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_preview_rotated
def test_preview_rotated(self):
addon = Webapp.objects.get(pk=337141)
preview = Preview.objects.create(addon=addon)
src = self.get_image('preview_landscape.jpg')
tasks.resize_preview(src, preview.pk)
preview = preview.reload()
eq_(preview.image_size, [533, 400])
eq_(preview.thumbnail_size, [133, 100])
eq_(preview.is_landscape, True)
with public_storage.open(preview.thumbnail_path) as fp:
im = Image.open(fp)
eq_(list(im.size), [133, 100])
with public_storage.open(preview.image_path) as fp:
im = Image.open(fp)
eq_(list(im.size), [533, 400])
示例2: create_export
def create_export(self, name):
with self.settings(DUMPED_APPS_PATH=self.export_directory):
export_data(name=name)
tarball_path = os.path.join(self.export_directory, "tarballs", name + ".tgz")
self.tarfile_file = public_storage.open(tarball_path)
self.tarfile = tarfile.open(fileobj=self.tarfile_file)
return self.tarfile
示例3: perform_create
def perform_create(self, serializer):
"""Download and validate image URL."""
imgs = []
for image_field, hash_field, suffix in self.image_fields:
if serializer.validated_data.get(image_field):
img_url = serializer.validated_data[image_field]
img, hash_ = image_from_url(img_url)
# Store img for `post_save` where we have access to the pk so
# we can save img in appropriate directory.
imgs.append((suffix, img, hash_))
serializer.validated_data[hash_field] = hash_
elif (
serializer.validated_data.get("type")
or (serializer.instance and getattr(serializer.instance, "type", None))
) == feed.COLLECTION_PROMO:
# Remove background images for promo collections.
serializer.validated_data[hash_field] = None
if image_field in serializer.validated_data:
del serializer.validated_data[image_field]
obj = serializer.save()
for suffix, image, hash_ in imgs:
if image:
i = Image.open(image)
path = obj.image_path(suffix)
with public_storage.open(path, "wb") as f:
i.save(f, "png")
pngcrush_image.delay(path, set_modified_on=[obj])
示例4: save_icon
def save_icon(obj, icon_content):
"""
Saves the icon for `obj` to its final destination. `obj` can be an app or a
website.
"""
tmp_dst = os.path.join(settings.TMP_PATH, 'icon', uuid.uuid4().hex)
with public_storage.open(tmp_dst, 'wb') as fd:
fd.write(icon_content)
dirname = obj.get_icon_dir()
destination = os.path.join(dirname, '%s' % obj.pk)
remove_icons(destination)
icon_hash = resize_icon(tmp_dst, destination, mkt.CONTENT_ICON_SIZES,
set_modified_on=[obj], src_storage=public_storage,
dst_storage=public_storage)
# Need to set icon type so .get_icon_url() works normally
# submit step 4 does it through AppFormMedia, but we want to beat them to
# the punch. resize_icon outputs pngs so we know it's 'image/png'.
obj.icon_hash = icon_hash['icon_hash'] # In case, we're running not async.
try:
obj.icon_type = 'image/png'
except AttributeError:
# icon_type can be just a @property on models that only implement png.
pass
obj.save()
示例5: collection
def collection(apps, slug, background_image=True, **kw):
region = REGIONS_DICT[kw.get('region', 'restofworld')].id
colorname = kw.get('color', random.choice(COLLECTION_COLORS.keys()))
co = FeedCollection.objects.create(
type=kw.get('type', 'listing'),
color=colorname,
background_color=COLLECTION_COLORS[colorname],
slug=slug,
description=kw.get('description', ''))
name = kw.get('name', 'Collection %s' % co.pk)
if background_image:
gen = pydenticon.Generator(8, 8, foreground=foreground)
img = gen.generate(name, 128, 128,
output_format='png')
with public_storage.open(co.image_path(''), 'wb') as f:
f.write(img)
image_hash = hashlib.md5(img).hexdigest()[:8]
else:
image_hash = None
co.name = name
co.image_hash = image_hash
co.save()
for a in apps:
FeedCollectionMembership.objects.create(obj=co, app=a)
FeedItem.objects.create(item_type='collection', collection=co,
region=region)
return co
示例6: _no_sign
def _no_sign(src, dst_path):
# If this is a local development instance, just copy the file around
# so that everything seems to work locally.
log.info('Not signing the app, no signing server is active.')
with public_storage.open(dst_path, 'w') as dst_f:
shutil.copyfileobj(src, dst_f)
示例7: test_saves_promo_img
def test_saves_promo_img(self, requests_mock, crush_mock):
img_path = os.path.join(settings.ROOT, 'mkt', 'site', 'tests',
'images', 'game_1050.jpg')
# Mock the image fetch request.
with open(img_path, 'r') as content:
requests_mock.return_value = mock.Mock(
content=content.read(),
headers={'ok': 'ok'},
status_code=200)
result = fetch_promo_imgs(self.website.pk, 'http://mocked_url.ly')
ok_(result)
website = Website.objects.all()[0]
eq_(website.promo_img_hash, '215dd2a2')
# Check the actual saved image on disk.
img_dir = website.get_promo_img_dir()
for size in mkt.PROMO_IMG_SIZES:
img_path = os.path.join(img_dir, '%s-%s.png' % (str(website.id),
size))
with public_storage.open(img_path, 'r') as img:
checker = ImageCheck(img)
assert checker.is_image()
eq_(checker.img.size[0], size)
示例8: test_pngcrush_image_is_called
def test_pngcrush_image_is_called(self, mock_move):
expected_suffix = '.opti.png'
tmp_src = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
tmp_dest = os.path.splitext(tmp_src.name)[0] + expected_suffix
copy_stored_file(self.img_path, tmp_dest, src_storage=public_storage,
dst_storage=local_storage)
with mock.patch('tempfile.NamedTemporaryFile',
lambda *a, **k: tmp_src):
rval = tasks.pngcrush_image(self.img_path)
# pngcrush_image copies the stored file to a local tempfile.
eq_(open(tmp_src.name).read(),
public_storage.open(self.img_path).read())
expected_cmd = ['pngcrush', '-q', '-rem', 'alla', '-brute', '-reduce',
'-e', expected_suffix, tmp_src.name]
# pngcrush_image incokes pngcrush with the tempfile name and writes to
# another tempfile.
self.mock_popen.assert_called_once_with(
expected_cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
# The output file is then copied back to storage.
mock_move.assert_called_once_with(tmp_dest, self.img_path,
dst_storage=public_storage,
src_storage=local_storage)
eq_(rval, {'image_hash': 'bb362450'})
示例9: test_upload_sign_error_existing
def test_upload_sign_error_existing(self, sign_app_mock):
sign_app_mock.side_effect = SigningError
langpack = self.create_langpack()
eq_(LangPack.objects.count(), 1)
original_uuid = langpack.uuid
original_file_path = langpack.file_path
original_file_version = langpack.file_version
original_version = langpack.version
# create_langpack() doesn't create a fake file, let's add one.
with public_storage.open(langpack.file_path, 'w') as f:
f.write('.')
upload = self.upload('langpack')
with self.assertRaises(SigningError):
LangPack.from_upload(upload, instance=langpack)
# Test that we didn't delete the upload file
ok_(private_storage.exists(upload.path))
# Test that we didn't delete the existing filename or alter the
# existing langpack in the database.
eq_(LangPack.objects.count(), 1)
langpack.reload()
eq_(original_uuid, langpack.uuid)
eq_(langpack.file_path, original_file_path)
eq_(original_file_version, langpack.file_version)
eq_(original_version, langpack.version)
ok_(public_storage.exists(langpack.file_path))
# Cleanup
public_storage.delete(langpack.file_path)
示例10: test_unhide_disabled_files
def test_unhide_disabled_files(self):
f = File.objects.get()
f.status = mkt.STATUS_PUBLIC
with private_storage.open(f.guarded_file_path, 'wb') as fp:
fp.write('some data\n')
f.unhide_disabled_file()
assert public_storage.exists(f.file_path)
assert public_storage.open(f.file_path).size
示例11: setUp
def setUp(self):
self.export_directory = mkdtemp()
self.existing_tarball = os.path.join(self.export_directory, "tarballs", "2004-08-15")
with public_storage.open(self.existing_tarball, "w") as fd:
fd.write(".")
self.app_path = "apps/337/337141.json"
self.tarfile_file = None
self.tarfile = None
示例12: test_inject_ids
def test_inject_ids(self, post):
post().status_code = 200
post().content = '{"zigbert.rsa": ""}'
packaged.sign(self.version.pk)
zf = zipfile.ZipFile(public_storage.open(self.file.signed_file_path),
mode='r')
ids_data = zf.read('META-INF/ids.json')
eq_(sorted(json.loads(ids_data).keys()), ['id', 'version'])
示例13: setUp
def setUp(self):
self.export_directory = mkdtemp()
self.existing_tarball = os.path.join(
self.export_directory, 'tarballs', '2004-08-15')
with public_storage.open(self.existing_tarball, 'w') as fd:
fd.write('.')
self.app_path = 'apps/337/337141.json'
self.tarfile_file = None
self.tarfile = None
示例14: check_delete
def check_delete(self, file_, filename):
"""Test that when the File object is deleted, it is removed from the
filesystem."""
try:
with public_storage.open(filename, 'w') as f:
f.write('sample data\n')
assert public_storage.exists(filename)
file_.delete()
assert not public_storage.exists(filename)
finally:
if public_storage.exists(filename):
public_storage.delete(filename)
示例15: post_save
def post_save(self, obj, created=True):
"""Store image that we attached to the obj in pre_save."""
for image_field, hash_field, suffix in self.image_fields:
image = getattr(obj, '_%s' % image_field, None)
if image:
i = Image.open(image)
path = obj.image_path(suffix)
with public_storage.open(path, 'wb') as f:
i.save(f, 'png')
pngcrush_image.delay(path, set_modified_on=[obj])
return super(ImageURLUploadMixin, self).post_save(obj, created)