我有一个base64编码的图像文件的字符串.我需要使用Paper Clip保存它
我的控制器代码是
@driver = User.find(6)
encoded_file = Base64.encode64(File.open('/pjt_path/public/test.jpg').read)
decoded_file = Base64.decode64(encoded_file)
@driver.profile_pic = StringIO.open(decoded_file)
@driver.save
Run Code Online (Sandbox Code Playgroud)
在我的用户模型中
has_attached_file :profile_pic, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => '/icon.jpg'
Run Code Online (Sandbox Code Playgroud)
目前,该文件保存为文本文件(stringio.txt).但是当我将扩展名更改为JPG时,我可以将其视为图像.如何使用StringIO正确命名图像.
我有rails 3.2,ruby 1.9.2,paperclip 3.0.3
我正在使用subprocess包从 python 脚本调用一些外部控制台命令,我需要将文件处理程序传递给它以分别返回stdout和stderr。代码大致如下:
import subprocess
stdout_file = file(os.path.join(local_path, 'stdout.txt'), 'w+')
stderr_file = file(os.path.join(local_path, 'stderr.txt'), 'w+')
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
Run Code Online (Sandbox Code Playgroud)
这工作正常,并且正在创建具有相关输出的 txt 文件。然而,在忽略文件创建的内存中处理这些输出会更好。所以我使用 StringIO 包来处理它:
import subprocess
import StringIO
stdout_file = StringIO.StringIO()
stderr_file = StringIO.StringIO()
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
Run Code Online (Sandbox Code Playgroud)
但这不起作用。失败:
File "./test.py", line 17, in <module>
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1063, …Run Code Online (Sandbox Code Playgroud) 我想知道是否有人知道从StringIO对象生成python中的SQLite数据库连接的方法.
我有一个压缩的SQLite3数据库文件,我想使用该gzip库解压缩它,然后连接到它而不先生成临时文件.
我查看了slqite3库源代码,但它看起来像是filename一直传递到C代码中.是否有任何其他SQLite3连接库可以使用文件ID?或者是否有一些为什么我可以欺骗内置sqlite3库认为我的StringIO(或其他一些对象类型)是一个实际的文件?
我正在编写一个程序,可以接收各种常见图像格式的图像,但需要以一致的格式检查它们.什么图像格式并不重要,主要是因为它们都是相同的.由于我需要转换图像格式然后继续使用图像,我不想将其保存到磁盘; 只需将其转换并继续.这是我使用StringIO的尝试:
image = Image.open(cStringIO.StringIO(raw_image)).convert("RGB")
cimage = cStringIO.StringIO() # create a StringIO buffer to receive the converted image
image.save(cimage, format="BMP") # reformat the image into the cimage buffer
cimage = Image.open(cimage)
Run Code Online (Sandbox Code Playgroud)
它返回以下错误:
Traceback (most recent call last):
File "server.py", line 77, in <module>
s.listen_forever()
File "server.py", line 47, in listen_forever
asdf = self.matcher.get_asdf(data)
File "/Users/jedestep/dev/hitch-py/hitchhiker/matcher.py", line 26, in get_asdf
cimage = Image.open(cimage)
File "/Library/Python/2.7/site-packages/PIL/Image.py", line 2256, in open
% (filename if filename else fp))
IOError: cannot identify image file <cStringIO.StringO …Run Code Online (Sandbox Code Playgroud) 我正在尝试从StringIO(或更具体地说是cStringIO)获取数据并将其转换为django.core.files.images.ImageFile.
但它不起作用.不管怎样,我的意思是它在很多方面都失败了,谷歌让我失望了.
到目前为止我有:
pi = ProductImage(product=product)
image = ImageFile(image_file)
image.name = image_name # defined elsewhere
pi.source_image.save(image_name, image)
pi.save()
Run Code Online (Sandbox Code Playgroud)
我的堆栈跟踪如下:
File "dev.py", line 359, in process_csv_item
pi.source_image.save(image_name, image)
File "C:\Python26\lib\site-packages\django\db\models\fields\files.py", line 92, in save
self.name = self.storage.save(name, content)
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 48, in save
name = self._save(name, content)
File "C:\Python26\lib\site-packages\django\core\files\storage.py", line 168, in _save
for chunk in content.chunks():
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 65, in chunks
counter = self.size
File "C:\Python26\lib\site-packages\django\core\files\base.py", line 39, in _get_size
elif os.path.exists(self.file.name):
AttributeError: 'cStringIO.StringI' object has no attribute …Run Code Online (Sandbox Code Playgroud) 假设我有一些StringIO(来自cStringIO).我想从中读取缓冲区,直到遇到某个字符/字节,比如'Z',所以:
stringio = StringIO('ABCZ123')
buf = read_until(stringio, 'Z') # buf is now 'ABCZ'
# strinio.tell() is now 4, pointing after 'Z'
Run Code Online (Sandbox Code Playgroud)
在Python中执行此操作的最快方法是什么?谢谢
有几个类似的问题,但没有一个直接回答这个简单的问题:
如何捕获命令输出并将该内容流式传输到numpy数组而不创建要读取的临时字符串对象?
那么,我想做的是:
import subprocess
import numpy
import StringIO
def parse_header(fileobject):
# this function moves the filepointer and returns a dictionary
d = do_some_parsing(fileobject)
return d
sio = StringIO.StringIO(subprocess.check_output(cmd))
d = parse_header(sio)
# now the file pointer is at the start of data, parse_header takes care of that.
# ALL of the data is now available in the next line of sio
dt = numpy.dtype([(key, 'f8') for key in d.keys()])
# i don't know how do make this …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Django创建和提供excel文件.我有一个jar文件,它获取参数并根据参数生成一个excel文件,它没有问题.但是,当我试图获取生成的文件并将其提供给用户下载时,文件就会破碎.它的大小为0kb.这是我用于excel生成和服务的代码片段.
def generateExcel(request,id):
if os.path.exists('./%s_Report.xlsx' % id):
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
args = ['ServerExcel.jar', id]
result = jarWrapper(*args) # this creates the excel file with no problem
if result:
excel = open("%s_Report.xlsx" % id, "r")
output = StringIO.StringIO(excel.read())
out_content = output.getvalue()
output.close()
response = HttpResponse(out_content,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s_Report.xlsx' % id
return response
else:
return HttpResponse(json.dumps({"no":"excel","no one": "cries"}))
Run Code Online (Sandbox Code Playgroud)
我搜索了可能的解决方案并尝试使用File …
我有一个存储在变量中的大型 xml 文件。我想使用 pysftp 将它直接写入 ftp。我相信我需要使用 pysftp.putfo 并且这需要一个类似对象的文件。这是一个最小的例子:
from io import StringIO
from pysftp import Connection, CnOpts
cnopts = CnOpts()
cnopts.hostkeys = None
with Connection('localhost'
,username= 'admin'
,password = 'test'
,cnopts=cnopts
) as sftp:
sftp.putfo(StringIO('xml string'))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TypeError: Expected unicode or bytes, got None
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?是否有更简单更好的方法来实现我将字符串变量写入 ftp 上的文件的目标?
首先,我了解如何在 Python3 中从字符串编写 UTF-8,并且StringIO推荐用于此类字符串构建。但是,我特别需要一个类似二进制文件的对象,为此我需要BytesIO. 如果我执行以下操作,那么数据最终会崩溃,因为它被读取为Latin1,我的计算机的默认区域设置/字符集。
with io.StringIO() as sb:
csv.writer(sb).writerows(rows)
sb.flush()
sb.seek(0)
# blows up with Latin1 encoding error
job = bq.load_table_from_file(sb, table_ref, job_config=job_config)
Run Code Online (Sandbox Code Playgroud)
所以我的解决方法是这个怪物,使内存使用量加倍:
with io.StringIO() as sb:
csv.writer(sb).writerows(rows)
sb.flush()
sb.seek(0)
with io.BytesIO(sb.getvalue().encode('utf-8')) as buffer:
job = bq.load_table_from_file(buffer, table_ref, job_config=job_config)
Run Code Online (Sandbox Code Playgroud)
在此链中的某个位置必须有一种方法来指定字节编码,以便类似文件的读者sb将看到 UTF-8 格式的数据。或者有没有办法使用csv.writer()字节流?
我在 StackOverflow 上寻找了这两个答案,但我发现的通常是写入文件和内存中所有内容都指向的内容StringIO。
stringio ×10
python ×8
django ×2
console ×1
excel ×1
file ×1
file-upload ×1
numpy ×1
optimization ×1
paperclip ×1
performance ×1
pysftp ×1
python-2.x ×1
python-3.x ×1
ruby ×1
sqlite ×1
stdin ×1
stream ×1
xlsx ×1