基于python ttkbootstarp的密钥生成器

App key和App Secret

App key简称API接口验证序号,是用于验证API接入合法性的。接入哪个网站的API接口,就需要这个网站允许才能够接入,如果简单比喻的话:可以理解成是登陆网站的用户名。

App Secret简称API接口密钥,是跟App Key配套使用的,可以简单理解成是密码。

App Key 和 App Secret 配合在一起,通过其他网站的协议要求,就可以接入API接口调用或使用API提供的各种功能和数据。

比如淘宝联盟的API接口,就是淘宝客网站开发的必要接入,淘客程序通过API接口直接对淘宝联盟的数据库调用近亿商品实时数据。做到了轻松维护,自动更新。

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# pyinstaller --clean -w  -F -i favicon.ico app_gen.py -n 密钥生成器

import datetime
import hashlib
import os.path
import random
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from tkinter import filedialog as tkFileDialog
from ttkbootstrap.dialogs import Messagebox
import pyperclip
import base64
from icon import img

# 获取当前工作目录
path = os.getcwd()
# 默认文件名
filename = 'id_rsa.txt'

# 实例化创建应用程序窗口
root = ttk.Window(
    title="密钥生成器V1.0",  # 设置窗口的标题
    themename="litera",  # 设置主题
    minsize=(800, 400),  # 窗口的最小宽高
    maxsize=(1920, 1080),  # 窗口的最大宽高
    resizable=(True, True),  # 设置窗口是否可以更改大小
    alpha=1.0,  # 设置窗口的透明度(0.0完全透明)
)


def setIcon(root):
    tmp = open("tmp.ico", "wb+")
    tmp.write(base64.b64decode(img))  # 写入到临时文件中
    tmp.close()
    root.iconbitmap("tmp.ico")  # 设置图标
    os.remove("tmp.ico")


setIcon(root)

root.place_window_center()

root.wm_attributes('-topmost', 1)  # 让窗口位置其它窗口之上

ENTRY_WIDTH = 320
LABEL_LEFT_X = 160
ENTRY_LEFT_X = 280

# 在窗口上创建组件(AppId)
APP_ID_Y = 60
labeName = ttk.Label(root, text='AppId:', font=("微软雅黑", 16), bootstyle=INFO)
labeName.place(x=LABEL_LEFT_X, y=APP_ID_Y, width=125, height=40)
varId = ttk.StringVar(root, value='')
entryName = ttk.Entry(root, width=200, textvariable=varId, bootstyle=INFO)
entryName.place(x=ENTRY_LEFT_X, y=APP_ID_Y, width=ENTRY_WIDTH, height=40)


def callback1(event=None):
    if(varId.get() != ''):
        pyperclip.copy(varId.get())
        Messagebox.show_info(title='温馨提示', message='复制成功!')


buttonCopy1 = ttk.Button(
    root, text='复制', bootstyle=(PRIMARY, "outline-toolbutton"), command=callback1)
buttonCopy1.place(x=ENTRY_LEFT_X+ENTRY_WIDTH+20,
                  y=APP_ID_Y, width=60, height=40)


# 在窗口上创建组件(AppKey)
APP_KEY_Y = 120
labeName = ttk.Label(root, text='AppKey:', bootstyle=INFO, font=("微软雅黑", 16))
labeName.place(x=LABEL_LEFT_X, y=APP_KEY_Y, width=125, height=40)
varKey = ttk.StringVar(root, value='')
entryPwd = ttk.Entry(root, width=120, textvariable=varKey)
entryPwd.place(x=ENTRY_LEFT_X, y=APP_KEY_Y, width=ENTRY_WIDTH, height=40)


def callback2(event=None):
    if(varKey.get() != ''):
        pyperclip.copy(varKey.get())
        Messagebox.show_info(title='温馨提示', message='复制成功!')


buttonCopy1 = ttk.Button(
    root, text='复制', bootstyle=(PRIMARY, "outline-toolbutton"), command=callback2)
buttonCopy1.place(x=ENTRY_LEFT_X+ENTRY_WIDTH+20,
                  y=APP_KEY_Y, width=60, height=40)


# 在窗口上创建组件(AppSecret)
APP_SECRET_Y = 180
labeName = ttk.Label(root, text='AppSecret:',
                     bootstyle=INFO, font=("微软雅黑", 16))
labeName.place(x=LABEL_LEFT_X, y=APP_SECRET_Y, width=125, height=40)
varSecret = ttk.StringVar(root, value='')
entrySecret = ttk.Entry(root, width=120, textvariable=varSecret)
entrySecret.place(x=ENTRY_LEFT_X, y=APP_SECRET_Y, width=ENTRY_WIDTH, height=40)


