本文整理汇总了Python中tempfile.TemporaryFile.seek方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryFile.seek方法的具体用法?Python TemporaryFile.seek怎么用?Python TemporaryFile.seek使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tempfile.TemporaryFile
的用法示例。
在下文中一共展示了TemporaryFile.seek方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: image_register
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def image_register(request):
params = request.GET if request.method == "GET" else request.POST
if not ("url" in params):
content = {"message": u"パラメータ`url`が指定されていません"}
return Response(content, status=status.HTTP_400_BAD_REQUEST)
try:
image = Images.objects.get(url=params["url"])
except ObjectDoesNotExist:
image = Images(url=params["url"], adult_flag=False, grotesque_flag=False)
descriptor = factory.descriptor(filepath=image.local_path)
if descriptor == None:
content = {"message": u"ローカルに画像が見つかりません"}
return Response(content, status=status.HTTP_412_PRECONDITION_FAILED)
else:
tmp = TemporaryFile()
try:
np.save(tmp, descriptor)
tmp.seek(0)
image.description = tmp.read()
image.save()
finally:
tmp.close()
return Response(ImageMapper(image).as_dict())
示例2: CandidateUploadFile
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [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))
示例3: test_read_several
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def test_read_several(self):
"""Read several stanzas from file"""
tmpf = TemporaryFile()
tmpf.write("""\
version_header: 1
name: foo
val: 123
name: quoted
address: "Willowglen"
\t 42 Wallaby Way
\t Sydney
name: bar
val: 129319
""")
tmpf.seek(0)
s = read_stanza(tmpf)
self.assertEquals(s, Stanza(version_header='1'))
s = read_stanza(tmpf)
self.assertEquals(s, Stanza(name="foo", val='123'))
s = read_stanza(tmpf)
self.assertEqualDiff(s.get('name'), 'quoted')
self.assertEqualDiff(s.get('address'), ' "Willowglen"\n 42 Wallaby Way\n Sydney')
s = read_stanza(tmpf)
self.assertEquals(s, Stanza(name="bar", val='129319'))
s = read_stanza(tmpf)
self.assertEquals(s, None)
self.check_rio_file(tmpf)
示例4: send_form
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def send_form(self,):
import csv
product = self[0]
#_logger.warning('data %s b64 %s ' % (account.data,base64.decodestring(account.data)))
if not product.data == None:
fileobj = TemporaryFile('w+')
fileobj.write(base64.decodestring(product.data))
fileobj.seek(0)
try:
for row in csv.DictReader(fileobj):
pass
finally:
fileobj.close()
return True
#product.write({'state': 'get', 'name': '%s.xml' % account.model.model.replace('.','_'),'data': base64.b64encode(account._export_xml()) })
return {
'type': 'ir.actions.act_window',
'res_model': 'account.export',
'view_mode': 'form',
'view_type': 'form',
'res_id': product.id,
'views': [(False, 'form')],
'target': 'new',
}
示例5: _getPID
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def _getPID():
"""Get PID from specified PIDFile.
Returns:
int: >0 -- RESTservice PID
-1 -- _pidfile contains invalid PID
-2 -- _pidfile not found
"""
pid = 0
try:
f = open(_pidfile, 'r')
pid = int(f.read())
f.close()
except IOError as e:
if e.errno == 2:
return -2
raise e
except ValueError:
return -1
# Double check PID from PIDFile:
outfile = TemporaryFile(mode='w+')
call(['ps', 'x'], stdout=outfile)
outfile.seek(0)
for line in outfile:
line = line.strip()
if line.startswith(str(pid)) and line.endswith(_script_name):
return pid
return -1
示例6: fix_img_gff_errors
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def fix_img_gff_errors(gff_file):
''' GFF files in the IMG directory can contain errors. This fixes them and returns a file handle to the fixed file
transforms literal semicolon (;) characters in field 9 to their proper percent encoding (%3B)
fixes the CRISPR lines
'''
new_gff = TemporaryFile()
with open(gff_file) as fp:
for ln, line in enumerate(fp):
if line[0] == '#':
new_gff.write(line)
else:
fields = line.split('\t')
if fields[2] == 'CRISPR':
fields[5] = '.'
fields[6] = '?'
fields[7] = '.'
else:
attributes = fields[8]
attribute_kv = attributes.split(';')
new_attributes = []
for i in range(len(attribute_kv)):
if ',' in attribute_kv[i]:
attribute_kv[i] = re.sub(',', '%2C', attribute_kv[i])
if '=' not in attribute_kv[i]:
new_attributes[-1] += '%3B' + attribute_kv[i]
else:
new_attributes.append(attribute_kv[i])
fields[8] = ';'.join(new_attributes)
new_gff.write('\t'.join(fields))
new_gff.seek(0)
return new_gff
示例7: set_sff_trimpoints_with_sfftools
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def set_sff_trimpoints_with_sfftools(
sff_dir, technical_lengths, sffinfo_path='sffinfo', sfffile_path='sfffile',
debug=False):
"""Set trimpoints to end of technical read for all SFF files in directory.
This function essentially provides the reference implementation.
It uses the official sfftools from Roche to process the SFF files.
"""
if not (exists(sffinfo_path) or which(sffinfo_path)):
raise ApplicationNotFoundError(
'sffinfo executable not found. Is it installed and in your $PATH?')
if not (exists(sfffile_path) or which(sfffile_path)):
raise ApplicationNotFoundError(
'sfffile executable not found. Is it installed and in your $PATH?')
for lib_id, sff_fp in get_per_lib_sff_fps(sff_dir):
try:
readlength = technical_lengths[lib_id]
except KeyError:
continue
sffinfo_args = [sffinfo_path, '-s', sff_fp]
if debug:
print "Running sffinfo command %s" % sffinfo_args
sffinfo_output_file = TemporaryFile()
check_call(sffinfo_args, stdout=sffinfo_output_file)
sffinfo_output_file.seek(0)
seqlengths = {}
for line in sffinfo_output_file:
if line.startswith('>'):
fields = line[1:].split()
seq_len = fields[1].split('=')[1]
seqlengths[fields[0]] = seq_len
trim_fp = sff_fp + '.trim'
trim_file = open(trim_fp, 'w')
for id_, length in seqlengths.items():
curr_length = int(seqlengths[id_])
# Sfftools use 1-based index
left_trim = readlength + 1
# Key sequence not included in FASTA length
right_trim = curr_length + 4
if curr_length > left_trim:
trim_file.write(
"%s\t%s\t%s\n" % (id_, left_trim, right_trim))
else:
stderr.write(
'Rejected read %s with trim points %s and %s (orig '
'length %s)' % (id_, left_trim, curr_length, length))
trim_file.close()
trimmed_sff_fp = sff_fp + '.trimmed'
sfffile_args = [
sfffile_path, '-t', trim_fp, '-o', trimmed_sff_fp, sff_fp]
if debug:
print "Running sfffile command:", sfffile_args
check_call(sfffile_args, stdout=open(devnull, 'w'))
remove(sff_fp)
rename(trimmed_sff_fp, sff_fp)
示例8: proxy_stdf
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def proxy_stdf():
"""
Circulate stdout/stderr via a proper file object. Designed to work around a
problem where Python nose replaces sys.stdout/stderr with a custom 'Tee'
object that is not a file object (compatible) and thus causes a crash with
Popen.
"""
tmp_stdout = sys.stdout
try:
tmp_stdout.fileno()
except Exception:
tmp_stdout = TemporaryFile()
tmp_stderr = sys.stderr
try:
tmp_stderr.fileno()
except Exception:
tmp_stderr = TemporaryFile()
try:
yield tmp_stdout, tmp_stderr
finally:
if tmp_stdout != sys.stdout:
tmp_stdout.seek(0)
sys.stdout.write(tmp_stdout.read().decode())
if tmp_stderr != sys.stderr:
tmp_stderr.seek(0)
sys.stderr.write(tmp_stderr.read().decode())
示例9: test_execute_commands
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def test_execute_commands(self):
"""Test executing arbitrary commands and logging their output."""
# All commands succeed.
exp = (True, [])
log_f = TemporaryFile(prefix=self.prefix, suffix='.txt')
obs = _execute_commands(['echo foo', 'echo bar'], log_f, 1)
self.assertEqual(obs, exp)
exp = ("Command:\n\necho foo\n\nStdout:\n\nfoo\n\nStderr:\n\n\n"
"Command:\n\necho bar\n\nStdout:\n\nbar\n\nStderr:\n\n\n")
log_f.seek(0, 0)
obs = log_f.read()
self.assertEqual(obs, exp)
# One command fails.
exp = (False, [])
log_f = TemporaryFile(prefix=self.prefix, suffix='.txt')
obs = _execute_commands(['echo foo', 'foobarbaz'], log_f, 1)
self.assertEqual(obs, exp)
exp = ("Command:\n\necho foo\n\nStdout:\n\nfoo\n\nStderr:\n\n\n"
"Command:\n\nfoobarbaz\n\nStdout:\n\n\nStderr:\n\n\n\n")
log_f.seek(0, 0)
obs = sub('Stderr:\n\n.*\n\n', 'Stderr:\n\n\n\n',
log_f.read())
self.assertEqual(obs, exp)
示例10: generate_minion_keys
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def generate_minion_keys(self):
# XXX TODO: Replace M2Crypto with PyCrypto
# see: https://github.com/saltstack/salt/pull/1112/files
# generate keys
keyname = self.get_keyname()
if not keyname:
LOG.error("Must specify salt_id or hostname")
return False
gen = RSA.gen_key(2048, 1, callback=lambda x, y, z: None)
pubpath = os.path.join(self.pki_dir, "{0}.pub".format(keyname))
gen.save_pub_key(pubpath)
LOG.info("public key {0}".format(pubpath))
if self.config.get("save_keys"):
cumask = os.umask(191)
gen.save_key(os.path.join(self.pki_dir, "{0}.pem".format(keyname)), None)
os.umask(cumask)
# public key
_pub = TemporaryFile()
bio_pub = BIO.File(_pub)
m2.rsa_write_pub_key(gen.rsa, bio_pub._ptr())
_pub.seek(0)
self.config["public_key"] = self.public_key = _pub.read()
self.config["formatted_public_key"] = "\n".join(" {0}".format(k) for k in self.public_key.split("\n"))
# private key
_pem = TemporaryFile()
bio_pem = BIO.File(_pem)
gen.save_key_bio(bio_pem, None)
_pem.seek(0)
self.config["private_key"] = self.private_key = _pem.read()
self.config["formatted_private_key"] = "\n".join(" {0}".format(k) for k in self.private_key.split("\n"))
return True
示例11: _open
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def _open(self):
tmp = TemporaryFile()
resp = requests.get(self.metadata['url'], stream=True)
for chunk in resp.iter_content(256*1024):
tmp.write(chunk)
tmp.seek(0)
return tmp
示例12: run_reduce
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def run_reduce(self):
self.stopped_received = 0
self.merged_files = []
merged_iterator = None
while True:
# Iterate and merge files until all jobs are processed
get_next = self.get_next_file()
files = get_next
# itertools.islice(get_next, self.reduce_max_files)
all_files = [file for file in files]
iterables = [self.iter_on_file(file) for file in all_files]
merged_iterator = heapq.merge(*iterables)
if self.stopped_received < self.numprocs:
if self.debug:
debug_print("Performing intermediate merge on %u files" % len(iterables))
f = TemporaryFile()
self.merged_files.append(f)
for m in merged_iterator:
cPickle.dump(m, f, cPickle.HIGHEST_PROTOCOL)
f.seek(0)
f.flush()
else:
break
if len(self.merged_files) > 0:
if self.debug:
debug_print("Final merge")
# Final merge if required
merged_iterator = heapq.merge(
*([self.iter_on_file(stream) for stream in self.merged_files] + [merged_iterator])
)
if self.debug:
debug_print("Reduce loop")
result = self.reduce_loop(merged_iterator)
return result
示例13: _create_temp_file
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def _create_temp_file(edid_binary):
edid_file = TemporaryFile()
edid_file.write(edid_binary)
edid_file.flush()
edid_file.seek(0)
return edid_file
示例14: to_xml
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def to_xml(self, f=None):
"""Get this domain as an XML DOM Document
:param f: Optional File to dump directly to
:type f: File or Stream
:return: File object where the XML has been dumped to
:rtype: file
"""
if not f:
from tempfile import TemporaryFile
f = TemporaryFile()
print('<?xml version="1.0" encoding="UTF-8"?>', file=f)
print('<Domain id="%s">' % self.name, file=f)
for item in self:
print('\t<Item id="%s">' % item.name, file=f)
for k in item:
print('\t\t<attribute id="%s">' % k, file=f)
values = item[k]
if not isinstance(values, list):
values = [values]
for value in values:
print('\t\t\t<value><![CDATA[', end=' ', file=f)
if isinstance(value, unicode):
value = value.encode('utf-8', 'replace')
else:
value = unicode(value, errors='replace').encode('utf-8', 'replace')
f.write(value)
print(']]></value>', file=f)
print('\t\t</attribute>', file=f)
print('\t</Item>', file=f)
print('</Domain>', file=f)
f.flush()
f.seek(0)
return f
示例15: merge_in_pdf
# 需要导入模块: from tempfile import TemporaryFile [as 别名]
# 或者: from tempfile.TemporaryFile import seek [as 别名]
def merge_in_pdf(fa, fb):
for f in [fa, fb]:
if _is_img(f.name):
img = Image.open(f.file)
try:
r, g, b, a = img.split() #alpha
except Exception as e:
r, g, b = img.split()
img = Image.merge('RGB', (r, g, b))
temp_file = TemporaryFile()
img.save(temp_file, "PDF", resolution=100, transparency=0)
temp_file.seek(0)
f.file = temp_file
merger = PdfFileMerger()
for f in [fa, fb]:
merger.append(PdfFileReader(f.file))
temp_file = TemporaryFile()
merger.write(temp_file)
temp_file.seek(0)
pdf_file = File(temp_file)
pdf_file.name = 'id_card.pdf'
return pdf_file