洋葱头 洋葱头 - 3 months ago 18
Python Question

python-couchdb: How to check if database already exists

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?

Answer

You can do something like:

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