Search code examples
pythonpython-2.7couchdbcouchdb-python

couchdb-python specify own _id failed


How is it possible to define own _id in couchdb-python (0.9), because when I tried '_id': i[5] I got the following error message?

$ python test3.py
828288
Traceback (most recent call last):
  File "test3.py", line 42, in <module>
    db.save(doc)
  File "/home/mictadlo/.virtualenvs/unisnp/lib/python2.7/site-packages/couchdb/client.py", line 415, in save
    func = _doc_resource(self.resource, doc['_id']).put_json
  File "/home/mictadlo/.virtualenvs/unisnp/lib/python2.7/site-packages/couchdb/client.py", line 954, in _doc_resource
    if doc_id[:1] == '_':
TypeError: 'int' object has no attribute '__getitem__'

Below is the script which is causing the above error:

from couchdb.mapping import Document, TextField, IntegerField, Mapping
from couchdb.mapping import DictField, ViewField, BooleanField, ListField
from couchdb import Server

# $ sudo systemctl start couchdb
# http://localhost:5984/_utils/

server = Server()
db = server.create("test")

r = [["Test", "A", "B01", 828288,  1,    7, 'C', 5],
    ["Test", "A", "B01", 828288,  1,    7, 'T', 6],
    ["Test", "A", "B01", 171878,  3,    8, 'C', 5],
    ["Test", "A", "B01", 171878,  3,    8, 'T', 6],
    ["Test", "A", "B01", 871963,  3,    9, 'A', 5],
    ["Test", "A", "B01", 871963,  3,    9, 'G', 6],
    ["Test", "A", "B01", 1932523, 1,   10, 'T', 4],
    ["Test", "A", "B01", 1932523, 1,   10, 'A', 5],
    ["Test", "A", "B01", 1932523, 1,   10, 'X', 6],
    ["Test", "A", "B01", 667214,  1,   14, 'T', 4],
    ["Test", "A", "B01", 667214,  1,   14, 'G', 5],
    ["Test", "A", "B01", 667214,  1,   14, 'G', 6]]


for i in r:
    print i[3]

    doc = {
        'type': i[0],
        'name': i[1],
        'sub_name': i[2],
        'pos': i[3],
        's_type': i[4],
        '_id': i[5],
        'chr':[]
    }
    doc['chr'].append({
        "letter":i[6],
        "no":i[7]
    })

    db.save(doc)

Solution

  • It expects _id to be a string and you are passing a type of int. The error is caused by this line:

    if doc_id[:1] == '_':
    

    Because script is trying to slice an int object.

    So change it to string type:

    ...
    ...
    '_id': str(i[5]),
    ...