Search code examples
pythonhttpflaskbasic-authentication

Basic HTTP Authentication in Flask AttributeError: 'NoneType' error


I'm doing a Flask app and I need to do HTTP Basic Authentication and it doesn't work

I'm doing like in example

What do I need to do in order to fix this problem?

Imported libraries

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

Code fragment with auth

@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']
    )

An error

AttributeError: 'NoneType' object has no attribute 'username'

Solution

  • You need to check if there is a request.authorization first so

      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 sure you import make_response.