55502f40dc8b7c769880b10874abc9d0

I have some database access code with a bunch of functions that follow a similar pattern to the get_user() function I've attached. I haven't spent much time working in python or with MySQLdb so any pythonic tips are appreciated.

You'll notice that I have 2 boiler plate lines at the beginning and end of every function. It would be nice to cut down on those.

Also it would be nice if I could index into the result by column name rather than numerical index (result["user_name"] rather than result[1]).

def get_conn():
    host="myhost"
    user="myuser"
    password="mypass"
    db="mydb"
    conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db)
    return conn

def get_user(user_id):
    conn = get_conn()
    cur = conn.cursor()
    
    cur.execute("select id, user_name from users where id = %s", user_id)
    result = cur.fetchone()
    user_info = User(id=result[0], user_name=result[1])
        
    conn.commit()
    conn.close()

    return user_info

Refactorings

No refactoring yet !

64798a399a79ed8d34fa83ba0e61c1ac

ielectric.myopenid.com

July 9, 2009, July 09, 2009 08:04, permalink

1 rating. Login to rate!

You should take a look at sqlalchemy, you can use plain dbapi with all the neat features it provides.

7e01e4c31fb60d06e81990ae0b611fe1

Doug

August 5, 2009, August 05, 2009 10:40, permalink

No rating. Login to rate!

I'd strongly recommend using SQLAlchemy (http://www.sqlalchemy.org/).
If you're creating a web app then using a full framework like TurboGears or Django would be your best route to take.

Dd1696879621083cb32811a3b8926cd2

William Bowers

October 6, 2009, October 06, 2009 07:38, permalink

No rating. Login to rate!

You can also use Django's ORM (http://docs.djangoproject.com/en/dev/topics/db/) without actually having to use Django. That's Django's design philosophy (or one of them?) -- keep everything separate. Anyway, having used both Django's ORM and SQLAlchemy, I would highly recommend going the Django route, or at least trying both so you can make your own decision.

14d31365b5aa707c17590218afcecc65

Seun Osewa

October 29, 2009, October 29, 2009 05:57, permalink

1 rating. Login to rate!

Use the 'with' statement:

def get_conn():
    host="myhost"
    user="myuser"
    password="mypass"
    db="mydb"
    conn = MySQLdb.connect(host=host, user=user, passwd=password, db=db)
    return conn

def get_user(user_id):
    with get_conn() as cur:
        cur.execute("select id, user_name from users where id = %s", user_id)
        result = cur.fetchone()
        user_info = User(id=result[0], user_name=result[1])
    return user_info

Your refactoring





Format Copy from initial code

or Cancel