Python实现 多进程导入CSV数据到 MySQL


Posted in Python onFebruary 26, 2017

前段时间帮同事处理了一个把 CSV 数据导入到 MySQL 的需求。两个很大的 CSV 文件, 分别有 3GB、2100 万条记录和 7GB、3500 万条记录。对于这个量级的数据,用简单的单进程/单线程导入 会耗时很久,最终用了多进程的方式来实现。具体过程不赘述,记录一下几个要点:

  1. 批量插入而不是逐条插入
  2. 为了加快插入速度,先不要建索引
  3. 生产者和消费者模型,主进程读文件,多个 worker 进程执行插入
  4. 注意控制 worker 的数量,避免对 MySQL 造成太大的压力
  5. 注意处理脏数据导致的异常
  6. 原始数据是 GBK 编码,所以还要注意转换成 UTF-8
  7. 用 click 封装命令行工具

具体的代码实现如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import codecs
import csv
import logging
import multiprocessing
import os
import warnings

import click
import MySQLdb
import sqlalchemy

warnings.filterwarnings('ignore', category=MySQLdb.Warning)

# 批量插入的记录数量
BATCH = 5000

DB_URI = 'mysql://root@localhost:3306/example?charset=utf8'

engine = sqlalchemy.create_engine(DB_URI)


def get_table_cols(table):
  sql = 'SELECT * FROM `{table}` LIMIT 0'.format(table=table)
  res = engine.execute(sql)
  return res.keys()


def insert_many(table, cols, rows, cursor):
  sql = 'INSERT INTO `{table}` ({cols}) VALUES ({marks})'.format(
      table=table,
      cols=', '.join(cols),
      marks=', '.join(['%s'] * len(cols)))
  cursor.execute(sql, *rows)
  logging.info('process %s inserted %s rows into table %s', os.getpid(), len(rows), table)


def insert_worker(table, cols, queue):
  rows = []
  # 每个子进程创建自己的 engine 对象
  cursor = sqlalchemy.create_engine(DB_URI)
  while True:
    row = queue.get()
    if row is None:
      if rows:
        insert_many(table, cols, rows, cursor)
      break

    rows.append(row)
    if len(rows) == BATCH:
      insert_many(table, cols, rows, cursor)
      rows = []


def insert_parallel(table, reader, w=10):
  cols = get_table_cols(table)

  # 数据队列,主进程读文件并往里写数据,worker 进程从队列读数据
  # 注意一下控制队列的大小,避免消费太慢导致堆积太多数据,占用过多内存
  queue = multiprocessing.Queue(maxsize=w*BATCH*2)
  workers = []
  for i in range(w):
    p = multiprocessing.Process(target=insert_worker, args=(table, cols, queue))
    p.start()
    workers.append(p)
    logging.info('starting # %s worker process, pid: %s...', i + 1, p.pid)

  dirty_data_file = './{}_dirty_rows.csv'.format(table)
  xf = open(dirty_data_file, 'w')
  writer = csv.writer(xf, delimiter=reader.dialect.delimiter)

  for line in reader:
    # 记录并跳过脏数据: 键值数量不一致
    if len(line) != len(cols):
      writer.writerow(line)
      continue

    # 把 None 值替换为 'NULL'
    clean_line = [None if x == 'NULL' else x for x in line]

    # 往队列里写数据
    queue.put(tuple(clean_line))
    if reader.line_num % 500000 == 0:
      logging.info('put %s tasks into queue.', reader.line_num)

  xf.close()

  # 给每个 worker 发送任务结束的信号
  logging.info('send close signal to worker processes')
  for i in range(w):
    queue.put(None)

  for p in workers:
    p.join()


def convert_file_to_utf8(f, rv_file=None):
  if not rv_file:
    name, ext = os.path.splitext(f)
    if isinstance(name, unicode):
      name = name.encode('utf8')
    rv_file = '{}_utf8{}'.format(name, ext)
  logging.info('start to process file %s', f)
  with open(f) as infd:
    with open(rv_file, 'w') as outfd:
      lines = []
      loop = 0
      chunck = 200000
      first_line = infd.readline().strip(codecs.BOM_UTF8).strip() + '\n'
      lines.append(first_line)
      for line in infd:
        clean_line = line.decode('gb18030').encode('utf8')
        clean_line = clean_line.rstrip() + '\n'
        lines.append(clean_line)
        if len(lines) == chunck:
          outfd.writelines(lines)
          lines = []
          loop += 1
          logging.info('processed %s lines.', loop * chunck)

      outfd.writelines(lines)
      logging.info('processed %s lines.', loop * chunck + len(lines))


