Basic HTTP Authentication in Flask AttributeError: 'NoneType' error

Basic HTTP Authentication in Flask AttributeError: 'NoneType' error

我正在做一个 Flask 应用程序,我需要进行 HTTP 基本身份验证,但它不起作用

我和 example

一样

我需要做什么才能解决这个问题?

导入的库

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'

你需要先检查是否有 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.