问题从另一个文件导入方法

时间:2017-03-14 00:37:59

标签: python http flask

我正在尝试使用我的模型文件中的装饰器requires_auth(f)。 Docker-compose日志声明如下:

   __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

我似乎无法弄清楚为什么这不会建立。我可以告诉我,我没有做任何循环导入,因为我的其余代码构建正常,所以会搞乱它。这是我的 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')

这是我的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

1 个答案:

答案 0 :(得分:1)

更多Flasky方法是使用before_request装饰器。在你的情况下:

from models import requires_auth

@app.before_request
def before():
    if request.path == url_for('secret-page'):
        requires_auth()

编辑:我忘了使用url_for。我应该know better