Commits

mengzhuo committed bf9b0e0

PEP8

Comments (0)

Files changed (2)

 
 
 __all__ = ["BlockingCouch", "AsyncCouch", "CouchException", "NotModified",
-        "BadRequest", "NotFound", "MethodNotAllowed", "Conflict",
-        "PreconditionFailed", "InternalServerError"]
+           "BadRequest", "NotFound", "MethodNotAllowed", "Conflict",
+           "PreconditionFailed", "InternalServerError"]
 
 __version__ = '0.2.1'
 
 
 JSON_MIME_TYPE = 'application/json'
 
+
 class AsyncCouch(object):
+
     """Basic wrapper class for asynchronous operations on a CouchDB
 
     Example usage::
                            'more docs')
         # make list of docs to mark as deleted
         deleted = [{'_id': doc['_id'], '_rev': doc['_rev'],
-                '_deleted': True} for doc in docs]
+                    '_deleted': True} for doc in docs]
         # use bulk docs API to update the docs
         url = '/{0}/_bulk_docs'.format(self.db_name)
         body = json_encode({'all_or_nothing': all_or_nothing,
             raise KeyError('Missing id or revision information in doc')
         else:
             url = '/{0}/{1}/{2}?rev={3}'.format(self.db_name,
-                    url_escape(doc['_id']), url_escape(attachment_name),
-                    doc['_rev'])
+                                                url_escape(doc['_id']), url_escape(
+                                                    attachment_name),
+                                                doc['_rev'])
         r = yield self._http_delete(url)
         raise gen.Return(r)
 
           inclusive_end=false
         """
         url = '/{0}/_design/{1}/_view/{2}'.format(self.db_name,
-                design_doc_name, view_name)
+                                                  design_doc_name, view_name)
         r = yield self._view(url, **kwargs)
         raise gen.Return(r)
 
             for item in obj:
                 if 'error' in item:
                     raise relax_exception(httpclient.HTTPError(
-                            resp.code if item['error'] != 'not_found' else 404,
-                            item['reason'], resp))
+                        resp.code if item['error'] != 'not_found' else 404,
+                        item['reason'], resp))
 
         elif 'error' in obj:
             raise relax_exception(httpclient.HTTPError(resp.code,
-                    obj['reason'], resp))
+                                                       obj['reason'], resp))
 
         elif 'rows' in obj:
             # check if there is an error in the result rows,
             for row in obj['rows']:
                 if 'error' in row:
                     raise relax_exception(httpclient.HTTPError(
-                            resp.code if row['error'] != 'not_found' else 404,
-                            row['error'], resp))
+                        resp.code if row['error'] != 'not_found' else 404,
+                        row['error'], resp))
         return obj
-    
+
     def _parse_headers(self, resp):
-        headers = {"code":resp.code}
+        headers = {"code": resp.code}
         headers.update(resp.headers)
         return headers
 
                 raise relax_exception(e)
             resp = e.response
         raise gen.Return(self._parse_response(resp) if decode else resp.body)
-        
+
     @gen.coroutine
     def _http_post(self, uri, body, **kwargs):
         if self._closed:
         req_args = copy.deepcopy(self.request_args)
         req_args.update(kwargs)
         req_args.setdefault('headers', {}).update({
-                'Accept': 'application/json',
-                'Content-Type': 'application/json'})
+            'Accept': 'application/json',
+            'Content-Type': 'application/json'})
         req = httpclient.HTTPRequest(self.couch_url + uri, method='POST',
                                      body=body, **req_args)
         try:
             raise CouchException('Database connection is closed.')
         req_args = copy.deepcopy(self.request_args)
         req_args.setdefault('headers', {}).update({
-                'Accept': 'application/json'})
+            'Accept': 'application/json'})
         req = httpclient.HTTPRequest(self.couch_url + uri, method='DELETE',
                                      **req_args)
         try:
         if self._closed:
             raise CouchException('Database connection is closed.')
         req_args = copy.deepcopy(self.request_args)
-        req = httpclient.HTTPRequest(urljoin(self.couch_url,uri), method='HEAD',
-                                     **req_args)
+        req = httpclient.HTTPRequest(
+            urljoin(self.couch_url, uri), method='HEAD',
+            **req_args)
         try:
             resp = yield self._client.fetch(req)
         except httpclient.HTTPError as e:
             resp = e.response
         raise gen.Return(self._parse_headers(resp))
 
+
 class BlockingCouch(AsyncCouch):
