Python 使用Window&;中tkinter前端应用程序中扩展的Flask jwt保存Flask REST API生成的承载令牌的最佳方法是什么;其他
我尝试了制作一个非常基本的FlaskRESTAPI,它在登录时向客户端返回访问令牌和刷新令牌。我用tkinter做前端Python 使用Window&;中tkinter前端应用程序中扩展的Flask jwt保存Flask REST API生成的承载令牌的最佳方法是什么;其他,python,json,flask,tkinter,flask-jwt-extended,Python,Json,Flask,Tkinter,Flask Jwt Extended,我尝试了制作一个非常基本的FlaskRESTAPI,它在登录时向客户端返回访问令牌和刷新令牌。我用tkinter做前端 import requests as re from functools import wraps import time import json import tkinter as tk import os BASE_URL = "http://127.0.0.1:5000/api" auth_data = { "access_tok
import requests as re
from functools import wraps
import time
import json
import tkinter as tk
import os
BASE_URL = "http://127.0.0.1:5000/api"
auth_data = {
"access_token": None,
"access_token_exp": None,
'refresh_token': None,
'refresh_token_exp': None
}
def get_dir(filename:str = None)-> str:
_curent_dir = os.path.dirname(__file__)
_path = os.path.join(_curent_dir, filename)
return _path
def get_new_token():
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
global access_token
response = fn(*args, **kwargs)
if response.status_code == 200:
data = response.json()
if data.get("status") == 401:
print("REFRESHING THE ACCESS TOKEN...")
token_response = re.post(
url = f"{BASE_URL}/refresh_token",
headers = {"Authorization": f"Bearer {auth_data.get('refresh_token')}"}
)
if token_response.status_code == 200:
try:
jsonize = token_response.json()
if jsonize.get("status") == 401:
print("refresh Token has been expired and need to login again.")
return False
elif jsonize.get("status") == 199:
print("Error Occured. maybe server is unable to make connection to the database, try again")
auth_data["access_token"] = jsonize["access_token"]
with open(get_dir("auth.json"), "w") as auth:
auth.write(json.dumps(auth_data, indent=4, sort_keys=False))
print('REFRESHED ACCESS TOKEN')
response = fn(*args, **kwargs)
data = response.json()
if data.get("status") == 401:
print("USER LOGGED OUT")
raise Exception
except Exception as e:
print("Exception occured", e)
return False
else:
return False
return response
else:
return False
return decorator
return wrapper
@get_new_token()
def get_profile_data(page = "all"):
global access_token
response = re.get(
url = f"{BASE_URL}/user/profile/{page}",
data = {
"user":"annup76779",
"password":"76779"
},
headers = {
"content-type":"application/json",
"Authorization": f"Bearer {auth_data.get('access_token')}",
"accept": "application/json"
}
)
return response
def main(page):
r = get_profile_data(page)
if not r:
print(r)
else:
print(r.json())
app = tk.Tk()
def user_login():
global auth_data
response = re.post(
url = f"{BASE_URL}/login",
data = {
"user":"username",
"password":"password"
}
)
if response.status_code == 200:
r_json = response.json()
if r_json.get("status") == 1:
auth_data = r_json
with open(get_dir("auth.json"), "w") as auth:
print("saving token to auth.json...")
auth.write(json.dumps(auth_data, indent=4, sort_keys=False))
print("token saved to auth.json...")
print("redirecting to user_profile_access_page...")
get_user_profile()
else:
print(r_json.get("msg"))
else:
print("Messed up!")
def get_user_profile():
global auth_data
global app
app.geometry("200x300")
if auth_data.get("access_token") is not None:
button_all = tk.Button(app, text = "ALL DETAILS", command = lambda : main("all"))
button_profile = tk.Button(app, text = "PROFILE DETAILS", command = lambda : main("profile"))
button_personal = tk.Button(app, text = "PERSONAL DETAILS", command = lambda : main("personal"))
button_additional = tk.Button(app, text = "ADDITIONAL DETAILS", command = lambda : main("additional"))
button_all.pack()
button_profile.pack()
button_personal.pack()
button_additional.pack()
else:
user_login_win()
def user_login_win():
global auth_data
global app
l1 = tk.Label(app, text = "Loggin into the app...",fg = "green", font = ("Arial", 15, "bold"), justify="left")
l1.pack()
b1 = tk.Button(app, text = "Login", command = user_login)
b1.pack()
app.geometry("300x70")
def create_app():
global app
global auth_data
print("starting app...")
try:
with open(get_dir("auth.json"), "r") as auth:
auth_data = json.load(auth)
if auth_data.get('refresh_token') is not None:
get_user_profile()
else:
user_login_win()
except IOError:
print("auth file not found!")
print("Making auth.json ...")
with open(get_dir("auth.json"), "w") as auth:
print("auth.json created successfully.")
print('writing to auth.json...')
auth.write(json.dumps(auth_data, indent=4, sort_keys=False))
print('writing to auth.json completed successfully.')
print("closing auth.json...")
print("auth.json closed.")
user_login_win()
app.mainloop()
create_app()
在此代码段中,前端Tkinter代码从第89行开始。
我将访问令牌和刷新令牌及其过期时间简单地保存在auth.json文件中
但我想知道的是,在本地系统上保存这些令牌的最佳位置是什么,以及当有人启动这些令牌时,在应用程序中检索这些令牌的最佳方式是什么。
下面是保存在json文件中的令牌片段
提前谢谢 为什么不查看一下
钥匙圈
软件包呢?请重复并从。“给我最好的设计”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后就您的算法或技术提出具体问题。堆栈溢出不是为了替换现有的文档和教程。
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyMzE0NjExNCwianRpIjoiNzU4YzY5MjctNWQ4OS00OWQwLTkzYzgtYTEzOWEwYTA3MDAxIiwibmJmIjoxNjIzMTQ2MTE0LCJ0eXBlIjoiYWNjZXNzIiwic3ViIjoxLCJleHAiOjE2MjMxNDcwMTQsInJlZnJlc2hfanRpIjoiN2ZkMzVkZDAtZGMwZS00YmJlLWFlYTMtM2I0NWU0NWMxNTA2In0.kfdskw88NL9YoteSrYoa8EJX5gHhBPGHIop5V4PAABk",
"access_token_expires": 10.0,
"refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyMzAwNTM3OCwianRpIjoiN2ZkMzVkZDAtZGMwZS00YmJlLWFlYTMtM2I0NWU0NWMxNTA2IiwibmJmIjoxNjIzMDA1Mzc4LCJ0eXBlIjoicmVmcmVzaCIsInN1YiI6MSwiZXhwIjoxNjI1NTk3Mzc4fQ.srrBctVvJNQywI9EI1d6ndmrorI_pdPzcdlpBa3HBbQ",
"refresh_token_expires": 2592000.0,
"status": 1
}