4

I am writing a small Python program that loads some documents into couchdb. It would be very convenient to check whether a database with a certain name already exists, so I can either create a new one or open the existing one. What I want to do is something like this:

import couchdb

def connect(url, dbName):
    server = couchdb.Server(url)
    if dbName exists: # how do I do this?
        return server[dbName]
    else:
        return server.create(dbName)

I know a try-except block would do the trick, but isn't there a more elegant way?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
arne.z
  • 3,242
  • 3
  • 24
  • 46

2 Answers2

7

The easiest way I can think is:

import couchdb
server = couchdb.Server("http://localhost:5984")
"dataBaseName" in server

Return True if a database with the name exists, False otherwise

https://github.com/djc/couchdb-python/blob/master/couchdb/client.py#L90-L101

João Amaro
  • 86
  • 1
  • 6
  • Thanks for your answer. That's indeed a lot nicer. – arne.z Aug 26 '16 at 10:51
  • There's a good examples of simple commands for couchdb using python in this link: https://gist.github.com/marians/8e41fc817f04de7c4a70. – haper Jan 06 '18 at 14:11
1

You can do something like:

try:
    couch = couchdb.Server() # assuming localhost
    db = couch['existent']
except:
    db = couch.create('somedb')