librelist archives

« back to archive

db connection + logging configuration

db connection + logging configuration

From:
hubert depesz lubaczewski
Date:
2012-01-17 @ 22:25
Hi,
First of all - I'm starting to learn Python and Flask - at more or less
the same time.
I'm reading tutorial, and while doing it, I started coding first
project.
Based on what I read so far (answer can be later on in docs, if so,
I would appreciate simple pointer to it), I have following questions:

1. How can I have persistent database connection?

I have this app code:

#v+
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
from flask import Flask, url_for, render_template, request, flash, g

# Default configuration
DEBUG = False
SECRET_KEY = 'dev key'
HOST = '0.0.0.0'
DB_DATABASE = 'jab'
DB_PORT = 5920
DB_HOST = '/tmp'
# Default configuration

app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('JDC_SETTINGS', silent=True)

def get_db_connection():
    conn_details = dict()

    for i in ( j for j in ( 'database', 'user', 'password', 'host', 
'port', 'sslmode' ) if app.config.has_key( 'DB_' + j.upper() ) ):
        conn_details[ i ] = app.config[ 'DB_' + i.upper() ]

    return psycopg2.connect( **conn_details )

@app.before_request
def before_request():
    g.db = get_db_connection()

@app.teardown_request
def teardown_request(exception):
    g.db.rollback()

@app.route('/')
def index():
    c=g.db.cursor()
    c.execute("SELECT version()")
    version = c.fetchone()[0]
    return render_template( 'index.html', version=version)

if __name__ == '__main__':
    app.run( host=app.config['HOST'] )
#v-

Which works, but starts (and drops) new connection for every request.

How can I make it so that I will have persistent connection from app,
that will get reused for next requests?

2. How can I reconfigure Flask logger? I tried some (obviously bad,
   since it didn't work) stuff, but never got to anything. The simplest
   thing - adding time prefix for lines or logging to file, how can
   I set it up?

Best regards,

depesz

-- 
The best thing about modern society is how easy it is to avoid contact with it.
                                                             http://depesz.com/

-- 
The best thing about modern society is how easy it is to avoid contact with it.
                                                             http://depesz.com/

Re: [flask] db connection + logging configuration

From:
Ryo Mikami
Date:
2012-01-18 @ 01:23
Hi hebert.

1.
You can have persistent connection to put it on a top level scope like
your app variable.

2.
You can configure logger with add handlers to Flask.logger.
http://flask.pocoo.org/docs/errorhandling/

Good luck!

On Wed, Jan 18, 2012 at 7:25 AM, hubert depesz lubaczewski
<depesz@depesz.com> wrote:
> Hi,
> First of all - I'm starting to learn Python and Flask - at more or less
> the same time.
> I'm reading tutorial, and while doing it, I started coding first
> project.
> Based on what I read so far (answer can be later on in docs, if so,
> I would appreciate simple pointer to it), I have following questions:
>
> 1. How can I have persistent database connection?
>
> I have this app code:
>
> #v+
> #!/usr/bin/env python
> # -*- coding: utf-8 -*-
> import psycopg2
> from flask import Flask, url_for, render_template, request, flash, g
>
> # Default configuration
> DEBUG = False
> SECRET_KEY = 'dev key'
> HOST = '0.0.0.0'
> DB_DATABASE = 'jab'
> DB_PORT = 5920
> DB_HOST = '/tmp'
> # Default configuration
>
> app = Flask(__name__)
> app.config.from_object(__name__)
> app.config.from_envvar('JDC_SETTINGS', silent=True)
>
> def get_db_connection():
>    conn_details = dict()
>
>    for i in ( j for j in ( 'database', 'user', 'password', 'host', 
'port', 'sslmode' ) if app.config.has_key( 'DB_' + j.upper() ) ):
>        conn_details[ i ] = app.config[ 'DB_' + i.upper() ]
>
>    return psycopg2.connect( **conn_details )
>
> @app.before_request
> def before_request():
>    g.db = get_db_connection()
>
> @app.teardown_request
> def teardown_request(exception):
>    g.db.rollback()
>
> @app.route('/')
> def index():
>    c=g.db.cursor()
>    c.execute("SELECT version()")
>    version = c.fetchone()[0]
>    return render_template( 'index.html', version=version)
>
> if __name__ == '__main__':
>    app.run( host=app.config['HOST'] )
> #v-
>
> Which works, but starts (and drops) new connection for every request.
>
> How can I make it so that I will have persistent connection from app,
> that will get reused for next requests?
>
> 2. How can I reconfigure Flask logger? I tried some (obviously bad,
>   since it didn't work) stuff, but never got to anything. The simplest
>   thing - adding time prefix for lines or logging to file, how can
>   I set it up?
>
> Best regards,
>
> depesz
>
> --
> The best thing about modern society is how easy it is to avoid contact with it.
>                                                             http://depesz.com/
>
> --
> The best thing about modern society is how easy it is to avoid contact with it.
>                                                             http://depesz.com/

Re: [flask] db connection + logging configuration

From:
hubert depesz lubaczewski
Date:
2012-01-23 @ 19:19
On Wed, Jan 18, 2012 at 10:23:07AM +0900, Ryo Mikami wrote:
> Hi hebert.
> 
> 1.
> You can have persistent connection to put it on a top level scope like
> your app variable.
> 
> 2.
> You can configure logger with add handlers to Flask.logger.
> http://flask.pocoo.org/docs/errorhandling/
> 
> Good luck!

Sorry, somhow missed your mail. Thanks, will check the docs, and the db
connection will have to be global. thanks.

Best regards,

depesz

Re: [flask] db connection + logging configuration

From:
Carlos Gonzales
Date:
2012-01-23 @ 23:36
Sort of new here as well. I've been pretty much working the same way Hubert
mentions. How does having a persistent connection affect concurrent
requests? Would like to see some code showing how new transactions are
handled per request for example.

Saludos,
Carlos R. Gonzales


On Mon, Jan 23, 2012 at 1:19 PM, hubert depesz lubaczewski <
depesz@depesz.com> wrote:

> On Wed, Jan 18, 2012 at 10:23:07AM +0900, Ryo Mikami wrote:
> > Hi hebert.
> >
> > 1.
> > You can have persistent connection to put it on a top level scope like
> > your app variable.
> >
> > 2.
> > You can configure logger with add handlers to Flask.logger.
> > http://flask.pocoo.org/docs/errorhandling/
> >
> > Good luck!
>
> Sorry, somhow missed your mail. Thanks, will check the docs, and the db
> connection will have to be global. thanks.
>
> Best regards,
>
> depesz
>
>