Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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...
         #Format error and return...

def getValueHelper(value):
        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

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 Mar 13 '13 at 23:50

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

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:

share|improve this answer

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:

    db = Foo()
except Exception, e:

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

Your Answer


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