API Documentation

couchbasekit.connection

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.connection.Connection[source]

This is the singleton pattern for handling couchbase connections application-wide.

Simply set your authentication credentials at the beginning of your application (such as in “settings.py”) by:

>>> from couchbasekit import Connection
>>> Connection.auth('theusername', 'p@ssword')

or

>>> Connection.auth(
...     username='theusername', password='p@ssword',
...     server='localhost', port='8091', # default already
... )

Note

This class is not intended to create instances, so don’t try to do:

>>> conn = Connection() # wrong

or you will get a RuntimeWarning.

classmethod auth(username, password, server='localhost', port='8091')[source]

Sets the couchbase connection credentials, globally.

Parameters:
  • username (str) – bucket username (or “Administrator” for working with multi buckets).
  • password (str) – bucket password (or Administrator’s password for working with multi buckets).
  • server (str) – couchbase server to connect, defaults to “localhost”.
  • port (str) – couchbase server port, defaults to “8091”.
Returns:

None

classmethod bucket(bucket_name)[source]

Gives the bucket from couchbase server.

Parameters:bucket_name (str) – Bucket name to fetch.
Returns:couchbase driver’s Bucket object.
Return type:couchbase.client.Bucket
Raises :RuntimeError If the credentials wasn’t set.
classmethod close()[source]

Closes the current connection, which would be useful to ensure that no orphan couchbase processes are left. Use it in, for example one of your Django middleware’s process_response().

Note

The class will open a new connection if a bucket is requested even though its connection was closed already.

Returns:None

couchbasekit.document

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.document.Document(key_or_map=None, get_lock=False, **kwargs)[source]

Couchbase document to be inherited by user-defined model documents that handles everything from validation to comparison with the help of couchbasekit.schema.SchemaDocument parent class.

Parameters:
  • key_or_map (basestring or dict) – Either the document id to be fetched or dictionary to initialize the first values of a new document.
  • get_lock (bool) – True, if the document wanted to be locked for other processes, defaults to False.
  • kwargs – key=value arguments to be passed to the dictionary.
Raises :

couchbasekit.errors.StructureError or couchbasekit.errors.DoesNotExist

exception DoesNotExist(doc)

Raised when a model class passed with an id to be fetched, but not found within couchbase.

You don’t have to specifically import this error to check if does not exist because your model document has just the same error for convenience. For example:

try:
    mrnobody = Author('someone_doesnt_exist')
except Author.DoesNotExist:
    # some useful code here
    pass
Document.bucket[source]

Returns the couchbase Bucket object for this instance, object property.

Returns:See: couchbase.client.Bucket.
Return type:couchbase.client.Bucket
Document.delete()[source]

Deletes the current document explicitly with CAS value.

Returns:Response from CouchbaseClient.
Return type:unicode
Raises :couchbasekit.errors.DoesNotExist or couchbase.exception.MemcachedError
Document.doc_id[source]

Returns the couchbase document’s id, object property.

Returns:The document id (that is created from doc_type and __key_field__ value, or auto-hashed document id at first saving).
Return type:unicode
Document.id[source]

Returns the document’s key field value (sort of primary key if you defined it in your model, which is optional), object property.

Returns:The document key if __key_field__ was defined, or None.
Return type:unicode or None
Document.save(expiration=0)[source]

Saves the current instance after validating it.

Parameters:expiration (int) – Expiration in seconds for the document to be removed by couchbase server, defaults to 0 - will never expire.
Returns:couchbase document CAS value
Return type:int
Raises :couchbasekit.errors.StructureError, See couchbasekit.schema.SchemaDocument.validate().
Document.touch(expiration)[source]

Updates the current document’s expiration value.

Parameters:expiration (int) – Expiration in seconds for the document to be removed by couchbase server, defaults to 0 - will never expire.
Returns:Response from CouchbaseClient.
Return type:unicode
Raises :couchbasekit.errors.DoesNotExist or couchbase.exception.MemcachedError
Document.view(view_name=None)[source]

Returns a couchbase view (or design document view with no view_name provided) if couchbasekit.viewsync.register_view() decorator was applied to model class.

Parameters:view_name (str) – If provided returns the asked couchbase view object or design document otherwise.
Returns:couchbase design document, couchbase view or None
Return type:couchbase.client.View or couchbase.client.DesignDoc or None

couchbasekit.schema

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.schema.SchemaDocument(seq=None, **kwargs)[source]

Schema document class that handles validations and restoring raw couchbase documents into Python values as defined in model documents.

Under normal circumstances, you don’t use or inherit this class at all, because it is only being used by couchbasekit.document.Document class.

Parameters:seq (dict) – Document data to store at initialization, defaults to None.
Raises :couchbasekit.errors.StructureError if the minimum structure requirements wasn’t satisfied.
exception StructureError(key=None, exp=None, given=None, msg='')

Raised when things go wrong about your model class structure or instance values. For example, you pass an int value to some field that should be str or some required field wasn’t provided etc..

SchemaDocument.load()[source]

Helper function to pre-load all the raw document values into Python ones, custom types and/or other document relations as they are defined in model document.

This is only useful when you need the instance to convert all its raw values into Python types, custom fields and/or other document relations before sending that object to somewhere else. For example, sending a User document to your framework’s login(request, user) function.

If your code is the only one accessing its values such as; user.posts, you don’t have to .load() it as they’re auto-converted and cached on-demand.

Returns the instance itself (a.k.a. chaining) so you can do:

>>> book = Book('hhg2g').load()
Returns:The Document instance itself on which was called from.
SchemaDocument.validate()[source]

Validates the document object with current values, always called within couchbasekit.document.Document.save() method.

