gpt4 book ai didi

python-3.x - 未在Python Flask的装饰器中定义名称“字符串”

转载 作者:行者123 更新时间:2023-12-03 16:58:02 32 4
gpt4 key购买 nike

我是Flask编程的初学者,我有这段代码,我想将标题标记与装饰器函数中名为key的字符串进行比较。
这是代码:

def require_appkey(view_function):
@wraps(view_function)

def decorated_function(*args, **kwargs):
try:
if request.headers.get('auth') and request.headers.get('auth') == key:
return view_function(*args, **kwargs)
else:
return {'status' : 'success', 'message' : 'auth failed'}
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
return decorated_function


要在上面的装饰器上为键分配一个值,这是我的示例代码。

class AuthenticateUser(Resource):
def post(self):
try:
global key
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type=str)
parser.add_argument('password', type=str)
args = parser.parse_args()

_user = args['username']
_userPassword = args['password']

m = hashlib.md5(_userPassword.encode())
conn = psycopg2.connect(database='salestracking', user='postgres', password='postgres')
cursor = conn.cursor()
cursor.execute('SELECT count(*) FROM tbl_user WHERE username = %s AND password = %s', (_user,m.hexdigest(), ))


data = [dict(((cursor.description[i][0]), value)
for i, value in enumerate(row)) for row in cursor.fetchall()]

x = data[0]['count']

if(x == 1):
cursor = conn.cursor()
cursor.execute('SELECT userID, userlevel, employeeID, username FROM tbl_user WHERE username = %s AND password = %s;', (_user, m.hexdigest(), ))
data = [dict(((cursor.description[i][0]), value)
for i, value in enumerate(row)) for row in cursor.fetchall()]



create_access = create_access_token(args['username'])
data[0]['access_token'] = create_access
data[0]['status'] = 'success'
data[0]['message'] = 'success'

key = data[0]['access_token']

print(key)
cursor.close()

return data[0]


else:
cursor.close()
return {'status' : 'success', 'message' : 'failed'}


except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()


但是当我运行它

class CreateUser(Resource):
@require_appkey
def post(self):


错误返回,提示“未定义名称'key'”。请帮助我修复它。

最佳答案

您必须在调用修饰的AuthenticateUser.post()之前先调用CreateUser.post(),以便在修饰的函数调用时定义key

考虑以下代码示例:

from functools import wraps

def my_dec(f):
@wraps(f)
def wrapper(*args, **kwargs):
print(key)
return f(*args, **kwargs)
return wrapper

class AuthenticateUser(object):
def post(self):
global key
key = 'foo'

class CreateUser(object):
@my_dec
def post(self):
pass


输出:

In [1]: from app import AuthenticateUser, CreateUser
In [2]: CreateUser().post()
---------------------------------------------------------------------------
Traceback (most recent call last) <ipython-input-2-78b387fcad49> in <module>()
----> 1 CreateUser().post()

/home/user/projects/so/app.py in wrapper(*args, **kwargs)
5 @wraps(f)
6 def wrapper(*args, **kwargs):
----> 7 print(key)
8 return f(*args, **kwargs)
9 return wrapper
NameError: global name 'key' is not defined

In [3]: AuthenticateUser().post()
In [4]: CreateUser().post()
foo

关于python-3.x - 未在Python Flask的装饰器中定义名称“字符串”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51037176/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com