def callback3(event=None):
    if(varSecret.get() != ''):
        pyperclip.copy(varSecret.get())
        Messagebox.show_info(title='温馨提示', message='复制成功!')


buttonCopy1 = ttk.Button(
    root, text='复制', bootstyle=(PRIMARY, "outline-toolbutton"), command=callback3)
buttonCopy1.place(x=ENTRY_LEFT_X+ENTRY_WIDTH+20,
                  y=APP_SECRET_Y, width=60, height=40)

OPENID_PREFIX = "sddf"


def create_app_id() -> str:
    """
           生成开放接口openId,使用sddf作为统一前缀
           :return: 返回值名: 返回值说明
        """
    now = datetime.datetime.now().timestamp()
    app_id = hashlib.md5(str(now).encode('utf-8'))
    return OPENID_PREFIX + app_id.hexdigest()[4:]


def create_app_key(module='', length=8) -> str:
    """
       函数说明
       :param module: 模块名称,用作生成app_key的"盐值"
       :param length: 模块名称,用作生成app_key的长度,默认8位
       :return: app_key: 业务key
    """
    source_letters = module + \
        "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    str_list = [random.choice(source_letters) for i in range(length)]
    app_key = ''.join(str_list)
    return app_key


def create_app_secret(salt: str, length=40) -> str:
    """
          函数说明
          :param salt: 模块名称,用作生成app_key的"盐值"
          :param length: 模块名称,用作生成app_key的长度,默认8位
          :return: app_secret: 密钥
       """
    source_letters = salt + "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    str_list = [random.choice(source_letters) for i in range(length)]
    app_secret = ''.join(str_list)
    return app_secret


# 生成按钮事件处理函数
def gen():
    varId.set(create_app_id())
    varKey.set(create_app_key())
    varSecret.set(create_app_secret(create_app_id()))


BUTTON_FUN_Y = 260
BUTTON_FUN_H = 30
# 创建按钮组件,同时设置按钮事件处理函数
# 参数解释:  text='生成'文本内容      activeforeground='#ff0000'按下按钮时文字颜色     command=login关联的函数
buttonOk = ttk.Button(
    root, text='生成', bootstyle=SUCCESS, command=gen)
buttonOk.place(x=270, y=BUTTON_FUN_Y, width=80, height=BUTTON_FUN_H)

# 创建保存组件,同时设置按钮事件处理函数
file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = path
options['initialfile'] = filename
options['parent'] = root
options['title'] = '请选择保存路径'


def saveToFile():
    """Returns an opened file in write mode.
    This time the dialog just returns a filename and the file is opened by your own code.
    """
    if varId.get() == '' or varKey.get() == '' or varSecret.get() == '':
        Messagebox.show_error(message='请生成密钥')
        return
    # get filename
    filename = tkFileDialog.asksaveasfilename(**file_opt)

    # open file on your own
    if filename:
        app_id = "AppId: " + varId.get()
        app_key = "AppKey: " + varKey.get()
        app_secret = "AppSecret: " + varSecret.get()
        list = [app_id, app_key, app_secret]
        with open(filename, "w", encoding="utf-8") as fw:  # 可以写入txt文件
            for i in list:
                fw.write(i + "\n")
        Messagebox.show_info(message='写入成功!')


buttonSave = ttk.Button(
    root, text='保存', bootstyle=SUCCESS, command=saveToFile)
buttonSave.place(x=420, y=BUTTON_FUN_Y, width=80, height=BUTTON_FUN_H)


# 清空按钮的事件处理函数


def clear():
    # 清空生成的数据
    varId.set('')
    varKey.set('')
    varSecret.set('')


buttonClear = ttk.Button(root, text='清空', bootstyle=SUCCESS, command=clear)
buttonClear.place(x=550, y=BUTTON_FUN_Y, width=80, height=BUTTON_FUN_H)

root.mainloop()

打包icon文件需要用到的工具类:

# 这段程序可将图标gen.ico转换成icon.py文件里的base64数据
import base64
open_icon = open("favicon.ico", "rb")  # favicon.icon为你要放入的图标
b64str = base64.b64encode(open_icon.read())  # 以base64的格式读出
open_icon.close()
write_data = "img=%s" % b64str
f = open("icon.py", "w+")  # 将上面读出的数据写入到icon.py的img数组中
f.write(write_data)
f.close()

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值