Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am creating a Python Flask webservice and this is basically how I am doing all of my database calls if a webservice needs to interact with the database:

@event.route("/somepath/<value>", methods = ['GET'])
def getValue(value):
    result = getValueHelper(value)
    if (result != None)
         #format result and return...
    else
         #Format error and return...

def getValueHelper(value):
    try:
        db = getDBConnection()
        query = text('select * from my_table where value=:q_value')
        Result = db.execute(query, q_value=value)
        return Result
    except Exception, e:
        current_app.logger.error("Some sort of error message")
        return None
    finally:
        db.close()

Is this a good way to be doing it? I am fairly new to Flask and SQLAlchemy, so I'm not sure if what I am doing would be considered a good practice.

share|improve this question

migrated from programmers.stackexchange.com Mar 13 '13 at 23:50

This question came from our site for professional programmers interested in conceptual questions about software development.

add comment

2 Answers

If you really want to use SQLAlchemy, you should define some model classes that abstract your database layout. Then you would perform a query like model.Session.query(model.MyTable).filter(model.MyTable.value==value).first()

Writing literal SQL is mostly not needed anymore then...

Try reading the object relational tutorial for SQLAlchemy: http://docs.sqlalchemy.org/en/rel_0_8/orm/tutorial.html

share|improve this answer
add comment

You took the wrong approach here. Don't instantiate a database connection upon each request. This is something a connection pool should handle transparently for you. So, please take your time, follow an SQLAlchemy tutorial, and find out how to use SQLAlchemy properly. It's not difficult.

Another thing:

try:
    db = Foo()
except Exception, e:
    foo()
finally:
    db.close()

If there is an exception in Foo(), then db will be an unbound name leading to an UnboundLocalError in the finally clause.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.