本文整理汇总了Python中django.core.files.uploadedfile.TemporaryUploadedFile.write方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryUploadedFile.write方法的具体用法?Python TemporaryUploadedFile.write怎么用?Python TemporaryUploadedFile.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.core.files.uploadedfile.TemporaryUploadedFile
的用法示例。
在下文中一共展示了TemporaryUploadedFile.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: TemporaryFileUploadHandler
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
class TemporaryFileUploadHandler(FileUploadHandler):
"""
Upload handler that streams data into a temporary file.
"""
def __init__(self, *args, **kwargs):
super(TemporaryFileUploadHandler, self).__init__(*args, **kwargs)
def new_file(self, file_name, *args, **kwargs):
"""
Create the file object to append to as data is coming in.
"""
super(TemporaryFileUploadHandler, self).new_file(
file_name, *args, **kwargs)
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0,
self.charset,
self.content_type_extra)
def receive_data_chunk(self, raw_data, start):
self.file.write(raw_data)
def file_complete(self, file_size):
self.file.seek(0)
self.file.size = file_size
return self.file
示例2: handle_filedrop_upload
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def handle_filedrop_upload(request):
"""
Squeeze out an UploadedFile from a request sent through FileDrop.js.
FileDrop.js's AJAX mode passes the actual file data
as an unembellished binary stream as the POST payload
so we need to do some magic that normal (multipart/form-data)
uploads would not require.
Here's that magic.
:param request: HTTP request.
:type request: django.http.HttpRequest
:return: Uploaded file.
:rtype: django.core.files.uploadedfile.UploadedFile
"""
content_type = request.META.get("HTTP_X_FILE_TYPE", "")
filename = request.META["HTTP_X_FILE_NAME"]
size = int(request.META["HTTP_X_FILE_SIZE"])
if size >= settings.FILE_UPLOAD_MAX_MEMORY_SIZE:
upload_file = TemporaryUploadedFile(name=filename, content_type=content_type, size=size, charset="binary")
else:
upload_file = InMemoryUploadedFile(
name=filename, content_type=content_type, size=size, charset="binary", field_name="none", file=BytesIO()
)
upload_file.write(request.read())
return upload_file
示例3: decorate
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def decorate(request, *args, **kwargs):
if request.method == 'POST' and 'HTTP_X_FILE_NAME' in request.META:
tf = TemporaryUploadedFile('rawdata', request.META['HTTP_X_FILE_TYPE'], int(request.META['CONTENT_LENGTH']), None)
chunk = ' '
while len(chunk) > 0:
chunk = request.read(1024)
tf.write(chunk)
tf.seek(0)
request.FILES['file'] = tf
return func(request, *args, **kwargs)
示例4: _make_tempfile
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def _make_tempfile(self, filename, content):
fileobj = TemporaryUploadedFile(
name=filename + ".tempfile",
content_type='text/plain',
size=0,
charset='utf8',
)
fileobj.write(content)
fileobj.flush()
return fileobj
示例5: parse_distutils_request
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def parse_distutils_request(request):
"""
Due to a bug in the Python distutils library, the request post is sent using \n
as a separator instead of the \r\n that the HTTP spec demands. This breaks the Django
form parser and therefore we have to write a custom parser.
This bug was fixed in the Python 2.7.4 and 3.4:
http://bugs.python.org/issue10510
"""
if not request.body.endswith('\r\n'):
sep = request.body.splitlines()[1]
request.POST = QueryDict('', mutable=True)
try:
request._files = MultiValueDict()
except Exception:
pass
for part in filter(lambda e: e.strip(), request.body.split(sep)):
try:
header, content = part.lstrip().split('\n', 1)
except Exception:
continue
if content.startswith('\n'):
content = content[1:]
if content.endswith('\n'):
content = content[:-1]
headers = parse_header(header)
if "name" not in headers:
continue
if "filename" in headers and headers['name'] == 'content':
dist = TemporaryUploadedFile(name=headers["filename"],
size=len(content),
content_type="application/gzip",
charset='utf-8')
dist.write(content)
dist.seek(0)
request.FILES.appendlist('distribution', dist)
else:
request.POST.appendlist(headers["name"], content)
else:
request.FILES['distribution'] = request.FILES['content']
# Distutils sends UNKNOWN for empty fields (e.g platform)
for key, value in request.POST.items():
if value == 'UNKNOWN':
request.POST[key] = None
示例6: FeedUploadHandler
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
class FeedUploadHandler(TemporaryFileUploadHandler):
"""
This handler specifically handles feed uploads
"""
QUOTA = 42 * 2 ** 20 # 42 MB
# doesn't seem to be a good way to identify zip files
MIME_TYPES = ("application/zip", "application/x-zip", "application/x-gzip")
def __init__(self, *args, **kwargs):
super(FeedUploadHandler, self).__init__(*args, **kwargs)
self.total_upload = 0
self.file_name = ""
def _validate_file(self):
filename_re = re.compile(r'filename="(?P<name>[^"]+)"')
content_type = str(self.request.META.get("CONTENT_TYPE", ""))
content_length = int(self.request.META.get("CONTENT_LENGTH", 0))
charset = "binary"
m = filename_re.search(self.request.META.get("HTTP_CONTENT_DISPOSITION", ""))
if content_type not in self.MIME_TYPES:
raise IncorrectMimeTypeError("Incorrect mime type", connection_reset=True)
if content_length > self.QUOTA:
raise StopUpload(connection_reset=True)
if not m:
raise FileNameUnspecified("File name not specified", connection_reset=True)
self.file_name = self.file_name = m.group("name")
self.content_type = content_type
self.content_length = content_length
# print content_length
def new_file(self, file_name, *args, **kwargs):
"""
Create the file object to append to as data is coming in.
Ignores and overwrites most of the arguments and relies on exsiting request
"""
super(FeedUploadHandler, self).new_file(file_name, *args, **kwargs)
self._validate_file()
self.file = TemporaryUploadedFile(self.file_name, self.content_type, 0, self.charset)
def receive_data_chunk(self, raw_data, start):
self.total_upload += len(raw_data)
# print "Total upload: {0}".format(self.total_upload)
if self.total_upload >= self.QUOTA:
raise StopUpload(connection_reset=True)
self.file.write(raw_data)
示例7: test_save_tempfile
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def test_save_tempfile(self):
with media_root():
storage = SafeFileSystemStorage()
content = 'Hello world!'
f = TemporaryUploadedFile(name='filename',
content_type='text/plain',
size=len(content),
charset='utf-8')
f.write(content)
f.seek(0)
name = storage.save('hello.txt', f)
self.assertEqual(name, 'hello.txt')
self.assertEqual(open(storage.path(name)).read(), content)
示例8: parse_distutils_request
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def parse_distutils_request(request):
""" This is being used because the built in request parser that Django uses,
django.http.multipartparser.MultiPartParser is interperting the POST data
incorrectly and/or the post data coming from distutils is invalid.
One portion of this is the end marker: \r\n\r\n (what Django expects)
versus \n\n (what distutils is sending).
"""
sep = request.body.splitlines()[1]
request.POST = QueryDict('', mutable=True)
try:
request._files = MultiValueDict()
except Exception:
pass
for part in filter(lambda e: e.strip(), request.body.split(sep)):
try:
header, content = part.lstrip().split('\n', 1)
except Exception:
continue
try:
if content.startswith('\n'):
content = content[1:]
if content.endswith('\n'):
content = content[:-1]
headers = parse_header(header)
if "name" not in headers:
continue
if "filename" in headers:
dist = TemporaryUploadedFile(name=headers["filename"],
size=len(content),
content_type="application/gzip",
charset='utf-8')
dist.write(content)
dist.seek(0)
request.FILES.appendlist(headers['name'], dist)
else:
request.POST.appendlist(headers["name"], content)
except Exception as e:
print e
return
示例9: parse_distutils_request
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def parse_distutils_request(request):
"""Parse the `request.raw_post_data` and return a `MultiValueDict`
for the POST data and the FILES data.
This method is taken from the chishop source.
"""
try:
sep = request.raw_post_data.splitlines()[1]
except:
raise ValueError('Invalid post data')
request.POST = QueryDict('', mutable=True)
try:
request._files = MultiValueDict()
except Exception:
pass
for part in filter(lambda e: e.strip(), request.raw_post_data.split(sep)):
try:
header, content = part.lstrip().split('\n', 1)
except Exception:
continue
if content.startswith('\n'):
content = content[1:]
if content.endswith('\n'):
content = content[:-1]
headers = parse_header(header)
if "name" not in headers:
continue
if "filename" in headers and headers['name'] == 'content':
dist = TemporaryUploadedFile(name=headers["filename"],
size=len(content),
content_type="application/gzip",
charset='utf-8')
dist.write(content)
dist.seek(0)
request.FILES.appendlist('distribution', dist)
else:
# Distutils sends UNKNOWN for empty fields (e.g platform)
# [[email protected]]
if content == 'UNKNOWN':
content = None
request.POST.appendlist(headers["name"], content)
示例10: parse_distutils_request
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def parse_distutils_request(request):
"""Parse the `request.raw_post_data` and update the request POST and FILES
attributes .
"""
lines = request.raw_post_data.splitlines()
seperator = next(line for line in lines if line.startswith('----'))
request.POST = QueryDict('', mutable=True)
raw_post = request.raw_post_data.split(seperator)
raw_lines = [line.lstrip() for line in raw_post if line.lstrip()]
try:
request._files = MultiValueDict()
except Exception:
pass
for line in raw_lines:
line_content = line.lstrip().split('\n', 1)
header = line_content[0]
content = line_content[1]
if content.startswith('\n'):
content = content[1:]
if content.endswith('\n'):
content = content[:-1]
headers = parse_header(header)
if "name" not in headers:
continue
if "filename" in headers and headers['name'] == 'content':
dist = TemporaryUploadedFile(name=headers["filename"],
size=len(content),
content_type="application/gzip",
charset='utf-8')
dist.write(content)
dist.seek(0)
request.FILES.appendlist('distribution', dist)
else:
# Distutils sends UNKNOWN for empty fields (e.g platform)
# [[email protected]]
if content == 'UNKNOWN':
content = None
request.POST.appendlist(headers["name"], content)
示例11: clean
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def clean(self, value):
url = super(ImageFromURLField, self).clean(value)
if url:
wf = urllib.urlopen(url)
if wf.headers.getmaintype() != "image":
raise forms.ValidationError(u"Enter a URL for a valid image.")
importedFile = TemporaryUploadedFile(
url.split("/")[-1], wf.headers.gettype(), int(wf.headers.get("Content-Length")), None
)
importedFile.write(wf.read())
wf.close()
importedFile.seek(0)
if not is_valid_image(importedFile):
raise forms.ValidationError(u"Enter a URL for a valid image.")
return importedFile
return url
示例12: test_image_is_resized_for_setting_size_and_big_image
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def test_image_is_resized_for_setting_size_and_big_image(self):
image_path = get_full_file_path(os.path.join('data', 'big_image.jpg'))
with open(image_path, 'rb') as f:
upload_file = TemporaryUploadedFile(
name='medium_image.jpg',
content_type='image/jpeg',
size=os.path.getsize(image_path),
charset=None
)
upload_file.write(f.read())
image_field = ResizedImageField()
new_image = image_field.clean(upload_file)
tools.assert_not_equals(f, new_image.file)
with Image.open(new_image) as im:
tools.assert_equals(im.size, (300, 150))
示例13: clean_picture
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def clean_picture(self):
""" Ensure that picture is big enough (width & height >= PORTRAIT_PICTURE_MIN_DIMENSION
1) Clears the picture field in the field isn't an uploaded file
2) Detects the size of the uploaded image, and create ValidationError if neccessary
3) Resize the image so it conforms with the minimum size - minimize the space used
"""
min_size = settings.PORTRAIT_PICTURE_MIN_DIMENSION
# If user has ticked to delete his portrait - then the picture attribute can be False
if not self.cleaned_data['picture']:
self.cleaned_data['picture'] = ''
return ''
# Grab content of the Uploaded file and validate size - use StringIO to keep
image_file = self.cleaned_data['picture']
image_data = StringIO(image_file.read())
image = Image.open(image_data)
w, h = image.size
if min(w,h) < min_size:
raise forms.ValidationError('Picture is too small : must be a minimum of %(min)s x %(min)s pixels',
code='invalid',
params={'min':min_size} )
if min(w,h) == min_size:
return self.cleaned_data['picture']
# Resize image to ensure that the smallest size conforms to PORTRAIT_PICTURE_MIN_DIMENSION
ratio = max(min_size/float(w), min_size/float(h))
pic = image.resize((int(w*ratio), int(h*ratio)), Image.ANTIALIAS)
new_image = StringIO()
pic.save(new_image, 'JPEG', quality=90)
# Create a new File for the resized image - can't simply overwrite contents of old file.
new_Temp = TemporaryUploadedFile( name=image_file.name,
content_type= image_file.content_type,
content_type_extra=image_file.content_type_extra,
charset=image_file.charset,
size = new_image.len)
new_Temp.write(new_image.getvalue())
self.cleaned_data['picture'] = new_Temp
return self.cleaned_data['picture']
示例14: AjaxFileUploadSessionMiddleware
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
class AjaxFileUploadSessionMiddleware(object):
chunk_size = 64 * 2 ** 10 # The default chunk size is 64 KB.
def process_request(self, request):
file_name = request.META.get('HTTP_X_FILE_NAME')
self.uploaded_file = None
if ('application/octet-stream' in request.META.get('CONTENT_TYPE')
and request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
and request.method == 'POST'
and file_name):
initial_size = request._stream.remaining
self.uploaded_file = TemporaryUploadedFile(
name=unquote(file_name),
content_type='application/octet-stream',
size=initial_size,
charset=None)
size = 0
while True:
chunk = request._stream.read(self.chunk_size)
if not chunk:
break
size += len(chunk)
self.uploaded_file.write(chunk)
if size != initial_size:
raise HttpResponseBadRequest
self.uploaded_file.seek(0)
self.uploaded_file.size = size
request.FILES['file'] = self.uploaded_file
request.POST = request.GET
def process_response(self, request, response):
if hasattr(self, 'uploaded_file') and self.uploaded_file is not None:
tmp_file_name = self.uploaded_file.file.name
if os.path.exists(tmp_file_name):
os.remove(tmp_file_name)
return response
示例15: test_rack_form_clean_photo
# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import write [as 别名]
def test_rack_form_clean_photo(self):
from fixcity.exif_utils import get_exif_info
from PIL import Image
import os.path
data = self.data.copy()
# Jump through a few hoops to simulate a real upload.
HERE = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(HERE, 'files', 'test_exif.jpg')
content = open(path).read()
photofile = TemporaryUploadedFile('test_exif.jpg', 'image/jpeg',
len(content), None)
photofile.write(content)
photofile.seek(0)
# Okay, now we have something like a file upload.
data['photo'] = photofile
form = RackForm(data, {'photo': photofile})
self.assert_(form.is_valid())
# Make sure it doesn't have a bad rotation.
self.assertEqual({},
get_exif_info(Image.open(photofile.temporary_file_path())))