В дополнение к статье Apache Cassandra: работа с базами из Python и cassandra-driver — пример того, как можно сохранить файл в базу.
Создадим файл:
$ cat hello.c
#include <stdio.h>
main() {
printf("Hello Worldn");
}
Скомпилируем его:
$ gcc hello.c -o hello
Создадим таблицу с типом uuid для id, и blob для файлов:
cqlsh:testkeyspace> CREATE TABLE files_uuids (id uuid, file blob, PRIMARY KEY ((id)));
Далее — выполняем:
>>> from cassandra.cluster import Cluster
>>> cluster = Cluster()
>>> session = cluster.connect('testkeyspace')
>>> import os, uuid
>>> file = os.path.join(os.getcwd(), 'hello')
>>> fid = uuid.uuid4()
>>> 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 id from files_uuids; id -------------------------------------- 83dc3905-437c-4bd7-896f-d092827f01dd
И содержимое поля file:
cqlsh:testkeyspace> select file from files_uuids where id=83dc3905-437c-4bd7-896f-d092827f01dd; ... e35005f6564617461005f66696e69005f5f6c6962635f73746172745f6d61696e4040474c4942435f322e322e35005f5f646174615f7374617274005f5f676d6f6e5f73746172745f5f005f5f64736f5f68616e646c65005f494f5f737464696e5f75736564005f5f6c6962635f6373755f696e6974005f656e64005f7374617274005f5f6273735f7374617274006d61696e005f4a765f5265676973746572436c6173736573005f5f544d435f454e445f5f005f49544d5f7265676973746572544d436c6f6e655461626c65005f696e697400 (1 rows)
Запись в новый файл:
>>> fileout = os.path.join(os.getcwd(), 'helloout')
>>> with open(fileout, 'w') as fo:
... rows = session.execute("SELECT file FROM files_uuids WHERE id=83dc3905-437c-4bd7-896f-d092827f01dd")
... for i in rows:
... fo.write(''.join(i))
...
>>>
Проверяем:
$ ./helloout Hello World
$ file helloout helloout: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=0x320c1bcd829c0a6407a0331f5243f03110656ee8, not stripped
Готово.