@click.group()
def cli():
  logging.basicConfig(level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')


@cli.command('gbk_to_utf8')
@click.argument('f')
def convert_gbk_to_utf8(f):
  convert_file_to_utf8(f)


@cli.command('load')
@click.option('-t', '--table', required=True, help='表名')
@click.option('-i', '--filename', required=True, help='输入文件')
@click.option('-w', '--workers', default=10, help='worker 数量,默认 10')
def load_fac_day_pro_nos_sal_table(table, filename, workers):
  with open(filename) as fd:
    fd.readline()  # skip header
    reader = csv.reader(fd)
    insert_parallel(table, reader, w=workers)


if __name__ == '__main__':
  cli()

以上就是本文给大家分享的全部没人了,希望大家能够喜欢

Python 相关文章推荐
设计模式中的原型模式在Python程序中的应用示例
Mar 02 Python
Django日志模块logging的配置详解
Feb 14 Python
python中lambda()的用法
Nov 16 Python
快速解决安装python没有scripts文件夹的问题
Apr 03 Python
python列表list保留顺序去重的实例
Dec 14 Python
解决Python中list里的中文输出到html模板里的问题
Dec 17 Python
Python使用到第三方库PyMuPDF图片与pdf相互转换
May 03 Python
django框架使用方法详解
Jul 18 Python
tensorflow实现tensor中满足某一条件的数值取出组成新的tensor
Jan 04 Python
python 动态绘制爱心的示例
Sep 27 Python
用python写PDF转换器的实现
Oct 29 Python
教你怎么用Python监控愉客行车程
Apr 29 Python
python检查URL是否正常访问的小技巧
Feb 25 #Python
python解析基于xml格式的日志文件
Feb 25 #Python
Python中防止sql注入的方法详解
Feb 25 #Python
Python 数据结构之旋转链表
Feb 25 #Python
Python数据结构之翻转链表
Feb 25 #Python
浅析python中SQLAlchemy排序的一个坑
Feb 24 #Python
python函数的5种参数详解
Feb 24 #Python
You might like
通过对php一些服务器端特性的配置加强php的安全
2006/10/09 PHP
探讨如何在PHP开启gzip页面压缩实例
2013/06/09 PHP
php使用qr生成二维码的示例分享
2014/01/20 PHP
php把数据表导出为Excel表的最简单、最快的方法(不用插件)
2014/05/10 PHP
php+ajax无刷新分页实例详解
2015/12/07 PHP
JS 页面内容搜索,类似于 Ctrl+F功能的实现代码
2007/08/13 Javascript
js wmp操作代码小结(音乐连播功能)
2008/11/08 Javascript
非常强大的 jQuery.AsyncBox 弹出对话框插件
2011/08/29 Javascript
单击按钮显示隐藏子菜单经典案例
2013/01/04 Javascript
Extjs3.0 checkboxGroup 动态添加item实现思路
2013/08/14 Javascript
javascript loadScript异步加载脚本示例讲解
2013/11/14 Javascript
详解JavaScript中常用的函数类型
2015/11/18 Javascript
jquery实现点击其他区域时隐藏下拉div和遮罩层的方法
2015/12/23 Javascript
jquery仿ps颜色拾取功能
2017/03/08 Javascript
深入理解JS的事件绑定、事件流模型
2018/05/13 Javascript
nodejs require js文件入口,在package.json中指定默认入口main方法
2018/10/10 NodeJs
解决vue 界面在苹果手机上滑动点击事件等卡顿问题
2018/11/27 Javascript
Angular如何由模板生成DOM树的方法
2019/12/23 Javascript
js实现简单的无缝轮播效果
2020/09/05 Javascript
[00:10]DOTA2全国高校联赛速递
2018/05/30 DOTA
Python编码类型转换方法详解
2016/07/01 Python
python文件名和文件路径操作实例
2017/09/29 Python
浅谈django三种缓存模式的使用及注意点
2018/09/30 Python
浅谈tensorflow 中tf.concat()的使用
2020/02/07 Python
python线程里哪种模块比较适合
2020/08/02 Python
美国复古街头服饰精品店:Need Supply Co.
2017/02/22 全球购物
享受加州生活方式的时尚舒适:XCVI
2018/07/09 全球购物
Feelunique德国官方网站:欧洲最大的在线美容零售商
2019/07/20 全球购物
喷漆工的岗位职责
2014/03/17 职场文书
在职员工证明书
2014/09/19 职场文书
渠道运营商合作协议书范本
2014/10/06 职场文书
单位作风建设自查报告
2014/10/23 职场文书
党员群众路线整改措施及今后努力方向
2014/10/28 职场文书
银行文明优质服务培训心得体会
2016/01/09 职场文书
2016廉洁教育心得体会
2016/01/20 职场文书
关于JavaScript轮播图的实现
2021/11/20 Javascript