开发者

urllib2 exception handling with couchdb

I usually have a hard time nailing down how to handle urllib2 exceptions. So I'm still lea开发者_运维问答rning. Here is a scenario that I'd like some advice on.

I have a local couch db database. I want to know if the database exists. ie "127.0.0.1:5984/database". If it does not exist, and I can reach "127.0.0.1:5984", I want to know so I can create the new database.

Here are several cases I'm thinking about:

1) I could get a timeout.

2) my url is wrong in the sense that I fail to reach the database entirely ie I typed 127.0.4.1:5984/database but couchdb is on 127.0.0.1:5984

3) the database path "database" does not exist on the couch database.

So here some code I wrote to handle it:

What I do is test the response. If everything is fine I set db_exists to True. The only time I set db_exists to False is if I get a 404. Everything else just exits the program.

request = urllib2.Request(address)
try:
    response = urllib2.urlopen(request)
except urllib2.URLError, e:
    if hasattr(e, 'reason'):
        print 'Failed to reach database'
        print 'Reason: ', e.reason
        sys.exit()
    elif hasattr(e, 'code'):
        if e.code == 404:
            db_exists = False
        else:
            print 'Failed to reach database'
            print 'Reason: ' + str(e)
            sys.exit()
else:
    try:
                    #I am expecting a json response. So make sure of it.
        json.loads(response.read())
    except:
        print 'Failed to reach database at "' + address + '"'
        sys.exit()
    else:
        db_exists = True

I am following the exception handling scheme layed out in URLlib2 The Missing Manual.

So basically my questions are...

1) Is this a clean, robust way to handle this?

2) is it common practice to sprinkle sys.exit() throughout code.

-Update- Using couchdb-python:

main(db_url):
    database = couchdb.Database(url=db_url)
    try:
        database.info()
    except couchdb.http.ResourceNotFound, err:
        print '"' + db_url + '" ' + err.message[0] + ', ' + err.message[1]
        return
    except couchdb.http.Unauthorized, err:
        print err.message[1]
        return
    except couchdb.http.ServerError, err:
        print err.message
        return
    except socket.error, err:
        print str(err)
        return

if __name__ == '__main__':
    # note that id did not show it here, but db_url comes from an arg.
    main(db_url)


I would argue that you're attacking this problem at too low a level. Why not use couchdb-python?

To answer your questions, 1) no it is not an especially clean way to do this. I would at least factor the code in your except block out into a method that extracts error types suitable for your application out of the urrlib2.URLError. For 2), no it is bad practice to call sys.exit() nearly all the time. Raise an appropriate exception. By default this will bubble up and halt the interpreter, just like your sys.exit() but with a traceback. Or, since your Couch client is a library, the exceptions can be handled at the application's discretion. Library code should never exit the interpreter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