+
     """Basic wrapper class for blocking operations on a CouchDB.
 
     Example usage::
 
 
 class CouchException(httpclient.HTTPError):
+
     """Base class for Couch specific exceptions"""
+
     def __init__(self, HTTPError, msg=None):
         httpclient.HTTPError.__init__(self, HTTPError.code,
-                msg, HTTPError.response)
+                                      msg, HTTPError.response)
 
 
 class NotModified(CouchException):
+
     """HTTP Error 304 (Not Modified)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError,
-                'The document has not been modified since the last update.')
+                                'The document has not been modified since the last update.')
 
 
 class BadRequest(CouchException):
+
     """HTTP Error 400 (Bad Request)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError, 'The syntax of the request '
-                'was invalid or could not be processed.')
+                                'was invalid or could not be processed.')
 
 
 class NotFound(CouchException):
+
     """HTTP Error 404 (Not Found)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError,
-                'The requested resource was not found.')
+                                'The requested resource was not found.')
 
 
 class MethodNotAllowed(CouchException):
+
     """HTTP Error 405 (Method Not Allowed)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError, 'The request was made using '
-                'an incorrect request method; for example, a GET was used '
-                'where a POST was required.')
+                                'an incorrect request method; for example, a GET was used '
+                                'where a POST was required.')
 
 
 class Conflict(CouchException):
+
     """HTTP Error 409 (Conflict)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError, 'The request failed because '
-                'of a database conflict.')
+                                'of a database conflict.')
 
 
 class PreconditionFailed(CouchException):
