Using CouchDB Kit and Python; Trying to setup database without having to set DB inline

524 Views Asked by At

I am using couchdbkit to build a small Flask app and I am trying to write out some Python models so that interacting with the DB is easier (not inline).

Here is my code so far:

base.py

from couchdbkit import *
from api.config import settings


class WorkflowsCloudant(Server):

    def __init__(self):
        uri = "https://{public_key}:{private_key}@{db_uri}".format(
            public_key=settings.COUCH_PUBLIC_KEY,
            private_key=settings.COUCH_PRIVATE_KEY,
            db_uri=settings.COUCH_DB_BASE_URL
        )
        super(self.__class__, self).__init__(uri)


class Base(Document):

    def __init__(self):
        server = WorkflowsCloudant.get_db(settings.COUCH_DB_NAME)
        self.set_db(server)
        super(self.__class__, self).__init__()

workflows.py

from couchdbkit import *
from api.models.base import Base


class Workflow(Base):
    workflow = DictProperty()
    account_id = IntegerProperty()
    created_at = DateTimeProperty()
    updated_at = DateTimeProperty()
    deleted_at = DateTimeProperty()
    status = StringProperty()

Controller init.py

from api.models import Workflow

blueprint = Blueprint('workflows', __name__, url_prefix='/<int:account_id>/workflows')

@blueprint.route('/<workflow_id>')
def get_single_workflow(account_id, workflow_id):
    doc = Workflow.get(workflow_id)

    if doc['account_id'] != account_id:
        return error_helpers.forbidden('Invalid account')

    return Response(json.dumps(doc), mimetype='application/json')

The error I keep getting is: TypeError: doc database required to save document

I was trying to following the setup here (http://couchdbkit.org/docs/gettingstarted.html) but extrapolating their inline instructions to more of a dynamic context. Also, I am a Python newb, so my apologies for my ignorance

1

There are 1 best solutions below

0
On

This error happens if your model (Document) is not linked to the database (correctly). This is done by with set_db method.

Also I think you should change your model:

from couchdbkit import Document
from couchdbkit import StringProperty, IntegerProperty
from couchdbkit import DateTimeProperty,  DictProperty

class Workflow(Document):
    workflow = DictProperty()
    account_id = IntegerProperty()
    created_at = DateTimeProperty()
    updated_at = DateTimeProperty()
    deleted_at = DateTimeProperty()
    status = StringProperty()

I changed the Base inheritance to Document class. Also avoid using from some_module import *!

When you have your model set like this then you can link your model and couchdb like this:

Workflow.set_db(server)

NOTE: the code is not tested. I wrote it from my head so there could be some mistakes.