Skip to content

Instantly share code, notes, and snippets.

@estambolieva
Last active May 27, 2020 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save estambolieva/32cac557eb3fcf44ac968ed23be3157e to your computer and use it in GitHub Desktop.
Save estambolieva/32cac557eb3fcf44ac968ed23be3157e to your computer and use it in GitHub Desktop.
Postgress Connection Pool with Gunicorn and Connexion
#!/usr/bin/env python3
import configparser, os
import connexion
from swagger_server import encoder
from flask_cors import CORS
from flask import g, jsonify
import psycopg2
from psycopg2 import pool
application = connexion.App(__name__, specification_dir='./swagger/')
CORS(application.app)
application.app.json_encoder = encoder.JSONEncoder
application.add_api('swagger.yaml', arguments={'title': 'My Simple Swagger API'})
# CREATE A DB CONNECTION POOL FOR THIS APPLICATION
config = configparser.ConfigParser()
CONFIG_ABSOLUTE_PATH = os.getcwd() + os.sep + 'config.ini'
config.read_file(open(CONFIG_ABSOLUTE_PATH))
postgres_url = config.get('POSTGRES', 'URL')
postgres_port = config.get('POSTGRES', 'PORT')
postgres_user = config.get('POSTGRES', 'USER')
postgres_pwd = config.get('POSTGRES', 'PW')
postgres_db = config.get('POSTGRES', 'DB')
application.app.config['postgreSQL_pool'] = psycopg2.pool.ThreadedConnectionPool(1, 20,
user = postgres_user,
password = postgres_pwd,
host = postgres_url,
port = postgres_port,
database = postgres_db)
@application.app.before_request
def before_request():
g.db = application.app.config['postgreSQL_pool'].getconn()
@application.app.teardown_appcontext
def close_conn(e):
print('CLOSING CONN')
db = g.pop('db', None)
if db is not None:
application.config['postgreSQL_pool'].putconn(db)
if __name__ == '__main__':
application.run(port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment