本文整理汇总了Python中django.core.files.File方法的典型用法代码示例。如果您正苦于以下问题:Python files.File方法的具体用法?Python files.File怎么用?Python files.File使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.files
的用法示例。
在下文中一共展示了files.File方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_return_label
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def get_return_label(self):
"""Get the GSX return label for this part."""
if self.return_label.name == "":
# Return label not yet set, get it...
label = gsxws.Return(self.return_order).get_label(self.part_number)
filename = "%s_%s.pdf" % (self.return_order, self.part_number)
tmp_fp = os.path.join(settings.TEMP_ROOT, filename)
# move the label to local temp to avoid
# django.security.SuspiciousFileOperation
shutil.move(label.returnLabelFileData, tmp_fp)
f = File(open(tmp_fp, 'r'))
self.return_label = f
self.save()
self.return_label.save(filename, f)
f.closed
os.remove(tmp_fp)
return self.return_label.read()
示例2: setUp
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def setUp(self):
#settings.DEBUG = True
super(BatchImportTestCase, self).setUp()
self.loadAdminBoundaries()
self.test_user = User.objects.create_user('testuser', 'admin@example.com', "mypassword")
from django.core.files import File
batch_file1 = File(open('data/batch_import1.csv'))
batch_file2 = File(open('data/batch_import2.csv'))
batch_file3 = File(open('data/batch_import3.csv'))
self.batch_import_add = BatchImport(name="test batch import just add new", user=self.test_user, batch_file=batch_file1 )
self.batch_import_add_update = BatchImport(name="test batch import add and update", user=self.test_user, batch_file=batch_file2 )
self.batch_import_update_no_id = BatchImport(name="test batch import with no id", user=self.test_user, batch_file=batch_file3 )
batch_file_from_export = File(open('data/gazetteer_results_nypl_church.csv'))
self.batch_import_from_export = BatchImport(name="test batch import with no id", user=self.test_user, batch_file=batch_file_from_export )
self.assertFalse(self.batch_import_add.start_import)
self.assertEquals(None, self.batch_import_add.record_count)
self.assertEquals(None, self.batch_import_add.imported_at)
示例3: test_clean_leftover_should_correctly_clean_after_document_update
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def test_clean_leftover_should_correctly_clean_after_document_update(settings):
document = DocumentFactory(original__from_path=os.path.join(DATA_PATH, 'a-video.mp4'),
preview__from_path=os.path.join(DATA_PATH, 'an-image.jpg'))
old_original_path = document.original.path
preview_path = document.preview.path
with open(os.path.join(DATA_PATH, 'a-pdf.pdf'), 'rb') as f:
document.original = File(f, name='a-pdf.pdf')
document.save()
new_original_path = document.original.path
assert os.path.exists(old_original_path)
assert os.path.exists(new_original_path)
assert os.path.exists(preview_path)
call_command('clean', 'leftover-files')
assert not os.path.exists(old_original_path)
assert os.path.exists(new_original_path)
assert os.path.exists(preview_path)
示例4: create_document
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def create_document(original_dir, preview_dir=''):
form = DocumentForm(
data = {
'title': "A title",
'kind': 'video',
'lang': 'fr',
'credits':'BSF',
'summary': 'summary'},
files = {
'original': File(open(os.path.join(DATA_PATH, 'a-video.mp4'), 'rb'),
name=os.path.join(original_dir, 'a-video.mp4')),
'preview': File(open(os.path.join(DATA_PATH, 'an-image.jpg'), 'rb'),
name=os.path.join(preview_dir, 'an-image.jpg'))
}
)
return form.save()
示例5: do_download_archive
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def do_download_archive(request, content_type, object_id):
object_type = ContentType.objects.get(pk=content_type)
obj = get_object_or_404(object_type.model_class(), pk=object_id)
if not request.user.has_perm('incidents.view_incidents', obj=obj):
raise PermissionDenied()
if obj.file_set.count() == 0:
raise Http404
temp = BytesIO()
with zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) as archive:
media_root = settings.MEDIA_ROOT
for file in obj.file_set.all():
path = os.path.join(media_root, file.file.path)
archive.write(path, os.path.basename(path))
file_size = temp.tell()
temp.seek(0)
wrapper = FileWrapper(temp)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=archive_%s_%s.zip' % (object_type.model, object_id)
response['Content-Length'] = file_size
return response
示例6: setUp
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def setUp(self):
if not os.path.exists(MEDIA_ROOT):
os.makedirs(MEDIA_ROOT)
mock_description = MagicMock(spec=File)
mock_description.name = 'description.md'
mock_description.read = MagicMock(return_value=b'desc')
mock_description.open = MagicMock(return_value=mock_description)
mock_data_opener = MagicMock(spec=File)
mock_data_opener.name = 'opener.py'
mock_data_opener.read = MagicMock(return_value=b'import os')
mock_data_opener.open = MagicMock(return_value=mock_data_opener)
self.datamanager = DataManager.objects.create(name='slide opener',
description=mock_description,
data_opener=mock_data_opener)
self.data_sample_file, self.data_sample_file_filename = get_sample_zip_data_sample()
示例7: test_add_data_sample_ko_not_a_zip
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def test_add_data_sample_ko_not_a_zip(self):
url = reverse('substrapp:data_sample-list')
self.add_default_data_manager()
file_mock = MagicMock(spec=File)
file_mock.name = 'foo.zip'
file_mock.read = MagicMock(return_value=b'foo')
data = {
'file': file_mock,
'json': json.dumps({
'data_manager_keys': [get_hash(self.data_data_opener)],
'test_only': True,
})
}
extra = {
'HTTP_ACCEPT': 'application/json;version=0.0',
}
response = self.client.post(url, data, format='multipart', **extra)
r = response.json()
self.assertEqual(r['message'], 'Archive must be zip or tar.*')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
示例8: get_file_info
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def get_file_info(request: HttpRequest, user_file: File) -> Tuple[str, int, Optional[str]]:
uploaded_file_name = user_file.name
content_type = request.GET.get('mimetype')
if content_type is None:
guessed_type = guess_type(uploaded_file_name)[0]
if guessed_type is not None:
content_type = guessed_type
else:
extension = guess_extension(content_type)
if extension is not None:
uploaded_file_name = uploaded_file_name + extension
uploaded_file_name = urllib.parse.unquote(uploaded_file_name)
uploaded_file_size = user_file.size
return uploaded_file_name, uploaded_file_size, content_type
示例9: upload_realm_icon_image
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def upload_realm_icon_image(self, icon_file: File, user_profile: UserProfile) -> None:
content_type = guess_type(icon_file.name)[0]
s3_file_name = os.path.join(self.realm_avatar_and_logo_path(user_profile.realm), 'icon')
image_data = icon_file.read()
upload_image_to_s3(
self.avatar_bucket,
s3_file_name + ".original",
content_type,
user_profile,
image_data,
)
resized_data = resize_avatar(image_data)
upload_image_to_s3(
self.avatar_bucket,
s3_file_name + ".png",
'image/png',
user_profile,
resized_data,
)
# See avatar_url in avatar.py for URL. (That code also handles the case
# that users use gravatar.)
示例10: upload_emoji_image
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def upload_emoji_image(self, emoji_file: File, emoji_file_name: str,
user_profile: UserProfile) -> None:
content_type = guess_type(emoji_file.name)[0]
emoji_path = RealmEmoji.PATH_ID_TEMPLATE.format(
realm_id=user_profile.realm_id,
emoji_file_name=emoji_file_name,
)
image_data = emoji_file.read()
resized_image_data = resize_emoji(image_data)
upload_image_to_s3(
self.avatar_bucket,
".".join((emoji_path, "original")),
content_type,
user_profile,
image_data,
)
upload_image_to_s3(
self.avatar_bucket,
emoji_path,
content_type,
user_profile,
resized_image_data,
)
示例11: retrieve_poster
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def retrieve_poster(self, url=None, session=None):
if session is None:
session = requests
if url is None:
url = self.ext_poster
if not url:
return False
poster_filename = "{:d}-{:s}".format(self.id, os.path.basename(urlparse(url).path))
# FIXME: Add a get_poster_filename with hash, and use it everywhere
try:
r = session.get(url, timeout=5, stream=True)
except requests.RequestException as e:
return False
try:
with tempfile.TemporaryFile() as f:
for chunk in r.iter_content(chunk_size=1024):
f.write(chunk)
self.ext_poster = url
self.int_poster.save(poster_filename, File(f))
finally:
r.close()
return True
示例12: handle
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def handle(self, *args, **options):
try:
csvfile = open(options['file'], 'rt')
except IOError:
raise CommandError('File does not exist')
expiration_date = options['expiration']
if expiration_date:
expiration_date = datetime.strptime(expiration_date, '%d-%m-%Y')
batch = self._create_batch(**options)
batch.expiration_date = expiration_date
batch.save()
batch.csvfile.save(csvfile.name.split('/')[-1], File(csvfile))
csvfile.seek(0)
try:
batch.csvfile_upload(csvfile, options['password_length'])
except ValidationError:
batch.delete()
self.stdout.write('Error in uploading users from the file')
sys.exit(1)
self.stdout.write('Added a batch of users from a csv file')
csvfile.close()
示例13: publish_set_background
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def publish_set_background(queryset,model,check,mode,logf):
from django.core.files import File
# import pdb; pdb.set_trace()
import time
with open(logf,'w') as f:
proclog = File(f)
f.write("Publishing %s %ss in mode %s at %s<BR>" % ( str(len(queryset)), model, mode, time.asctime()))
for msg in publish_set(queryset,model,check,mode):
if( msg.startswith("Exception") ):
em = "<strong>"
emend = "</strong>"
else:
em = ""
emend = ""
f.write("".join(("<LI>",em,msg,emend,"</LI>")))
f.flush()
f.write ("<BR> publish action finished at %s<BR>" % ( time.asctime(),))
示例14: handle
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def handle(self, *args, **options):
script = options.get('script')
if not script:
if len(args):
script = args[0]
else:
raise CommandError('You must provide a script path or directory containing scripts.')
if not os.path.exists(script):
raise CommandError('{0} does not exist.'.format(script))
group = options.get('group', 'Djangui Scripts')
scripts = [os.path.join(script, i) for i in os.listdir(script)] if os.path.isdir(script) else [script]
converted = 0
for script in scripts:
if script.endswith('.pyc') or '__init__' in script:
continue
if script.endswith('.py'):
sys.stdout.write('Converting {}\n'.format(script))
# copy the script to our storage
with open(script, 'r') as f:
script = default_storage.save(os.path.join(djangui_settings.DJANGUI_SCRIPT_DIR, os.path.split(script)[1]), File(f))
added, error = add_djangui_script(script=os.path.abspath(os.path.join(settings.MEDIA_ROOT, script)), group=group)
if added:
converted += 1
sys.stdout.write('Converted {} scripts\n'.format(converted))
示例15: update_photo
# 需要导入模块: from django.core import files [as 别名]
# 或者: from django.core.files import File [as 别名]
def update_photo(self):
"""
Updates this product image with the GSX part image
"""
if self.component_code and not self.photo:
try:
part = parts.Part(partNumber=self.code)
result = part.fetch_image()
filename = basename(result)
self.photo.save(filename, File(open(result)))
except Exception as e:
print e