本文整理汇总了Python中tempfile.TemporaryFile.tell方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryFile.tell方法的具体用法?Python TemporaryFile.tell怎么用?Python TemporaryFile.tell使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.TemporaryFile
的用法示例。
在下文中一共展示了TemporaryFile.tell方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dataentry
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def dataentry(self):
self.toaster.msgblockbegin("writing to temporary file")
f_tmp = TemporaryFile()
try:
total_padding = self.data.write(f_tmp)
# comparing the files will usually be different because blocks may
# have been written back in a different order, so cheaply just compare
# file sizes
self.toaster.msg("comparing file sizes")
self.stream.seek(0, 2)
f_tmp.seek(0, 2)
if self.stream.tell() != f_tmp.tell():
self.toaster.msg("original size: %i" % self.stream.tell())
self.toaster.msg("written size: %i" % f_tmp.tell())
self.toaster.msg("padding: %i" % total_padding)
if self.stream.tell() > f_tmp.tell() or self.stream.tell() + total_padding < f_tmp.tell():
f_tmp.seek(0)
f_debug = open("debug.cgf", "wb")
f_debug.write(f_tmp.read(-1))
f_debug.close()
raise Exception('write check failed: file sizes differ by more than padding')
finally:
f_tmp.close()
self.toaster.msgblockend()
# spell is finished: prevent recursing into the tree
return False
示例2: T
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
class T(threading.Thread):
_shutdown_msg = "shutdown"
def __init__(self):
threading.Thread.__init__(self)
self._fd = TemporaryFile()
self._comm_fd = TemporaryFile()
self._run = False
def get_file_handle(self):
return self._fd
def run(self):
self._run = True
while self._run:
t1 = time.time()
r, _, _ = select.select([self._fd.fileno(), self._comm_fd.fileno()], [], [])
print "select time:", time.time()-t1
for elem in r:
if elem == self._fd.fileno():
s = self._fd.tell()
self._fd.seek(0, os.SEEK_END) # to the end
e = self._fd.tell()
if s == e: # nothing new
continue
self._fd.seek(-(e-s), os.SEEK_END)
diff = self._fd.read(e-s)
if True:
sys.stdout.write(diff)
sys.stdout.flush()
# exit
elif elem == self._comm_fd.fileno():
self._comm_fd.seek(0, os.SEEK_END)
if self._comm_fd.tell() == len(T._shutdown_msg):
self._run = False
self._comm_fd.write(T._shutdown_msg)
self._comm_fd.flush()
def stop(self):
self._comm_fd.seek(0, os.SEEK_END)
if self._comm_fd.tell() != 0:
return
self._comm_fd.write(T._shutdown_msg)
self._comm_fd.flush()
while self._comm_fd.tell() != 2*len(T._shutdown_msg):
self._comm_fd.seek(0, os.SEEK_END)
def __del__(self, ):
self._fd.close()
示例3: read_file
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def read_file(self, data):
temp_file = TemporaryFile(mode="w+b")
if "content-length" in self.current_headers:
temp_file.write(data.read(self.current_headers["content-length"]))
else:
bytes = data.readline()
while not bytes[-2:] == "\r\n":
temp_file.write(bytes)
bytes = data.readline()
temp_file.write(bytes.rstrip())
filesize = temp_file.tell()
if filesize == 0:
self.read_boundry(data)
return
key = self.current_headers["content-disposition"]["name"]
filename = self.current_headers["content-disposition"].get("filename", "")
content_type = self.current_headers["content-type"]
if key not in self.files:
self.files[key] = []
temp_file.seek(0)
self.files[key].append({"filename":filename, "filesize":filesize, "content-type":content_type, "data":temp_file})
self.read_boundry(data)
示例4: books
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def books(self, oncard=False, end_session=True):
"""
Return a list of ebooks on the device.
@param oncard: If True return a list of ebooks on the storage card,
otherwise return list of ebooks in main memory of device
@return: L{BookList}
"""
root = "/Data/media/"
tfile = TemporaryFile()
if oncard:
try:
self.get_file("a:" + self.CACHE_XML, tfile, end_session=False)
root = "a:/"
except PathError:
try:
self.get_file("b:" + self.CACHE_XML, tfile, end_session=False)
root = "b:/"
except PathError:
pass
if tfile.tell() == 0:
tfile = None
else:
self.get_file(self.MEDIA_XML, tfile, end_session=False)
bl = BookList(root=root, sfile=tfile)
paths = bl.purge_corrupted_files()
for path in paths:
try:
self.del_file(path, end_session=False)
except PathError: # Incase this is a refetch without a sync in between
continue
return bl
示例5: write_lines
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def write_lines(self, key, lines):
self._verify_key_format(key)
storage = self.bucket.new_key(key + ".json.gz")
buff = TemporaryFile()
archive = gzip.GzipFile(fileobj=buff, mode='w')
count = 0
for l in lines:
if hasattr(l, "__iter__"):
for ll in l:
archive.write(ll.encode("utf8"))
archive.write(b"\n")
count += 1
else:
archive.write(l.encode("utf8"))
archive.write(b"\n")
count += 1
archive.close()
file_length = buff.tell()
retry = 3
while retry:
try:
with Timer("Sending {{count}} lines in {{file_length|comma}} bytes", {"file_length": file_length, "count": count}, debug=self.settings.debug):
buff.seek(0)
storage.set_contents_from_file(buff)
break
except Exception, e:
Log.warning("could not push data to s3", cause=e)
retry -= 1
示例6: CandidateUploadFile
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
class CandidateUploadFile(BaseHandler):
def initialize(self):
self.tempfile = TemporaryFile()
@tornado.web.authenticated
@granted()
@tornado.web.asynchronous
def post(self):
fp_url = self.get_argument("url")
mime_type = self.get_argument("data[type]")
size = int(self.get_argument("data[size]"))
candidate_id = self.get_argument("id")
self.candidate = self.db.query(Candidate).get(int(candidate_id))
logging.info("type: %s, size: %r", mime_type, size)
if mime_type == "image/jpeg" and size < MAX_UPLOAD_SIZE:
http_client = tornado.httpclient.AsyncHTTPClient()
request = tornado.httpclient.HTTPRequest(url=fp_url, streaming_callback=self.streaming_callback)
http_client.fetch(request, self.on_download)
else:
self.finish(dict(status=0))
def streaming_callback(self, data):
self.tempfile.write(data)
logging.info("This is the streaming_callback file tell function: %r", self.tempfile.tell())
def on_download(self, response):
img_path = os.path.join(os.path.dirname(__file__), "static/profiles/img/" + str(self.candidate.backup_id) + '.jpg')
self.tempfile.seek(0)
ptr = open(img_path, 'wb')
ptr.write(self.tempfile.read())
ptr.close()
self.tempfile.close()
self.finish(dict(src="/static/profiles/img/" + str(self.candidate.backup_id) + '.jpg', status=1))
示例7: index_html
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def index_html (self, icon=0, preview=0, width=None, height=None,
REQUEST=None):
""" Return the file with it's corresponding MIME-type """
if REQUEST is not None:
if self._if_modified_since_request_handler(REQUEST):
self.ZCacheable_set(None)
return ''
if self._redirect_default_view_request_handler(icon, preview, REQUEST):
return ''
filename, content_type, icon, preview = self._get_file_to_serve(icon, preview)
filename = self._get_fsname(filename)
if _debug > 1: logger.info('serving %s, %s, %s, %s' %(filename, content_type, icon, preview))
if filename:
size = os.stat(filename)[6]
else:
filename = self._get_icon_file(broken=True)
size = os.stat(filename)[6]
content_type = 'image/gif'
icon = 1
if icon==0 and width is not None and height is not None:
data = TemporaryFile() # hold resized image
try:
from PIL import Image
im = Image.open(filename)
if im.mode!='RGB':
im = im.convert('RGB')
filter = Image.BICUBIC
if hasattr(Image, 'ANTIALIAS'): # PIL 1.1.3
filter = Image.ANTIALIAS
im = im.resize((int(width),int(height)), filter)
im.save(data, 'JPEG', quality=85)
except:
data = open(filename, 'rb')
else:
data.seek(0,2)
size = data.tell()
data.seek(0)
content_type = 'image/jpeg'
else:
data = open(filename, 'rb')
if REQUEST is not None:
last_mod = rfc1123_date(self._p_mtime)
REQUEST.RESPONSE.setHeader('Last-Modified', last_mod)
REQUEST.RESPONSE.setHeader('Content-Type', content_type)
REQUEST.RESPONSE.setHeader('Content-Length', size)
self.ZCacheable_set(None)
return stream_iterator(data)
try:
return data.read()
finally:
data.close()
示例8: thumb_img
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def thumb_img(img, width=None, height=None, name='thumb.jpg'):
io = TemporaryFile()
thumb = img.copy()
thumb.thumbnail(image_width_height(img, width, height), Image.ANTIALIAS)
thumb.save(io, format='JPEG', quality=100)
del thumb
size = io.tell()
io.seek(0)
return InMemoryUploadedFile(io, None, name, 'image/jpeg', size, None)
示例9: exportContentInTempFile
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def exportContentInTempFile(self, context, obj_paths=None, filename=None):
""" Export content to a zip file.
"""
objects_list = self._createObjectList(context, obj_paths)
tfile = TemporaryFile()
self._getAllObjectsData(context, objects_list, tfile)
size = tfile.tell()
tfile.seek(0)
return tfile, size
示例10: savefile
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def savefile(fd,fname,bfirmid,bclientid):
# Encrypt each chunk from fd as it is read into a
# tmpfile which will be uploaded to Dropbox using
# the given filename.
r = requests.get("%s/keyserv/key/%s/%s" % (app.config['KEYSERVER_URI'],bfirmid,bclientid))
print "%s/keyserv/key/%s/%s" % (app.config['KEYSERVER_URI'],bfirmid,bclientid)
keyobj = r.json()
encrkey = keyobj['key']
print "Got key %s" % encrkey
# Carve out a 32byte/256 bit key from the keyserver
# but convert base64 back to binary first
bkey = binascii.a2b_base64(encrkey)
key = bkey[0:32]
try:
print "Starting encryption"
# Setup our AES cipher
iv = Random.new().read(AES.block_size)
cipher = AES.new(key,AES.MODE_CFB,iv)
#cipher = XORCipher.new(key)
print "Cipher created using iv %s" % binascii.hexlify(iv)
except:
raise
try:
f = TemporaryFile()
f.write(iv)
for chunk in chunkfd(fd,blocksize=4194304):
f.write(cipher.encrypt(chunk))
f.flush()
f.seek(0,os.SEEK_END)
fsize = f.tell()
f.seek(0)
except Exception as e:
print e
print "Getting ready for Dropbox upload"
# Get a Dropbox uploader
try:
access_token = config.get('Credentials','access_token')
dclient = DropboxClient(access_token)
uploader = dclient.get_chunked_uploader(f,fsize)
while uploader.offset < fsize:
try:
upload = uploader.upload_chunked()
except Exception as e:
print e
except Exception as e:
print e
f.close()
return uploader.finish(secure_filename("/%s_encr" % fname))
示例11: handleExport
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def handleExport(self, action):
data, errors = self.extractData()
if errors:
self.status = self.formErrorsMessage
return
if data['paths']:
objs = data['paths']
else:
objs = [self.context]
message = model.MessageT1()
message.action = data['action']
message.recipient_id = data['recipients']
if data['subject'] is not None:
message.subjects = [data['subject']]
if data['comment'] is not None:
message.comments = [data['comment']]
if data['directive']:
directive = model.Directive(data['directive'])
directive.priority = data['priority']
directive.deadline = data['deadline']
message.directive = directive
journal_entry = _(u'label_exported_as_ech0147',
default=u'Exported as eCH-0147 message')
for obj in objs:
message.add_object(obj)
journal_entry_factory(obj, 'eCH-0147 Export', journal_entry)
header_dom = message.header().toDOM(element_name='eCH-0147T0:header')
message_dom = message.binding().toDOM()
tmpfile = TemporaryFile()
with ZipFile(tmpfile, 'w', ZIP_DEFLATED, True) as zipfile:
zipfile.writestr(
'header.xml', header_dom.toprettyxml(encoding='UTF-8'))
zipfile.writestr(
'message.xml', message_dom.toprettyxml(encoding='UTF-8'))
message.add_to_zip(zipfile)
size = tmpfile.tell()
response = self.request.response
response.setHeader(
"Content-Disposition",
'inline; filename="message.zip"')
response.setHeader("Content-type", "application/zip")
response.setHeader("Content-Length", size)
self.response_body = TempfileStreamIterator(tmpfile, size)
示例12: check_requirements
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def check_requirements():
"Check requirements"
output = TemporaryFile(mode='rwt')
pos = 0
for req in REQUIREMENTS:
if 0 != call(['which', req], stdout=output, stderr=output):
# get call output
output.seek(pos)
err = output.read()
print "ERROR: %s is not satisfied (%s)" % (req, err)
sys.exit(1)
pos = output.tell()
示例13: __init__
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
class BadBoyResponseFilter:
def __init__(self, client):
if not os.path.exists(BAD_CONTENT_TMP_DIR) :
try:
os.makedirs(BAD_CONTENT_TMP_DIR)
except:
pass
self.fd_orig = TemporaryFile(mode='rw+b', dir=BAD_CONTENT_TMP_DIR)
self.fd_filtered = TemporaryFile(mode='rw+b', dir=BAD_CONTENT_TMP_DIR)
self.client = client
def feed(self, data):
self.fd_orig.write(data)
def filter(self):
pass
def send_response(self):
self.fd_orig.seek(0)
self.filter()
self.client.father.transport.write(self.client.bb_status)
for key,value in self.client.bb_headers :
if key.lower() == "content-length" :
value = self.fd_filtered.tell()
self.client.father.transport.write("%s: %s\r\n" % (key, value))
self.client.father.transport.write("\r\n")
file_len = self.fd_filtered.tell()
self.fd_filtered.seek(0)
while self.fd_filtered.tell() < file_len :
self.client.father.transport.write(self.fd_filtered.read(1024))
self.fd_orig.close()
self.fd_filtered.close()
示例14: thumb_crop_img
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
def thumb_crop_img(img, width=None, height=None, name='thumb.jpg'):
"""
Resizes image and crop him if it due proportions
"""
io = TemporaryFile()
thumb = img.copy()
thumb.thumbnail(image_width_height(img, width=width), Image.ANTIALIAS)
if thumb.size[1] >= height:
thumb = thumb.crop((0, 0, width, height))
else:
thumb = thumb.resize((width, height), Image.ANTIALIAS)
thumb.save(io, format='JPEG', quality=100)
del thumb
size = io.tell()
io.seek(0)
return InMemoryUploadedFile(io, None, name, 'image/jpeg', size, None)
示例15: __init__
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import tell [as 别名]
class ContentReceiver:
"Write-only file object used to receive data from FTP"
def __init__(self,callback,*args):
from tempfile import TemporaryFile
self.data = TemporaryFile('w+b')
self.callback = callback
self.args = args
def write(self,data):
self.data.write(data)
def close(self):
size = self.data.tell()
self.data.seek(0)
args = self.args + (self.data, size)
c = self.callback
self.callback = None
self.args = None
c(*args)