本文整理汇总了Python中django.core.files.base.ContentFile方法的典型用法代码示例。如果您正苦于以下问题:Python base.ContentFile方法的具体用法?Python base.ContentFile怎么用?Python base.ContentFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.files.base
的用法示例。
在下文中一共展示了base.ContentFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_export_book_notices
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def test_export_book_notices(staffapp, monkeypatch):
book1 = BookFactory(isbn="123456", name="my book title")
name_utf8 = u'النبي (كتاب)'
BookFactory(isbn="654321", name=name_utf8)
monkeypatch.setattr(BookExport, 'get_filename', lambda s: 'myfilename')
resp = staffapp.get(reverse('library:book_export'))
assert 'myfilename.zip' in resp['Content-Disposition']
content = ContentFile(resp.content)
assert zipfile.is_zipfile(content)
archive = zipfile.ZipFile(content)
cover_name = '{}.jpg'.format(book1.pk)
assert cover_name in archive.namelist()
assert 'myfilename.csv' in archive.namelist()
assert len(archive.namelist()) == 3
csv_content = archive.open('myfilename.csv').read().decode('utf-8')
assert csv_content.startswith(
'isbn,authors,serie,name,subtitle,description,publisher,section,lang,'
'cover,tags\r\n')
assert "my book title" in csv_content
assert cover_name in csv_content
assert name_utf8 in csv_content
示例2: download_media_files
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def download_media_files(self, xml_doc, media_path):
for media_node in xml_doc.getElementsByTagName('mediaFile'):
filename_node = media_node.getElementsByTagName('filename')
url_node = media_node.getElementsByTagName('downloadUrl')
if filename_node and url_node:
filename = filename_node[0].childNodes[0].nodeValue
path = os.path.join(media_path, filename)
if default_storage.exists(path):
continue
download_url = url_node[0].childNodes[0].nodeValue
if self._get_media_response(download_url):
download_res = self._current_response
media_content = ContentFile(download_res.content)
default_storage.save(path, media_content)
self.logger.debug("Fetched %s." % filename)
else:
self.logger.error("Failed to fetch %s." % filename)
示例3: _upload_instance
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def _upload_instance(self, xml_file, instance_dir_path, files):
xml_doc = clean_and_parse_xml(xml_file.read())
xml = StringIO()
de_node = xml_doc.documentElement
for node in de_node.firstChild.childNodes:
xml.write(node.toxml())
new_xml_file = ContentFile(xml.getvalue())
new_xml_file.content_type = 'text/xml'
xml.close()
attachments = []
for attach in de_node.getElementsByTagName('mediaFile'):
filename_node = attach.getElementsByTagName('filename')
filename = filename_node[0].childNodes[0].nodeValue
if filename in files:
file_obj = default_storage.open(
os.path.join(instance_dir_path, filename))
mimetype, encoding = mimetypes.guess_type(file_obj.name)
media_obj = django_file(file_obj, 'media_files[]', mimetype)
attachments.append(media_obj)
create_instance(self.user.username, new_xml_file, attachments)
示例4: _save_thumbnails
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def _save_thumbnails(image, path, size, suffix):
nm = NamedTemporaryFile(suffix='.%s' % settings.IMG_FILE_TYPE)
default_storage = get_storage_class()()
try:
# Ensure conversion to float in operations
image.thumbnail(
get_dimensions(image.size, float(size)), Image.ANTIALIAS)
except ZeroDivisionError:
pass
try:
image.save(nm.name)
except IOError:
# e.g. `IOError: cannot write mode P as JPEG`, which gets raised when
# someone uploads an image in an indexed-color format like GIF
image.convert('RGB').save(nm.name)
default_storage.save(
get_path(path, suffix), ContentFile(nm.read()))
nm.close()
示例5: test_publish_xml_xlsform_download
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def test_publish_xml_xlsform_download(self):
count = XForm.objects.count()
path = os.path.join(
self.this_directory, '..', '..', 'api', 'tests', 'fixtures',
'forms', 'contributions', 'contributions.xml')
f = open(path)
xml_file = ContentFile(f.read())
f.close()
xml_file.name = 'contributions.xml'
self.xform = publish_xml_form(xml_file, self.user)
self.assertTrue(XForm.objects.count() > count)
response = self.client.get(reverse(download_xlsform, kwargs={
'username': self.user.username,
'id_string': 'contributions'
}), follow=True)
self.assertContains(response, 'No XLS file for your form ')
示例6: _contributions_form_submissions
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def _contributions_form_submissions(self):
count = XForm.objects.count()
path = os.path.join(os.path.dirname(__file__),
'..', 'fixtures', 'forms', 'contributions')
form_path = os.path.join(path, 'contributions.xml')
f = open(form_path)
xml_file = ContentFile(f.read())
f.close()
xml_file.name = 'contributions.xml'
self.xform = publish_xml_form(xml_file, self.user)
self.assertTrue(XForm.objects.count() > count)
instances_path = os.path.join(path, 'instances')
for uuid in os.listdir(instances_path):
s_path = os.path.join(instances_path, uuid, 'submission.xml')
create_instance(self.user.username, open(s_path), [])
self.assertEqual(self.xform.instances.count(), 6)
示例7: save
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def save(self):
photo = super(OrganizationForm, self).save()
x = self.cleaned_data.get('x')
y = self.cleaned_data.get('y')
w = self.cleaned_data.get('width')
h = self.cleaned_data.get('height')
if x is not None and y is not None:
image = Image.open(photo.logo)
cropped_image = image.crop((x, y, w+x, h+y))
resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
# resized_image.save(photo.logo.path)
resized_image_file = StringIO.StringIO()
mime = mimetypes.guess_type(photo.logo.name)[0]
plain_ext = mime.split('/')[1]
resized_image.save(resized_image_file, plain_ext)
default_storage.delete(photo.logo.name)
default_storage.save(photo.logo.name, ContentFile(resized_image_file.getvalue()))
resized_image_file.close()
return photo
示例8: save_data_products
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def save_data_products(self, observation_record, product_id=None):
from tom_dataproducts.models import DataProduct
from tom_dataproducts.utils import create_image_dataproduct
final_products = []
products = self.data_products(observation_record.observation_id, product_id)
for product in products:
dp, created = DataProduct.objects.get_or_create(
product_id=product['id'],
target=observation_record.target,
observation_record=observation_record,
)
if created:
product_data = requests.get(product['url']).content
dfile = ContentFile(product_data)
dp.data.save(product['filename'], dfile)
dp.save()
logger.info('Saved new dataproduct: {}'.format(dp.data))
if AUTO_THUMBNAILS:
create_image_dataproduct(dp)
dp.get_preview()
final_products.append(dp)
return final_products
示例9: test_file_save_with_path
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def test_file_save_with_path(self):
"""
Saving a pathname should create intermediate directories as necessary.
"""
self.assertFalse(self.storage.exists("path/to"))
self.storage.save("path/to/test.file", ContentFile("file saved with path"))
self.assertTrue(self.storage.exists("path/to"))
with self.storage.open("path/to/test.file") as f:
self.assertEqual(f.read(), b"file saved with path")
self.assertTrue(
os.path.exists(
os.path.join(
self.temp_dir, connection.schema_name, "path", "to", "test.file"
)
)
)
self.storage.delete("path/to/test.file")
示例10: create_file
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def create_file(webdav_storage):
"""
Creates a file with a unique prefix in the WebDAV storage
"""
from django.core.files.base import ContentFile
from django_webdav_storage.compat import PY3, TEXT_TYPE
def inner(filename, content=b'', prefix=''):
if all((PY3, isinstance(content, TEXT_TYPE))):
content = content.encode('UTF-8')
col = str(uuid.uuid4())
key = os.path.join(prefix.lstrip('/') or col, filename)
webdav_storage.save(key, ContentFile(content, key))
return key
return inner
示例11: create_from_as2mdn
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def create_from_as2mdn(self, as2mdn, message, status, return_url=None):
"""Create the MDN from the pyas2lib's MDN object"""
signed = True if as2mdn.digest_alg else False
mdn, _ = self.update_or_create(
message=message,
defaults=dict(
mdn_id=as2mdn.message_id,
status=status,
signed=signed,
return_url=return_url,
),
)
filename = f"{uuid4()}.mdn"
mdn.headers.save(
name=f"{filename}.header", content=ContentFile(as2mdn.headers_str)
)
mdn.payload.save(filename, content=ContentFile(as2mdn.content))
return mdn
示例12: setUp
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def setUp(self):
self.user = User.objects.create(username="dummy")
with open(os.path.join(TEST_DIR, "client_public.pem"), "rb") as fp:
self.cert = PublicCertificate.objects.create(
name="test-cert", certificate=fp.read()
)
with open(os.path.join(TEST_DIR, "client_private.pem"), "rb") as fp:
self.private_key = PrivateKey.objects.create(
name="test-key", key=fp.read(), key_pass="test"
)
with open(os.path.join(TEST_DIR, "testmessage.edi"), "rb") as fp:
self.message = Message.objects.create(
message_id="some-message-id", direction="IN", status="S",
)
self.message.payload.save("testmessage.edi", fp)
self.mdn = Mdn.objects.create(
mdn_id="some-mdn-id", message=self.message, status="S"
)
self.mdn.payload.save("some-mdn-id.mdn", ContentFile("MDN Content"))
示例13: compile
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def compile(self):
from judge.models import problem_data_storage
yml_file = '%s/init.yml' % self.problem.code
try:
init = yaml.safe_dump(self.make_init())
except ProblemDataError as e:
self.data.feedback = e.message
self.data.save()
problem_data_storage.delete(yml_file)
else:
self.data.feedback = ''
self.data.save()
if init:
problem_data_storage.save(yml_file, ContentFile(init))
else:
# Don't write empty init.yml since we should be looking in manually managed
# judge-server#670 will not update cache on empty init.yml,
# but will do so if there is no init.yml, so we delete the init.yml
problem_data_storage.delete(yml_file)
示例14: install_xsl_file
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def install_xsl_file(apps, label, path=None, file_=None):
XSLFile = apps.get_model('core', 'XSLFile')
if XSLFile.objects.filter(label=label).exists():
return
xsl_file = XSLFile(label=label)
if path:
with open(path, 'r', encoding="utf-8") as f:
file_ = ContentFile(f.read())
file_.name = "default.xsl"
xsl_file.file = file_
xsl_file.save()
elif file_:
xsl_file = file_
xsl_file.save()
else:
raise RuntimeError("No file or path provided for '%s'" % label)
示例15: test_file_field
# 需要导入模块: from django.core.files import base [as 别名]
# 或者: from django.core.files.base import ContentFile [as 别名]
def test_file_field(self):
customer = Customer(**CUSTOMER__KWARGS)
customer.save()
avatar = Avatar()
avatar.customer = customer
avatar.image.save('test_file_secret_data', ContentFile('Super secret data'), save=False)
avatar.save()
avatar_2: Avatar = Avatar.objects.last()
self.assertEqual(avatar_2.image.read(), b'Super secret data')
avatar_2._anonymize_obj(base_encryption_key='LoremIpsumDolorSitAmet')
avatar_3: Avatar = Avatar.objects.last()
self.assertNotEqual(avatar_3.image.read(), b'Super secret data')
# Cleanup
avatar_3.image.delete()
avatar_3.delete()