python设置卡密
时间: 2025-08-21 18:54:20 AIGC 浏览: 15
### 卡密生成与验证
#### 生成卡密
为了创建有效的卡密,在Python中可以利用随机数生成功能来构建唯一的字符串作为激活码。下面是一个简单的例子,它展示了如何基于时间戳和随机字符组合生成唯一卡密:
```python
import random
import string
from datetime import datetime
def generate_card_key(length=16):
"""Generate a unique card key."""
timestamp = str(int(datetime.now().timestamp()))
chars = string.ascii_letters + string.digits
rand_str = ''.join(random.choice(chars) for _ in range(length))
return f"{rand_str}-{timestamp[:8]}" # Combine with part of the timestamp to ensure uniqueness
```
此函数`generate_card_key()`会返回一个由字母数字组成的字符串加上当前的时间戳前缀,确保每次产生的卡密具有高度的独特性[^1]。
#### 存储卡密
一旦生成了这些卡密,则需将其保存到数据库或其他持久化存储介质内供后续验证操作使用。这里假设采用MySQL数据库进行管理,并已在项目的初始化文件(`__init__.py`)里配置好了相应的连接库[^2]:
```python
import mysql.connector as mc
conn = mc.connect(
host="localhost",
user="root",
password="password",
database="auth_db"
)
cursor = conn.cursor()
card_keys_table_creation_query = """
CREATE TABLE IF NOT EXISTS CardKeys (
id INT AUTO_INCREMENT PRIMARY KEY,
key_value VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
"""
insert_into_cardkeys_query = "INSERT INTO CardKeys (key_value) VALUES (%s)"
try:
cursor.execute(card_keys_table_creation_query)
generated_key = generate_card_key()
cursor.execute(insert_into_cardkeys_query, (generated_key,))
conn.commit()
except Exception as e:
print(f"Error occurred while inserting data into table {e}")
finally:
if(conn.is_connected()):
cursor.close()
conn.close()
```
上述代码片段实现了向名为`CardKeys`的数据表插入新记录的功能,其中包含了之前定义好的`generate_card_key()`所生产的卡密值。
#### 验证卡密
当用户尝试输入卡密时,程序应当能够查询已有的数据并判断该卡密是否存在以及是否有效。以下是关于如何执行这项工作的示范代码:
```python
def validate_card_key(input_key):
"""Validate an inputted card key against stored ones."""
try:
connection = mc.connect(host='localhost',database='auth_db',
user='root',password='password')
sql_select_Query = "select * from CardKeys where key_value=%s;"
cursor = connection.cursor(buffered=True)
result = cursor.execute(sql_select_Query,(input_key,))
records = cursor.fetchall()
is_valid = bool(records) and not any(record[-1].strftime('%Y-%m-%d') < '2023-01-01' for record in records)
return is_valid
except Error as error :
print("Failed to read data from MySQL table", error)
finally:
if(connection.is_connected()):
connection.close()
cursor.close()
if __name__ == '__main__':
test_key = 'your_test_generated_key_here'
print(validate_card_key(test_key)) # Should output True or False based on existence & validity check.
```
这段脚本负责接收来自用户的卡密输入,并通过对比数据库中的条目确认其有效性;同时考虑到可能存在的过期情况,也加入了日期过滤逻辑以增强安全性.
阅读全文
相关推荐




















