0

I have been learning Python and working some CouchDb tutorials. The most current way to get a couchdb hosted DbaaS looks like Cloudant, since others have shut down.

I got progress developing locally using couchdbkit, which has a very nice DAO mapper in the schema package, and also the standard couchdb-python library has a "mapping" module that works a lot like that.

I can't find this feature in the cloudant library - examples are manipulating JSON directly - have they left it out, or is there an approved ODM library to use?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
charles ross
  • 570
  • 4
  • 15

1 Answers1

2

It sounds like what you're really asking is "how do I convert a json document to my own Python class". The role of a client library (for Cloudant) is to abstract away the boiler plate HTTP and json encoding stuff, and leave you with nice method calls and a native (in Python a dict) representation of a json document. In Python especially, given its superb requests library and slick json handling, most people probably wouldn't bother using a specific client library, even.

Converting a dict to a class of your own making shouldn't be hard, or requiring a library. Python 3.7:

from dataclasses import dataclass

@dataclass
class Employee:
    name: str
    department: str
    code: int

and

import requests
from employee import Employee

doc = requests.get("https://acc.cloudant.com/employees/bobthebuilder").json()
employee = Employee(
    name=doc.get("name", "n/a")
    department=doc.get("department", "n/a")
    code=doc.get("code", "n/a")
)
xpqz
  • 3,617
  • 10
  • 16
  • OK, so TIL about DataClasses! I have been running Python 2.7 sadly since many of the couchDb tutes use that. And it seems that the answer is "It was left out on purpose" because of the great new Python features. – charles ross Aug 03 '18 at 23:30
  • Well.. you can do pretty much the same in py2.7 with a named tuple. It’s left out of the library because doc-object mapping is application dependent, and that a dict is a pretty good representation of a Cloudant document. – xpqz Aug 04 '18 at 21:00