des-6ren">
gpt4 book ai didi

Python Cassandra - 保存文件给出 "Invalid STRING constant"

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:42 24 4
gpt4 key购买 nike

我是 Cassandra 的新手,我想使用 python-cassandra 驱动程序将一些小文件保存到数据库中,但出现“无效的字符串常量”错误。

表:

cqlsh:testkeyspace> desc table files_uuids;

CREATE TABLE files_uuids (
id uuid,
file blob,
PRIMARY KEY ((id))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};

和 Python 代码:

>>> from cassandra.cluster import Cluster
>>> cluster = Cluster()
>>> session = cluster.connect('testkeyspace')
>>> import os, uuid
>>> file = os.path.join(os.getcwd(), 'file.txt')
>>> fid = uuid.uuid4()
>>> with open(file, 'rb') as f:
... data = f.read()
... session.execute("INSERT INTO files_uuids (id, file) values (%s, %s)", (fid, data))
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 1405, in execute
result = future.result(timeout)
File "/usr/local/lib/python2.7/dist-packages/cassandra/cluster.py", line 2976, in result
raise self._final_exception
cassandra.InvalidRequest: code=2200 [Invalid query] message="Invalid STRING constant (text
) for file of type blob"

我做错了什么?

Python 2.7、Cassandra 2.0。

最佳答案

知道了... data = f.read()str() (message="无效的字符串常量 [...]).

所以这会起作用:

>>> with open(file, 'rb') as f:
... data = f.read()
... res = bytearray(data)
... session.execute("INSERT INTO files_uuids (id, file) values (%s, %s)", (fid, res))

结果:

cqlsh:testkeyspace> select * from files_uuids;

id | file
--------------------------------------+--------------
6a918341-c3d9-48a1-96fe-9a4b2bc6ea51 | 0x746578740a

关于Python Cassandra - 保存文件给出 "Invalid STRING constant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com