问题描述
我知道,如果我想这一个或如果有人给我看,这将是一个额头搭接。张贴任何问题之前,我尝试了至少三个小时,相当多的寻找。有一些迹象表明接近,但没有我所采用/尝试似乎工作。
I know that if I figure this one out or if somebody shows me, it'll be a forehead slapper. Before posting any questions, I try for at least three hours and quite a bit of searching. There are several hints that are close, but nothing I have adopted/tried seems to work.
我正在从Java一个byte [],并通过它通过JSON(与GSON)为Python使用JSON瓶。该字节[]存储在一个Python对象为一个整数列表接收时,但现在我需要将它发送给MySQLdb的,并存储为一个blob。的数据内容是二进制文件数据。
I am taking a byte[] from Java and passing that via JSON (with Gson) to a python JSON using Flask. This byte[] is stored in a python object as an integer list when received, but now I need to send it to MySQLdb and store it as a blob. The data contents is binary file data.
我要如何转换成一个Python整数列表[1,2,-3,-143 ....]的东西,我可以在MySQL的存储?我已经试过的bytearray()和array.array(),但那些时候我直接从对象访问列表中,并尝试转换为字符串存储thorugh MySQLdb的窒息。
How do I convert a python integer list [1,2,-3,-143....] to something that I can store in MySQL? I have tried bytearray() and array.array(), but those choke when I access the list directly from the object and try and convert to a string to store thorugh MySQLdb.
任何链接或提示是大大AP preciated。
Any links or hints are greatly appreciated.
推荐答案
您可以加入它变成一个字节串(刚下蟒蛇2.x的字符串)。最简单的,如果不是最有效的,方法是只国防部数据,然后转换成字符和加入。是这样的:
You can join it into a bytestring (just a string under python 2.x). The simplest, if not most efficient, way would be to just mod the data, then convert to chars and join. Something like:
data = [1,2,-3,-143, ...]
binData = ''.join(map(lambda x: chr(x % 256), data))
binData = ''.join(map(lambda x: chr(x % 256), attach.attcoll))
sql_stmt = """INSERT INTO attachments (attno,filename,fileextension,projNo,procNo,wpattachment) \
VALUES ('%s','%s','%s','%s','%s','%s') ON DUPLICATE KEY UPDATE filename='%s',fileextension='%s'""" % (attach.attno,\
attach.filename,attach.fileextension,attach.projNo,attach.procNo,binData,attach.filename,attach.fileextension)
try:
cursor.execute(sql_stmt)
conn.commit()
cursor.close()
conn.close()
return 'SUCCESS'
except MySQLdb.Error:
cursor.close()
conn.close()
print "My SQL cursor execute error."
return 'FAILURE'
这篇关于将Java字节数组到Python字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!