Setting application_name on Postgres/SQLAlchemy

the answer to this is a combination of:

http://initd.org/psycopg/docs/module.html#psycopg2.connect

Any other connection parameter supported by the client library/server can be passed either in the connection string or as keywords. The PostgreSQL documentation contains the complete list of the supported parameters. Also note that the same parameters can be passed to the client library using environment variables.

where the variable we need is:

http://www.postgresql.org/docs/current/static/runtime-config-logging.html#GUC-APPLICATION-NAME

The application_name can be any string of less than NAMEDATALEN characters (64 characters in a standard build). It is typically set by an application upon connection to the server. The name will be displayed in the pg_stat_activity view and included in CSV log entries. It can also be included in regular log entries via the log_line_prefix parameter. Only printable ASCII characters may be used in the application_name value. Other characters will be replaced with question marks (?).

combined with :

http://docs.sqlalchemy.org/en/rel_0_8/core/engines.html#custom-dbapi-args

String-based arguments can be passed directly from the URL string as query arguments: (example…) create_engine() also takes an argument connect_args which is an additional dictionary that will be passed to connect(). This can be used when arguments of a type other than string are required, and SQLAlchemy’s database connector has no type conversion logic present for that parameter

from that we get:

e = create_engine("postgresql://scott:tiger@localhost/test?application_name=myapp")

or:

e = create_engine("postgresql://scott:tiger@localhost/test", 
              connect_args={"application_name":"myapp"})

Leave a Comment