Open devMarlee opened 1 year ago
from flask import Flask, request, jsonify, Response
import asyncio
from asyncpg import create_pool, Pool
from asyncpg.connection import Connection
app = Flask(__name__)
# Initialize the connection pool globally
pool: Pool = None
async def init_pool():
global pool
pool = await create_pool(
min_size=50, max_size=100,
host='your_host', port='your_port',
user='your_username', password='your_password',
ssl=True
)
@app.before_first_request
async def setup_pool():
await init_pool()
@app.route('/route_name', methods=['POST'])
async def insert():
list_of_files = request.json.get('files', [])
response_list = []
async def execute_with_pool(file):
cmd = f"YOUR SQL COMMAND FOR {file}" # Adjust this to your actual command
try:
async with pool.acquire() as conn:
async with conn.transaction():
response = await conn.execute(cmd)
return response
except Exception as e:
print(f"Exception occurred: {e}")
return str(e)
tasks = [execute_with_pool(file) for file in list_of_files]
responses = await asyncio.gather(*tasks)
return jsonify(responses)
@app.teardown_appcontext
async def close_pool(exception=None):
global pool
if pool:
await pool.close()
if __name__ == '__main__':
app.run(threaded=True) # Gunicorn will handle multi-threading, this may not be necessary
Hello!! Did you manage to solve the problem? I just encountered exactly the same thing :) @devMarlee
Hello @long2ice and contributors, I am implementing connection pool in my Flask application. I am inserting a lot of files into Clickhouse at one time and wait for another long time. So I create a connection pool in each request and close it when the request is done.
My Flask app is running in Gunicorn with multiple threads.
However, i am getting an error like:
I only get this request from the second request and onwards (not on the first request). I am wondering if the problem could be related to something with thread-safety, SSL connections, or perhaps use of asyncio.gather with the connection pool
My route is like this:
Is this an incorrect way of using the connection pool?
Using python3.8, linux OS, asynch=0.2.2