首页 > 解决方案 > 使用 sqlalchemy 将 pandas 数据帧复制到 postgresql 会导致 502 bad gateway 错误

问题描述

我正在尝试从 django 表单更新 postgresql 表。我正在访问表格,修改表格,然后将更改保存在表格中。该表有大约 100k 行。我尝试使用df.to_sql,但它太慢了,以至于导致502 bad gateway错误。

在查看了 sqalchemy doc 和 stackoverflow 之后,我构建了这个:

engine = create_engine('postgresql://user:password@ip_address/db',
                               connect_args={'options': '-csearch_path={}'.format(dbschema)})

conn = engine.connect()
metadata = sqlalchemy.MetaData()
histoo = sqlalchemy.Table('uploadfiles_histoo', metadata, autoload=True, autoload_with=engine)
query = sqlalchemy.select([histoo])
resultproxy = conn.execute(query)
result_set = resultproxy.fetchall()
        
    
histoo = pd.DataFrame(result_set)
histoo.columns = result_set[0].keys()
        
data_initial = data_initial.append(histoo)
histo2 = pd.DataFrame(data_initial['Id'])


histo2[:0].to_sql('uploadfiles_histoo', engine, if_exists='replace')

            
output = io.StringIO()
histo2.to_csv(output, sep='\t', header=False, encoding='utf8')
output.seek(0)

           
connection = engine.raw_connection()
cursor = connection.cursor()
cursor.copy_from(output, 'uploadfiles_histoo', sep='\t', null='')
connection.commit()
cursor.close()

当我运行这段代码时,它仍然会导致502 bad gateway这意味着我一定做错了什么并且它并没有提高导入的性能。我真的很难理解可能出了什么问题,尤其是知道脚本没有输出与之相关的错误。我没有可以尝试的东西,希望有人能在这里发现我错了

更新:我发现对于 python 3,cStringI0就像io.StringIO这样写:

histo2db = histo2.to_sql('uploadfiles_histoo', engine, if_exists='replace', header=False, method='multi',chunksize='5000')

我开始认为问题可能来自这样一个事实,即访问表、读取表然后从同一个连接修改它可能存在问题?我在网上找不到太多关于该主题的内容。对此的任何帮助都非常受欢迎

标签: pythonpandaspostgresqlsqlalchemy

解决方案


推荐阅读