python 批量生成优惠券码并写入数据表

说明:这篇文章主要讲的是个人工作中遇到的解决问题的方法,而非程序写的多优美。要完善的地方太多了,大家嘴下留情

why do this

为什么要这么做?优惠券码直接在用的时候用程序直接生成不就OK了吗?

好,那么问题来了,我们的系统需要一次性发送几十万张优惠券,怎么破。这里引来这个问题(php编写的web程序)
1.通过php函数来生成几十万个优惠券码,然后分批次比如每次1000插入到数据表中,主要考虑到这几十万的码会占用大量内存,而且php执行时间也会过长,虽然可以设置超时时间,但总归不是better的解决方案
2.现有各个系统中都存在自己优惠券码的生成规则,但是数据表却是同一张,有了这个优惠码池,各个系统就无需再自己生成优惠码,而是直接要用多少读取多少即可。

引申出优惠券码池表(保证code值唯一)

数据表结构
CREATE TABLE `prefix_coupon_pool` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增ID',
  `code` varchar(32) NOT NULL COMMENT '优惠券码 唯一性约束',
  `is_assigned` tinyint(1) DEFAULT '0' COMMENT '0:未分配 1:已分配',
  `created_at` int(10) unsigned DEFAULT '0' COMMENT '生成时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_code` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

python 代码说明

1.安装python-dotenv用来获取.env配置

git:https://github.com/theskumar/python-dotenv

2.建立.env文件
  DB_HOST=localhost
  DB_DATABASE=test
  DB_USERNAME=root
  DB_PASSWORD=root
  DB_PORT=3306
调用方法 ./pymakecoupon.py pp 6 10000

pp:优惠券前缀

6:优惠券长度

10000:生成个数

python源码如下
#!/usr/bin/env python
#coding:utf-8

import random
import string
from os.path import join, dirname
from dotenv import load_dotenv
from mysql import connector
import mysql
import os
import time
import sys


originCode = string.ascii_lowercase
failedRecord = 0

def getConnection():
    dotenv_path = join(dirname(__file__), '.env')
    print dotenv_path
    load_dotenv(dotenv_path)
    host = os.environ.get('DB_HOST')
    user = os.environ.get('DB_USERNAME')
    password = os.environ.get('DB_PASSWORD')
    database = os.environ.get('DB_DATABASE')
    port = os.environ.get('DB_PORT')
    try:
        connect = connector.connect(host=host, user=user, password=password, database=database, port=port)
        return connect
    except mysql.connector.Error as e:
        print e
        return False
    except Exception as e:
        return False

def makeCouponCode(prefix='p', length = 6):
    str = prefix
    if length == 0:
        pass
    for index in range(length):
        str += random.choice(originCode)
    return str

if __name__ == '__main__':
    args = sys.argv
    codeList = []
    if len(args) != 4:
        print '参数错误,调用方式为:./pymakecoupon.py p10 6 100'
        exit()
    try:
        prefix = args[1]
        length = int(args[2])
        count = int(args[3])
    except IndexError as e:
        print '参数错误'

    msg = '将生成前缀为:%s,优惠券长度为:%s,总共%s个优惠券码'
    msg = msg % (prefix, length, count)
    print msg
    inputPrompt = raw_input('y/n\n')
    if inputPrompt == 'y':
        pass
    else:
        print 'bye'
        exit

    connect = getConnection()
    if connect == False:
        sys.exit(0)
    cursor = connect.cursor()
    codeString = ''
    now = int(time.time())
    for index in range(1,count+1):
        pass
        code = makeCouponCode(prefix,length)
        codeTemplate = '(\'%s\',%s)'
        code = codeTemplate % (code,now)
        codeList.append(code)
        print code
        if index % 1000 == 0:
            codeString = ",".join(codeList)
            sql = 'INSERT IGNORE INTO prefix_coupon_pool(code,created_at)VALUES %s'
            sql = sql % (codeString)
            cursor.execute(sql)
            connect.commit()
    connect.close




tomato
309 声望19 粉丝

1个在coding路上越走越迷茫的coder