本文整理汇总了Python中sendfile.sendfile函数的典型用法代码示例。如果您正苦于以下问题:Python sendfile函数的具体用法?Python sendfile怎么用?Python sendfile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了sendfile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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,
)
示例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)
示例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
示例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)
示例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
示例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")
示例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()
示例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"))
示例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.")
示例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")
示例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)
示例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()