|
| 1 | +#coding=utf-8 |
| 2 | + |
| 3 | +import uuid |
| 4 | + |
| 5 | +import MySQLdb |
| 6 | + |
| 7 | +""" |
| 8 | +002, 将 0001 题生成的 200 个激活码(或者优惠券)保存到 **MySQL** 关系型数据库中 |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +class ActivationCode(object): |
| 13 | + def __init__(self, code_count, database, username, host='localhost', port=3306, password=''): |
| 14 | + self._host = host |
| 15 | + self._username = username |
| 16 | + self._password = password |
| 17 | + self._database = database |
| 18 | + self._port = port |
| 19 | + |
| 20 | + self.codes = self._generate_activation_code(code_count) |
| 21 | + #print self.codes |
| 22 | + |
| 23 | + |
| 24 | + def _get_mysql_instance(self): |
| 25 | + params = { |
| 26 | + 'host': self._host, |
| 27 | + 'user': self._username, |
| 28 | + 'passwd': self._password, |
| 29 | + 'db': self._database, |
| 30 | + 'port': self._port, |
| 31 | + } |
| 32 | + return MySQLdb.connect(**params) |
| 33 | + |
| 34 | + |
| 35 | + def _generate_activation_code(self, count): |
| 36 | + code_list = [] |
| 37 | + for i in xrange(count): |
| 38 | + code = str(uuid.uuid4()).replace('-', '').upper() |
| 39 | + if not code in code_list: |
| 40 | + code_list.append(code) |
| 41 | + |
| 42 | + return code_list |
| 43 | + |
| 44 | + |
| 45 | + def store_to_mysql(self): |
| 46 | + if self.codes: |
| 47 | + conn = self._get_mysql_instance() |
| 48 | + |
| 49 | + try: |
| 50 | + cur = conn.cursor() |
| 51 | + |
| 52 | + # clear old datas |
| 53 | + cur.execute('delete from code') |
| 54 | + |
| 55 | + # insert mutilple code |
| 56 | + for code in self.codes: |
| 57 | + cur.execute("insert into code(code) values('%s')" % code) |
| 58 | + |
| 59 | + conn.commit() |
| 60 | + cur.close() |
| 61 | + conn.close() |
| 62 | + |
| 63 | + return True |
| 64 | + except MySQLdb.Error,e: |
| 65 | + conn.rollback() |
| 66 | + print "Mysql Error %d: %s" % (e.args[0], e.args[1]) |
| 67 | + |
| 68 | + return False |
| 69 | + |
| 70 | + |
| 71 | + def print_activation_code(self): |
| 72 | + conn = self._get_mysql_instance() |
| 73 | + |
| 74 | + try: |
| 75 | + cur = conn.cursor() |
| 76 | + cur.execute('select code from code') |
| 77 | + |
| 78 | + results = cur.fetchall() |
| 79 | + for row in results: |
| 80 | + print row[0] |
| 81 | + except MySQLdb.Error,e: |
| 82 | + print "Mysql Error %d: %s" % (e.args[0], e.args[1]) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + active_code = ActivationCode(200, database='Test', username='root') |
| 87 | + if active_code.store_to_mysql(): |
| 88 | + active_code.print_activation_code() |
0 commit comments