Python 練習(xí)冊,每天一個小程序,原題來自Yixiaohan/show-me-the-code
我的代碼倉庫在Github
目標(biāo)
做為 Apple Store App 獨立開發(fā)者,你要搞限時促銷,為你的應(yīng)用生成激活碼(或者優(yōu)惠券),使用 Python 生成 200 個激活碼(或者優(yōu)惠券),并將激活碼保存到 MySQL 關(guān)系型數(shù)據(jù)庫中。
解決方案
該題目采用 python 中的 PyMySQL 模塊 來連接操作MySQL數(shù)據(jù)庫,代碼如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 將0001題目中隨機生成的驗證碼保存到MySQL數(shù)據(jù)庫
import uuid
import pymysql
# 生成 num 個驗證碼,每個長度為length,可設(shè)置默認(rèn)長度
def create_num(num, length=16):
result = []
while num > 0:
uuid_id = uuid.uuid4()
# 刪去字符串中的'-',取出前l(fā)ength 個字符
temp = str(uuid_id).replace('-', '')[:length]
if temp not in result:
result.append(temp)
num -= 1
return result
# 保存到MySQL數(shù)據(jù)庫
def save_to_mysql(code):
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd=None,
db='test')
try:
with conn.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `codes` (`code`) VALUES (%s)"
cursor.execute(sql, code)
# connection is not autocommit by default. So you must commit to save
# your changes.
conn.commit()
with conn.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `code` FROM `codes` WHERE `code`=%s"
cursor.execute(sql, code)
result = cursor.fetchone()
print(result)
finally:
conn.close()
for code in create_num(200):
save_to_mysql(code)