pythoncouchdbdaocloudantodm

How to do object mapping using python-cloudant


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?


Solution

  • 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")
    )