python – Improving response time of flask endpoint


The flask endpoint is supposed to take a table name as a parameter, and then return the entire contents of the table as JSON. The table has 200,000 rows and I was wondering if there is any way to improve the response time which is currently about 7 seconds.

@app.route('/tableToJson')
def retrieve_dataset():
    '''
    Accepts a table name as a parameter and returns the output of the table as JSON
    '''
    table_name = request.args.get('table', type = str)
    if not table_name:
        content = {'success':False,'message':'A table name must be provided','status':400}
        return make_response(jsonify(content), 400)
    db = PGConnect()
    result = db.query_table(table_name)
    content = {'success':False,'data':result,'status':200}
    return make_response(jsonify(content), 200) 

The function querying the table looks like this:

def query_table(self, table_name):
    query = f'''SELECT jsonb_agg(to_jsonb(t))
                FROM (
                SELECT *
                from {table_name}
                ) t'''
    self.cursor.execute(query)
    return self.cursor.fetchall()