Flask中的基本HTTP认证 AttributeError: 'NoneType' 错误。

问题描述 投票:2回答:1

我在做一个Flask应用,我需要做HTTP基本认证,但它不工作。

我做的像在 例子

为了解决这个问题,我需要做什么?

导入的库

from flask import Flask, render_template, render_template_string, request
import json

带认证的代码片段

@app.route('/user/<string:name>')
def user(name):
    request.authorization.username
    request.authorization.password

    with open('json/users.json', 'rt', encoding='utf8') as f:
        x = f.read()
    data = json.loads(x)
    user = data[name]
    return render_template('about_user.html',
        _name=user['name'],
        _age=user['age'],
        _discord=user['discord']
    )

一个错误

AttributeError: 'NoneType' object has no attribute 'username'
python http flask basic-authentication
1个回答
5
投票

你需要检查是否有一个 request.authorization 先这样

  if request.authorization:
    request.authorization.username
    request.authorization.password

    with open('json/users.json', 'rt', encoding='utf8') as f:
        x = f.read()
    data = json.loads(x)
    user = data[name]
    return render_template('about_user.html',
        _name=user['name'],
        _age=user['age'],
        _discord=user['discord']
    )


    else:
       return make_response(....)

确保你导入 make_response.

© www.soinside.com 2019 - 2024. All rights reserved.