J'essaie d'utiliser le décorateur requires_auth(f) à partir de mon fichier de modèles. Le journal de Docker-compose indique ce qui suit :
__import__(module)
wsgi_1 | File "/deploy/project/__init__.py", line 11, in <module>
wsgi_1 | @requires_auth
wsgi_1 | NameError: name 'requires_auth' is not defined
Je n'arrive pas à comprendre pourquoi il ne se construit pas. Pour autant que je sache, je ne fais pas d'importations circulaires qui pourraient le perturber car le reste de mon code se construit bien. Voici mon init .py
from flask import Flask, Response
app = Flask(__name__)
from flask import Flask
from flask import render_template
from flask import request, Response
import models
@app.route('/secret-page', methods=['GET'])
@requires_auth
def secret_page():
users = models.retrieveUsers()
return render_template('secret.html' , users=users, current=current)
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
phone = request.form['phone']
models.insertUser(username, password, phone)
return render_template('index.html')
else:
return render_template('index.html')
Et voici mon models.py
import sqlite3 as sql
from functools import wraps
q = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL,
phone TEXT NOT NULL
);
"""
con = sql.connect("database.db")
cur = con.cursor()
cur.execute(q)
# original code from https://gist.github.com/PolBaladas/07bfcdefb5c1c57cdeb5
def insertUser(username, password, phone):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("INSERT INTO users (username,password,phone) VALUES (?,?,?)", (username,password,phone))
con.commit()
con.close()
def retrieveUsers():
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("SELECT username, password, phone FROM users")
users = cur.fetchall()
con.close()
return users
def retrieveUser(username):
con = sql.connect("database.db")
cur = con.cursor()
cur.execute("SELECT username, password FROM users WHERE username = (?)", [username])
user = cur.fetchone()
con.close()
return user
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'password'
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated