Python 从另一个文件导入方法时出现问题

Python 从另一个文件导入方法时出现问题,python,http,flask,Python,Http,Flask,我正在尝试从我的模型文件中使用decorator 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 这是

我正在尝试从我的模型文件中使用decorator 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
这是我的模特

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

一个更灵活的方法是使用decorator。就你而言:

from models import requires_auth

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

编辑:我忘了使用
url\u作为
。我应该这样做。

@需要认证
->
@模型。需要认证
from models import requires_auth

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