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实现带声音的摩斯码翻译实现方法
May 20 Python
Python脚本实现自动将数据库备份到 Dropbox
Feb 06 Python
Python 多进程并发操作中进程池Pool的实例
Nov 01 Python
关于反爬虫的一些简单总结
Dec 13 Python
python 动态加载的实现方法
Dec 22 Python
Python设计模式之门面模式简单示例
Jan 09 Python
Django 限制用户访问频率的中间件的实现
Aug 23 Python
python得到windows自启动列表的方法
Oct 14 Python
python中logging模块的一些简单用法的使用
Feb 22 Python
flask框架自定义过滤器示例【markdown文件读取和展示功能】
Nov 08 Python
python列表切片和嵌套列表取值操作详解
Feb 27 Python
使用wxpy实现自动发送微信消息功能
Feb 28 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 OPCode缓存 APC详细介绍
2010/10/12 PHP
浅析Dos下运行php.exe,出现没有找到php_mbstring.dll 错误的解决方法
2013/06/29 PHP
用Zend Studio+PHPnow+Zend Debugger搭建PHP服务器调试环境步骤
2014/01/19 PHP
php+ajax实现文章自动保存的方法
2014/12/30 PHP
在Linux系统的服务器上隐藏PHP版本号的方法
2015/06/06 PHP
php创建无限级树型菜单
2015/11/05 PHP
PHP给源代码加密的几种方法汇总(推荐)
2018/02/06 PHP
一些不错的js函数ajax
2008/08/20 Javascript
jquery实现的可隐藏重现的靠边悬浮层实例代码
2013/05/27 Javascript
js图片处理示例代码
2014/05/12 Javascript
使用JSON.parse将json字符串转换成json对象的时候会出错
2014/09/04 Javascript
多个checkbox被选中时如何判断是否有自己想要的
2014/09/22 Javascript
jQuery循环动画与获取组件尺寸的方法
2015/02/02 Javascript
解决bootstrap中modal遇到Esc键无法关闭页面
2015/03/09 Javascript
js变形金刚文字特效代码分享
2015/08/20 Javascript
JavaScript操作HTML元素和样式的方法详解
2015/10/21 Javascript
解决vue 路由变化页面数据不刷新的问题
2018/03/13 Javascript
微信小程序如何实现精确的日期时间选择器
2020/01/21 Javascript
工作中常用js功能汇总
2020/11/07 Javascript
[03:40]DOTA2英雄梦之声_第01期_炼金术士
2014/06/23 DOTA
[03:01]完美盛典趣味短片 DOTA2年度最佳&拉胯英雄
2019/12/07 DOTA
基于python实现微信模板消息
2015/12/21 Python
Centos7 Python3下安装scrapy的详细步骤
2018/03/15 Python
python读取csv文件指定行的2种方法详解
2020/02/13 Python
Keras 实现加载预训练模型并冻结网络的层
2020/06/15 Python
OpenCV+python实现膨胀和腐蚀的示例
2020/12/21 Python
python解决OpenCV在读取显示图片的时候闪退的问题
2021/02/23 Python
HTML5+CSS3实现拖放(Drag and Drop)示例
2014/07/07 HTML / CSS
BabyBjörn婴儿背带法国官网:BabyBjorn法国
2018/06/16 全球购物
吉列剃须刀美国官网:Gillette美国
2018/07/13 全球购物
LN-CC英国:伦敦时尚生活的缩影
2019/09/01 全球购物
Agoda中文官网:安可达(低价预订全球酒店)
2021/01/18 全球购物
儿科护理实习自我鉴定
2013/09/19 职场文书
自荐信不宜过于夸大
2013/11/06 职场文书
大学生军训广播稿
2014/01/24 职场文书
Golang 实现超大文件读取的两种方法
2021/04/27 Golang