+
     """HTTP Error 412 (Precondition Failed)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError, 'Could not create database - '
-                'a database with that name already exists.')
+                                'a database with that name already exists.')
 
 
 class InternalServerError(CouchException):
+
     """HTTP Error 500 (Internal Server Error)"""
+
     def __init__(self, HTTPError):
         CouchException.__init__(self, HTTPError, 'The request was invalid and '
-                'failed, or an error occurred within the CouchDB server that '
-                'prevented it from processing the request.')
+                                'failed, or an error occurred within the CouchDB server that '
+                                'prevented it from processing the request.')
 
 
 def relax_exception(e):
     # info_db
     resp = db.info_db()
     assert ('db_name' in resp) and (resp['db_name'] == db.db_name), \
-           'No database info'
+        'No database info'
 
     # uuids
     resp = db.uuids()
     # save doc
     resp = db.save_doc(doc1)
     assert ('rev' in resp) and ('id' in resp), 'Failed to save doc'
-    doc1.update({'_id':resp['id'], '_rev':resp['rev']})
+    doc1.update({'_id': resp['id'], '_rev': resp['rev']})
 
     # save doc with wrong rev number
     try:
     # has doc on non-existing doc
     resp = db.has_doc('a')
     assert not resp, "Failed on getting head of non-existing doc"
-    
+
     # get doc
     resp = db.get_doc(doc1['_id'])
     assert doc1 == resp, 'Failed to get doc'
     doc1['msg2'] = 'Another message'
     resp = db.save_docs([doc1, doc2])
     assert all('rev' in item and 'id' in item for item in resp), \
-           'Failed to save docs'
+        'Failed to save docs'
     doc1['_rev'] = resp[0]['rev']
     doc2.update({'_id': resp[1]['id'], '_rev': resp[1]['rev']})
 
 
     # list docs
     resp = db.view_all_docs(include_docs=True)
-    assert {doc1['_id']:doc1['_rev'], doc2['_id']:doc2['_rev']} == \
-           dict((row['doc']['_id'], row['doc']['_rev'])
-                for row in resp['rows']), 'Failed listing all docs'
+    assert {doc1['_id']: doc1['_rev'], doc2['_id']: doc2['_rev']} == \
+        dict((row['doc']['_id'], row['doc']['_rev'])
+             for row in resp['rows']), 'Failed listing all docs'
 
     # pull database
     resp = db2.pull_db(dbname1, create_target=True)
     assert 'ok' in resp, 'Replication failed'
     assert dbname2 in db2.list_dbs(), \
-           'Replication failed, new database replication not found'
+        'Replication failed, new database replication not found'
 
     # delete docs
     resp = db2.delete_docs([doc1, doc2])
-    assert resp[0]['id']==doc1['_id'] and resp[1]['id']==doc2['_id'], \
-           'Failed to delete docs'
-    assert len(db2.view_all_docs()['rows'])==0, \
-           'Failed to delete docs, database not empty'
+    assert resp[0]['id'] == doc1['_id'] and resp[1]['id'] == doc2['_id'], \
+        'Failed to delete docs'
+    assert len(db2.view_all_docs()['rows']) == 0, \
+        'Failed to delete docs, database not empty'
 
     # delete database
     resp = db2.delete_db()
     # view
     resp = db.view('test', 'msg')
     assert [doc1['_id'], doc2['_id']] == [row['key'] for row in resp['rows']], \
-           'Failed to get view results from design doc'
+        'Failed to get view results from design doc'
 
     # delete doc
     resp = db.delete_doc(doc2)
     # save attachment
     data = {'msg3': 'This is a test'}
     attachment = {'mimetype': 'application/json', 'name': 'test attachment',
-                 'data': json.dumps(data)}
+                  'data': json.dumps(data)}
     resp = db.save_attachment(doc1, attachment)
     assert 'ok' in resp, 'Attachment not saved'
     doc1['_rev'] = resp['rev']
     # info_db
     resp = yield db.info_db()
     assert ('db_name' in resp) and (resp['db_name'] == db.db_name), \
-           'No database info'
+        'No database info'
 
     # uuids
     resp = yield db.uuids()
     # save doc
     resp = yield db.save_doc(doc1)
     assert ('rev' in resp) and ('id' in resp), 'Failed to save doc'
-    doc1.update({'_id':resp['id'], '_rev':resp['rev']})
+    doc1.update({'_id': resp['id'], '_rev': resp['rev']})
 
     # save doc with wrong rev number
     try:
 
     # has doc
     resp = yield db.has_doc(doc1['_id'])
-    assert resp, "Failed to get doc HEAD"    
-        
+    assert resp, "Failed to get doc HEAD"
+
     # has doc on non-existing doc
     resp = yield db.has_doc('a')
     assert not resp, "Has a non-existing doc"
-    
+
     # save docs
     doc1['msg2'] = 'Another message'
     resp = yield db.save_docs([doc1, doc2])
     assert all('rev' in item and 'id' in item for item in resp), \
-           'Failed to save docs'
+        'Failed to save docs'
     doc1['_rev'] = resp[0]['rev']
     doc2.update({'_id': resp[1]['id'], '_rev': resp[1]['rev']})
 
     # list docs
     resp = yield db.view_all_docs(include_docs=True)
     assert {doc1['_id']: doc1['_rev'], doc2['_id']: doc2['_rev']} == \
-            dict((row['doc']['_id'], row['doc']['_rev'])
-                 for row in resp['rows']), 'Failed listing all docs'
+        dict((row['doc']['_id'], row['doc']['_rev'])
+             for row in resp['rows']), 'Failed listing all docs'
 
     # pull database
     resp = yield db2.pull_db(dbname1, create_target=True)
     # verify that replicated db is in the list of dbs
     resp = yield db2.list_dbs()
     assert dbname2 in resp, \
-           'Replication failed, new database replication not found'
+        'Replication failed, new database replication not found'
 
     # delete docs
     resp = yield db2.delete_docs([doc1, doc2])
-    assert resp[0]['id']==doc1['_id'] and \
-           resp[1]['id']==doc2['_id'], 'Failed to delete docs'
+    assert resp[0]['id'] == doc1['_id'] and \
+        resp[1]['id'] == doc2['_id'], 'Failed to delete docs'
 
     # check that deleted docs are not in the list all docs
     resp = yield db2.view_all_docs()
-    assert len(resp['rows'])==0, 'Failed to delete docs, database not empty'
+    assert len(resp['rows']) == 0, 'Failed to delete docs, database not empty'
 
     # delete database
     resp = yield db2.delete_db()
     resp = yield db.view('test', 'msg')
     assert [doc1['_id'], doc2['_id']] == \
            [row['key'] for row in resp['rows']], \
-           'Failed to get view results from design doc'
+        'Failed to get view results from design doc'
 
     # delete doc
     resp = yield db.delete_doc(doc2)
     # save attachment
     data = {'msg3': 'This is a test'}
     attachment = {'mimetype': 'application/json',
-            'name': 'test attachment', 'data': json.dumps(data)}
+                  'name': 'test attachment', 'data': json.dumps(data)}
 
     resp = yield db.save_attachment(doc1, attachment)
     assert 'ok' in resp, 'Attachment not saved'
     resp = yield db.get_attachment(doc1, attachment['name'],
                                    attachment['mimetype'])
     assert json.loads(resp.decode('utf8')) == data, \
-           'Attachment not loaded'
+        'Attachment not loaded'
 
     # delete attachment
     resp = yield db.delete_attachment(doc1, attachment['name'])
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.