本文整理汇总了Python中sendfile.sendfile函数的典型用法代码示例。如果您正苦于以下问题:Python sendfile函数的具体用法?Python sendfile怎么用?Python sendfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendfile函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: respuesta
def respuesta(sock):
try:
OUT = sock.makefile()
http_command = OUT.readline()
headers = []
command = http_command.split()
# print "Commando:", command
for line in OUT:
if line.strip() == "":
break
headers.append(line)
if command[0] == "GET":
if command[1] == "/":
filename = document_root + "/index.html"
else:
filename = document_root + command[1]
try:
FILE = open(filename, "rb")
# print "Sending", filename
m = mim.guess_type(filename)
size = os.stat(filename)[ST_SIZE]
mod = os.stat(filename)[ST_MTIME]
t = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(mod))
OUT.write("HTTP/1.0 200 OK\r\n")
OUT.write("Last-Modified: %s\r\n" % t)
OUT.write("Content-Type: %s\r\n" % m[0])
OUT.write("Content-Length: %d\r\n\r\n" % size)
OUT.flush()
sendfile.sendfile(OUT.fileno(), FILE.fileno(), 0, size)
except IOError:
OUT.write("HTTP 404 Fichero no existe\r\n")
# print "Error con", filename
except Exception, e:
print "Error en la conexión", e
开发者ID:vtomasr5,项目名称:adsopy,代码行数:34,代码来源:quechua.py
示例2: test_flags
def test_flags(self):
try:
sendfile.sendfile(self.sockno, self.fileno, 0, BUFFER_LEN, flags=sendfile.SF_NODISKIO)
except OSError:
err = sys.exc_info()[1]
if err.errno not in (errno.EBUSY, errno.EAGAIN):
raise
开发者ID:hkucs,项目名称:dtn-client,代码行数:7,代码来源:test_sendfile.py
示例3: _download
def _download(self, image_href, data=None, method='data'):
"""Calls out to Glance for data and writes data.
:param image_href: The opaque image identifier.
:param data: (Optional) File object to write data to.
"""
image_id = service_utils.parse_image_id(image_href)
if 'file' in CONF.glance.allowed_direct_url_schemes:
location = self._get_location(image_id)
url = urlparse.urlparse(location)
if url.scheme == "file":
with open(url.path, "r") as f:
filesize = os.path.getsize(f.name)
sendfile.sendfile(data.fileno(), f.fileno(), 0, filesize)
return
image_chunks = self.call(method, image_id)
# NOTE(dtantsur): when using Glance V2, image_chunks is a wrapper
# around real data, so we have to check the wrapped data for None.
if image_chunks.wrapped is None:
raise exception.ImageDownloadFailed(
image_href=image_href, reason=_('image contains no data.'))
if data is None:
return image_chunks
else:
for chunk in image_chunks:
data.write(chunk)
开发者ID:michaeltchapman,项目名称:ironic,代码行数:29,代码来源:base_image_service.py
示例4: stream
def stream(request, path):
basedir = Directory.get_basedir().absolute_path()
file_path = str(basedir / path)
mime_type = 'audio/ogg'
if(file_path.lower().endswith(('mp3', 'ogg', 'flac'))):
return sendfile(
request,
file_path,
attachment=False,
mimetype=mime_type,
)
file_path_without_ext = os.path.splitext(file_path)[0]
new_file_path = '/tmp' + file_path_without_ext + '.ogg'
if not os.path.isfile(new_file_path):
transcode_audio(file_path, new_file_path)
return StreamingHttpResponse(
stream_audio(file_path),
content_type=mime_type
)
return sendfile(
request,
new_file_path,
root_url='/tmp' + settings.SENDFILE_URL,
root_directory='/tmp' + settings.SENDFILE_ROOT,
attachment=False,
mimetype=mime_type,
)
开发者ID:pando85,项目名称:sharemusic,代码行数:32,代码来源:views.py
示例5: _download
def _download(self, image_href, data=None, method='data'):
"""Calls out to Glance for data and writes data.
:param image_id: The opaque image identifier.
:param data: (Optional) File object to write data to.
"""
image_id = service_utils.parse_image_ref(image_href)[0]
if (self.version == 2 and
'file' in CONF.glance.allowed_direct_url_schemes):
location = self._get_location(image_id)
url = urlparse.urlparse(location)
if url.scheme == "file":
with open(url.path, "r") as f:
filesize = os.path.getsize(f.name)
sendfile.sendfile(data.fileno(), f.fileno(), 0, filesize)
return
image_chunks = self.call(method, image_id)
if data is None:
return image_chunks
else:
for chunk in image_chunks:
data.write(chunk)
开发者ID:Tehsmash,项目名称:ironic,代码行数:26,代码来源:base_image_service.py
示例6: respuesta
def respuesta(sock):
try:
OUT = sock.makefile()
http_command = OUT.readline()
headers = []
command = http_command.split()
#print "Commando:", command
for line in OUT:
if line.strip() == "": break
headers.append(line)
if command[0] == "GET":
if command[1] == "/":
filename = document_root + "/index.html"
else:
filename = document_root + command[1]
try:
FILE = open(filename, "rb")
#print "Sending", filename
OUT.write("HTTP/1.0 200 Va be\r\n")
last_modified = os.stat(filename)[ST_MTIME]
OUT.write("Last-Modified: %s \r\n" % last_modified)
content_type = mimetypes.guess_type(filename)
OUT.write("Content-Type: %s\r\n" % content_type[0])
size = os.stat(filename)[ST_SIZE]
OUT.write("Content-Length: %s\r\n\r\n" % size)
OUT.flush()
sendfile.sendfile(OUT.fileno(), FILE.fileno(), 0, size)
except IOError:
OUT.write("HTTP 404 Fichero no existe\r\n")
print "Error con", filename
except TypeError,e: #Exception, e:
print "Error en la conexión", e
开发者ID:andreuramos,项目名称:adso-http,代码行数:35,代码来源:httpd.py
示例7: download
def download(self, image_href, image_file):
"""Downloads image to specified location.
:param image_href: Image reference.
:param image_file: File object to write data to.
:raises: exception.ImageRefValidationFailed if source image file
doesn't exist.
:raises: exception.ImageDownloadFailed if exceptions were raised while
writing to file or creating hard link.
"""
source_image_path = self.validate_href(image_href)
dest_image_path = image_file.name
local_device = os.stat(dest_image_path).st_dev
try:
# We should have read and write access to source file to create
# hard link to it.
if (local_device == os.stat(source_image_path).st_dev and
os.access(source_image_path, os.R_OK | os.W_OK)):
image_file.close()
os.remove(dest_image_path)
os.link(source_image_path, dest_image_path)
else:
filesize = os.path.getsize(source_image_path)
with open(source_image_path, 'rb') as input_img:
sendfile.sendfile(image_file.fileno(), input_img.fileno(),
0, filesize)
except Exception as e:
raise exception.ImageDownloadFailed(image_href=image_href,
reason=e)
开发者ID:Pratyusha9,项目名称:ironic,代码行数:29,代码来源:image_service.py
示例8: copy_data
def copy_data(data_length, blocksize, infp, outfp):
# type: (int, int, BinaryIO, BinaryIO) -> None
'''
A utility function to copy data from the input file object to the output
file object. This function will use the most efficient copy method available,
which is often sendfile.
Parameters:
data_length - The amount of data to copy.
blocksize - How much data to copy per iteration.
infp - The file object to copy data from.
outfp - The file object to copy data to.
Returns:
Nothing.
'''
use_sendfile = False
if have_sendfile:
# Python 3 implements the fileno method for all file-like objects, so
# we can't just use the existence of the method to tell whether it is
# available. Instead, we try to assign it, and if we fail, then we
# assume it is not available.
try:
x_unused = infp.fileno() # NOQA
y_unused = outfp.fileno() # NOQA
use_sendfile = True
except (AttributeError, io.UnsupportedOperation):
pass
if use_sendfile:
# This is one of those instances where using the file object and the
# file descriptor causes problems. The sendfile() call actually updates
# the underlying file descriptor, but the file object does not know
# about it. To get around this, we instead get the offset, allow
# sendfile() to update the offset, then manually seek the file object
# to the right location. This ensures that the file object gets updated
# properly.
in_offset = infp.tell()
out_offset = outfp.tell()
sendfile(outfp.fileno(), infp.fileno(), in_offset, data_length)
infp.seek(in_offset + data_length)
outfp.seek(out_offset + data_length)
else:
left = data_length
readsize = blocksize
while left > 0:
if left < readsize:
readsize = left
data = infp.read(readsize)
# We have seen ISOs in the wild (Tribes Vengeance 1of4.iso) that
# lie about the size of their files, causing reads to fail (since
# we hit EOF before the supposed end of the file). If we are using
# sendfile above, sendfile just silently returns as much data as it
# can, with no additional checking. We should do the same here, so
# if we got less data than we asked for, abort the loop silently.
data_len = len(data)
if data_len != readsize:
data_len = left
outfp.write(data)
left -= data_len
开发者ID:clalancette,项目名称:pyiso,代码行数:59,代码来源:utils.py
示例9: test_invalid_offset
def test_invalid_offset(self):
try:
sendfile.sendfile(self.sockno, self.fileno, -1, BUFFER_LEN)
except OSError:
err = sys.exc_info()[1]
self.assertEqual(err.errno, errno.EINVAL)
else:
self.fail("exception not raised")
开发者ID:4sp1r3,项目名称:pysendfile,代码行数:8,代码来源:test_sendfile.py
示例10: handle
def handle (self):
if sendfile.has_sf_hdtr:
#print sendfile.sendfile(self.request.fileno(), datafile.fileno(), 0, 0, (["HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Connection: close\r\n\r\n"], 'test'))
print sendfile.sendfile(self.request.fileno(), datafile.fileno(), 0, 0, ["HTTP/1.1 200 OK\r\n", "Content-Type: text/html\r\n", "Connection: close\r\n\r\n"])
#print sendfile.sendfile(self.request.fileno(), datafile.fileno(), 0, 0, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: close\r\n\r\n", 'test')
else:
print sendfile.sendfile(self.request.fileno(), datafile.fileno(), 0, 0)
self.request.close()
开发者ID:j4cbo,项目名称:chiral,代码行数:8,代码来源:test.py
示例11: test_trailer
def test_trailer(self):
with open(TESTFN2, "wb") as f:
f.write(b("abcde"))
with open(TESTFN2, "rb") as f:
sendfile.sendfile(self.sockno, f.fileno(), 0, trailer=b("12345"))
time.sleep(0.1)
self.client.close()
self.server.wait()
data = self.server.handler_instance.get_data()
self.assertEqual(data, b("abcde12345"))
开发者ID:hkucs,项目名称:dtn-client,代码行数:10,代码来源:test_sendfile.py
示例12: custom_resource
def custom_resource(request, user_id, res_type):
if request.user.id != int(user_id):
return HttpResponseForbidden("You are not allowed to view this resource.")
customization = get_object_or_404(UserCustomization, user_id=user_id)
if res_type == "css":
if customization.custom_css:
return sendfile.sendfile(request, customization.custom_css.path)
elif res_type == "js":
if customization.custom_js:
return sendfile.sendfile(request, customization.custom_js.path)
return HttpResponseNotFound("Requested resource does not exist.")
开发者ID:sairon,项目名称:score-phorum,代码行数:12,代码来源:views.py
示例13: write_chunk
def write_chunk(stream, chunk_fpath, payloadlen, prefix):
stream.write(prefix)
use_sendfile = configuration.use_sendfile
if use_sendfile:
sendfile(stream, chunk_fpath, payloadlen)
else:
with open(chunk_fpath, 'rb') as f:
stream.write(f.read())
if stream.closed():
logger.error("Write to DVR failed")
开发者ID:BradburyLab,项目名称:show_tv,代码行数:12,代码来源:dvr_writer.py
示例14: write
def write():
if not lcls.strm:
yield gen.Task(reconnect)
if lcls.strm.closed():
yield gen.Task(reconnect)
strm = lcls.strm
if strm.closed():
print('failed to connect')
return
yield gen.Task(write_string, strm, b"Hello, world")
def on_queue_change(change):
lcls.q_len += change
print("Write queue size:", lcls.q_len)
strm.on_queue_change = on_queue_change
#fname = '/home/muravyev/opt/bl/f451/git/show_tv/test-data/dump1.txt'
fname = os.path.expanduser("~/opt/bl/f451/tmp/test_src/pervyj-720x406.ts")
sz = os.stat(fname).st_size
a_str = b"abcbx"
cnt = 3
yield gen.Task(write_number, strm, cnt*(sz + len(a_str)))
for i in range(cnt):
sendfile(strm, fname, sz)
strm.write(a_str)
with open(fname, "rb") as f:
m = make_hash_obj()
txt = f.read()
for i in range(cnt):
m.update(txt)
m.update(a_str)
yield gen.Task(finish_packet, strm, m)
# запись подряд 2х строк
s1 = b"|".join([b"aaaa" for i in range(1000000)])
s11 = s1 + s1
m = make_hash_obj()
m.update(s11)
yield gen.Task(write_number, strm, len(s11))
strm.write(s1)
strm.write(s1)
yield gen.Task(finish_packet, strm, m)
yield gen.Task(write_string, strm, b"Bye, world")
# конец передачи данных
yield gen.Task(write_number, strm, 0)
close_and_one_second_pause(strm)
开发者ID:BradburyLab,项目名称:show_tv,代码行数:53,代码来源:test_sendfile.py
示例15: test_non_socket
def test_non_socket(self):
fd_in = open(TESTFN, 'rb')
fd_out = open(TESTFN2, 'wb')
try:
sendfile.sendfile(fd_in.fileno(), fd_out.fileno(), 0, BUFFER_LEN)
except OSError:
err = sys.exc_info()[1]
self.assertEqual(err.errno, errno.EBADF)
else:
self.fail("exception not raised")
finally:
fd_in.close()
fd_out.close()
开发者ID:4sp1r3,项目名称:pysendfile,代码行数:13,代码来源:test_sendfile.py
示例16: copyfile
def copyfile(self, source, outputfile, closeSource=True):
if sendfile and isinstance(source, file):
# use sendfile(2) for high performance static file serving
sfileno=source.fileno()
size=os.fstat(sfileno).st_size
outputfile.flush()
sendfile(outputfile.fileno(), sfileno, 0, size)
source.close()
else:
# source is not a true file or sendfile(2) is unavailable, use regular write method
try:
shutil.copyfileobj(source, outputfile, length=32*1024)
except socket.error,x:
log.error("Socket error during copyfile: "+str(x))
开发者ID:20after4,项目名称:Yaki,代码行数:14,代码来源:server_ssl.py
示例17: __iter__
def __iter__(self):
class OfLength:
def __init__(self, len):
self.len = len
def __len__(self):
return self.len
while self.sending:
try:
sent = sendfile.sendfile(self.connection.sock.fileno(),
self.body.fileno(),
self.offset,
CHUNKSIZE)
except OSError as e:
# suprisingly, sendfile may fail transiently instead of
# blocking, in which case we select on the socket in order
# to wait on its return to a writeable state before resuming
# the send loop
if e.errno in (errno.EAGAIN, errno.EBUSY):
wlist = [self.connection.sock.fileno()]
rfds, wfds, efds = select.select([], wlist, [])
if wfds:
continue
raise
self.sending = (sent != 0)
self.offset += sent
yield OfLength(sent)
开发者ID:blackantcloud,项目名称:glance,代码行数:29,代码来源:client.py
示例18: archive_download
def archive_download(request, archive_uid=None):
try:
archive\
= models.ExperimentDataExport.objects.get(short_uid=archive_uid)
return sendfile(request,
filename=archive.filepath,
mimetype='application/x-tar',
attachment=True,
attachment_filename=archive.attachment_filename)
except ObjectDoesNotExist as e:
raise Http404(
"data archive {archive_name} does not exist.".format(archive_uid)
)
except MultipleObjectsReturned as e:
logger.warning('Multiple objects returned: %s' % e.message)
raise Http404(
"Can not return data archive {archive_name}.".format(archive_uid)
)
开发者ID:lawsofthought,项目名称:wilhelmproject,代码行数:25,代码来源:views.py
示例19: get
def get(self, request, *args, **kwargs):
album = self.get_object()
reuse_zip = AlbumDownload.objects.filter(
album=album, timestamp__gte=album.last_upload, failed=False
).exists()
filename = os.path.join(settings.SENDFILE_ROOT, 'albums',
str(album.user_id), str(album.id),
'{}.zip'.format(album.id))
if not reuse_zip:
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
download = AlbumDownload.objects.create(album=album, downloader=request.user, failed=True)
with zipfile.ZipFile(filename, 'w') as ziph:
for photo in album.photo_set.filter(trash=False):
if not photo.exists:
logger.warn('Missing photo: %d' % photo.id)
continue
image = photo.image.path
ziph.write(image, os.path.split(image)[1])
download.failed = False
download.save()
return sendfile(request, filename, attachment=True)
开发者ID:modelbrouwers,项目名称:modelbrouwers,代码行数:28,代码来源:public.py
示例20: get_file
def get_file(request, slug, attachment_id, filename):
attachment = get_object_or_404(Attachment, id=attachment_id, page__slug=slug)
as_attachment = ((not imghdr.what(attachment.file.path) and 'embed' not in request.GET)
or 'as_attachment' in request.GET)
# ref https://github.com/johnsensible/django-sendfile
return sendfile(request, attachment.file.path,
attachment=as_attachment, attachment_filename=text_type(attachment))
开发者ID:ralsina,项目名称:waliki,代码行数:7,代码来源:views.py
注:本文中的sendfile.sendfile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论