Returns:Always True, or raises couchbasekit.errors.StructureError exception.
Raises :couchbasekit.errors.StructureError if any validation problem occurs.
couchbasekit.schema.ALLOWED_TYPES

This is the constant that will be used to check your model structure definitions:

ALLOWED_TYPES = (
    bool,
    int,
    long,
    float,
    unicode,
    basestring,
    list,
    dict,
    datetime.datetime,
    datetime.date,
    datetime.time,
)

However, it doesn’t include str type intentionally because couchbase will keep your values in unicode and you will have trouble re-saving a str field right after you fetch it. If you really have to pass a str value while you first creating a document record, you can simply define your field as basestring and both types will be accepted at the time of validation.

Besides these ones, you can also use couchbasekit.document.Document for document relations and couchbasekit.fields.CustomField subclasses for special field types. See couchbasekit.fields.

couchbasekit.fields

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.fields.ChoiceField(choice)[source]

The custom field to be used for multi choice options such as gender, static category list etc. This class can’t be used directly that has to be extended by your choice list class. Thankfully, it’s just easy:

class Gender(ChoiceField):
    CHOICES = {
        'M': 'Male',
        'F': 'Female',
    }

and all you have to do is to pass the current value to create your choice object:

>>> choice = Gender('F')
>>> choice.value
'F'
>>> choice.text
'Female'
Parameters:choice (basestring) – The choice value.
text[source]

Returns the text of the current choice, object property.

Return type:unicode
class couchbasekit.fields.CustomField[source]

The abstract custom field to be extended by all other field classes.

Note

You can also create your own custom field types by implementing this class. All you have to do is to assign your final (that is calculated and ready to be saved) value to the value property. Please note that it should also accept unicode raw values, which are fetched and returned from couchbase server. See PasswordField source code as an example.

Please contribute back if you create a generic and useful custom field.

value[source]

Property to be used when saving a custom field into couchbasekit.document.Document instance.

Returns:The value to be saved for the field within couchbasekit.document.Document instances.
Return type:mixed
class couchbasekit.fields.EmailField(email)[source]

The custom field to be used for email addresses and intended to validate them as well.

Parameters:email (basestring) – Email address to be saved.
static is_valid(email)[source]

Email address validation method.

Parameters:email (basestring) – Email address to be saved.
Returns:True if email address is correct, False otherwise.
Return type:bool
class couchbasekit.fields.PasswordField(password)[source]

The custom field to be used for password types.

It encrypts the raw passwords on-the-fly and depends on py-bcrypt library for such encryption.

Parameters:password (unicode) – Raw or encrypted password value.
Raises :ImportError if py-bcrypt was not found.
check_password(raw_password)[source]

Validates the given raw password against the intance’s encrypted one.

Parameters:raw_password (unicode) – Raw password to be checked against.
Returns:True if comparison was successful, False otherwise.
Return type:bool
Raises :ImportError if py-bcrypt was not found.
static get_bcrypt()[source]

Returns the py-bcrypt library for internal usage.

Returns:py-bcrypt package.
Raises :ImportError if py-bcrypt was not found.

couchbasekit.errors

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
exception couchbasekit.errors.CouchbasekitException[source]

Just to have some base exception class.

exception couchbasekit.errors.DoesNotExist(doc)[source]

Raised when a model class passed with an id to be fetched, but not found within couchbase.

You don’t have to specifically import this error to check if does not exist because your model document has just the same error for convenience. For example:

try:
    mrnobody = Author('someone_doesnt_exist')
except Author.DoesNotExist:
    # some useful code here
    pass
exception couchbasekit.errors.StructureError(key=None, exp=None, given=None, msg='')[source]

Raised when things go wrong about your model class structure or instance values. For example, you pass an int value to some field that should be str or some required field wasn’t provided etc..

couchbasekit.middlewares

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.middlewares.CouchbasekitMiddleware[source]

A helper that can be used in Django Middlewares to close couchbase connection gracefully in order not leave any orphan subprocess behind.

couchbasekit.viewsync

website:http://github.com/kirpit/couchbasekit
copyright:Copyright 2013, Roy Enjoy <kirpit at gmail.com>, see AUTHORS.txt.
license:MIT, see LICENSE.txt for details.
class couchbasekit.viewsync.ViewSync[source]

This is an experimental helper to download, upload and synchronize your couchbase views (both map and reduce JavaScript functions) in an organized way.

Unfortunately, it’s quite impossible to synchronize these views since couchbase doesn’t provide any information about when a specific view was created and modified. So we can’t know if previously downloaded .js file or the current one at couchbase server should be replaced..

This class also works in a singleton pattern so all its methods are @classmethod that you don’t need to create an instance at all.

In order to use this tool, you have to set VIEW_PATH attribute of the class to the directory wherever you want to keep downloaded JavaScript files. It is better to keep that directory under version controlled folder, as they can also become your view backups:

ViewSync.VIEW_PATH = '/path/to/your/js/view/backups'
classmethod download()[source]

Downloads all the views from server for the registered model documents into the defined VIEW_PATHS directory.

This method removes previous views directory if exist.

classmethod sync()[source]

Not implemented yet.

classmethod upload()[source]

Uploads all the local views from VIEW_PATHS directory to CouchBase server

This method over-writes all the server-side views with the same named ones coming from VIEW_PATHS folder.

couchbasekit.viewsync.register_view(design_doc, full_set=True)[source]

Model document decorator to register its design document view:

@register_view('dev_books')
class Book(Document):
    __bucket_name__ = 'mybucket'
    doc_type = 'book'
    structure = {
        # snip snip
    }
Parameters:
  • design_doc (basestring) – The name of the design document.
  • full_set (bool) – Attach full_set param to development views.

Project Versions

Table Of Contents

Previous topic

Model Document Structure

This Page