Example #1
0
 def escape_docid(self, docid):
     if docid.startswith('/'):
         docid = docid[1:]
     if docid.startswith('_design'):
         docid = '_design/%s' % url_quote(docid[8:], safe='')
     else:
         docid = url_quote(docid, safe='')
     return docid  
Example #2
0
    def create_db(self, dbname):
        """ Create a database on CouchDb host

        @param dname: str, name of db

        @return: Database instance if it's ok or dict message
        """
        _dbname = url_quote(validate_dbname(dbname), safe=":")
        res = self.res.put('/%s/' % _dbname)
        if res['ok']:
            return Database(self, dbname)
        return res['ok']
Example #3
0
    def delete_attachment(self, doc, name):
        """ delete attachement to the document

        @param doc: dict, document object in python
        @param name: name of attachement
    
        @return: dict, with member ok set to True if delete was ok.
        """
        docid = self.escape_docid(doc['_id'])
        name = url_quote(name, safe="")
        
        return self.res(docid).delete(name, rev=doc['_rev'])
Example #4
0
    def __init__(self, server, dbname):
        """Constructor for Database

        @param server: Server instance
        @param dbname: str, name of database
        """

        if not hasattr(server, 'next_uuid'):
            raise TypeError('%s is not a couchdbkit.server instance' % 
                            server.__class__.__name__)
                            
        self.dbname = validate_dbname(dbname)
        self.server = server
        self.res = server.res.clone()
        if "/" in dbname:
            self.res.client.safe = ":/%"
        self.res.update_uri('/%s' % url_quote(dbname, safe=":"))
Example #5
0
    def fetch_attachment(self, id_or_doc, name):
        """ get attachment in a document
        
        @param id_or_doc: str or dict, doc id or document dict
        @param name: name of attachment default: default result

        @return: str, attachment
        """

        if isinstance(id_or_doc, basestring):
            docid = id_or_doc
        else:
            docid = id_or_doc['_id']
      
        docid = self.escape_docid(docid)
        name = url_quote(name, safe="")
        try:
            data = self.res(docid).get(name)
        except ResourceNotFound:
            return None
        return data
Example #6
0
    def put_attachment(self, doc, content, name=None, 
            content_type=None, content_length=None, chunked=True):
        """ Add attachement to a document.

        @param doc: dict, document object
        @param content: string or :obj:`File` object.
        @param name: name or attachment (file name).
        @param content_type: string, mimetype of attachment.
        If you don't set it, it will be autodetected.
        @param content_lenght: int, size of attachment.

        @return: bool, True if everything was ok.


        Example:
            
            >>> from simplecouchdb import server
            >>> server = server()
            >>> db = server.create_db('couchdbkit_test')
            >>> doc = { 'string': 'test', 'number': 4 }
            >>> db.save(doc)
            >>> text_attachment = u'un texte attaché'
            >>> db.put_attachment(doc, text_attachment, "test", "text/plain")
            True
            >>> file = db.fetch_attachment(doc, 'test')
            >>> result = db.delete_attachment(doc, 'test')
            >>> result['ok']
            True
            >>> db.fetch_attachment(doc, 'test')
            >>> del server['couchdbkit_test']
            {u'ok': True}
        """

        headers = {}
        
        content = content or ''
        if content and chunked:
            headers.setdefault("Transfer-Encoding", "chunked")

        if name is None:
            if hasattr(content, "name"):
                name = content.name
            else:
                raise InvalidAttachment('You should provid a valid attachment name')

        if content_type is None:
            content_type = ';'.join(filter(None, guess_type(name)))

        if content_type:
            headers['Content-Type'] = content_type

        if content_length and content_length is not None:
            headers['Content-Length'] = content_length

        if hasattr(doc, 'to_json'):
            doc_ = doc.to_json()
        else:
            doc_ = doc

        docid = self.escape_docid(doc_['_id'])
        name = url_quote(name, safe="")
            
        res = self.res(docid).put(name, payload=content, 
                headers=headers, rev=doc_['_rev'])

        if res['ok']:
            doc_.update({ '_rev': res['rev']})
        return res['ok']
Example #7
0
 def __delitem__(self, dbname):
     return self.res.delete('/%s/' % url_quote(dbname, safe=":"))