Django,在获取令牌后,在页面打开后运行代码/重新呈现

2024-06-30 15:49:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Django中构建一个应用程序,该应用程序使用一个表单,该表单需要从API中收集一些数据。使用该API进行身份验证的令牌是通过使用登录流收集的。但是,当令牌过期时,Django拒绝运行,因此无法通过重新身份验证刷新令牌

是一种在登录后从表单运行代码的方法,这样Django就不会在启动时尝试运行它。或在打开/刷新页面时重新呈现表单

但是,此表单需要来自该API的一些数据。要访问这个API,我需要使用一个令牌,这个令牌是通过进入应用程序开头的登录流获得的,然后登录流将令牌存储在应用程序中使用。但是,当令牌过期时,Django将不会启动。因此,要实现登录流以获取新令牌是不可能的

我正在使用Microsoft graph API并请求AzureAD提供数据

我已尝试将表单的部分放置在Try中:除了:

这是可行的,但是它不会在刷新或重新打开包含表单的页面时重新加载正确的信息

表格:

    sign_in()
    infile = open('token.pickle', 'rb')
    token = pickle.load(infile)
    infile.close()
    depDict = get_deps(token)
    depDict = [(v, k) for k, v in depDict.items()]
except:
    pass



class userCreationForm(forms.Form):
    firstName = forms.CharField(label='First name', max_length=100, widget=forms.TextInput(attrs={'class': 'form-controll', 'type': 'text', 'placeholder': 'First Name'}))
    lastName = forms.CharField(label='Last name', max_length=100, widget=forms.TextInput(attrs={'class': 'form-controll', 'type': 'text', 'placeholder': 'Last Name'}))
    email = forms.EmailField(label='email', max_length=100, widget=forms.EmailInput(attrs={'class': 'form-controll','type': 'email', 'placeholder': 'Email adress'}))
    try:
        department = forms.CharField(label='department', widget=forms.Select(choices=depDict, attrs={'class': 'form-controll'}))
    except:
        department =forms.CharField(label='department', widget=forms.Select(choices=[('DEP-Everyone','DEP-Everyone')], attrs={'class': 'form-controll'}))

观点:

    user_create_form = userCreationForm
    if request.method == 'POST':
        form = user_create_form(request.POST)

        if form.is_valid():
            messages.info(request, 'User will be created')
            form = user_create_form()
            # first_name = user_create_form.firstName
            # last_name = user_create_form.lastName
            # UPN = user_create_form.email
            # password = "test123!"



    else:
        form = userCreationForm()

    return render(request, 'user_creation_page.html', {'form': form})

Tags: djangoformapi应用程序表单createformswidget