python - 使用 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')
我开始认为问题可能来自这样一个事实,即访问表、读取表然后从同一个连接修改它可能存在问题?我在网上找不到太多关于该主题的内容。对此的任何帮助都非常受欢迎
解决方案
推荐阅读
- javascript - 我如何通过在 react-native 中使用反应导航来传递数据?
- sql - SQL Server 获取标识号并分配给另一个列值
- pandas - 熊猫添加日期时间列
- python - 使用 XGBOOST 执行特征选择时的不同结果
- javascript - 在与 ngFor 相同的标签中作为点击函数是一个好习惯吗?角度和 JS
- python - 从列表列创建一个新的 Pandas 数据框
- python - 当我运行我的代码(关于使用 python 纸浆进行线性编程)时,无法得到任何答案
- javascript - 我收到 Postgresql 的 created_on 日期的语法错误
- phpmyadmin - #1227 - 访问被拒绝;您在 000webhost 中需要(至少一个)此操作的 SUPER 权限
- javascript - 如何将 JS 音频 Blob 保存为文件,以便可以将其发送到 Flask API