这是我得到错误的代码,.Same操作是用SQLAlchemy实现的,但是WHen,我是用mysql写的,然后我得到了错误。
import pymysql
from functools import wraps
import jwt
import uuid
import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request
app.config['SECRET_KEY']='confidential'
def token_required(f):
@wraps(f)
def decorated(*args,**kwargs):
token= None
if 'x-acess-token' in request.headers:
token=request.headers['x-acess-token']
if not token:
return jsonify("token not found")
try:
data=jwt.decode(token,app.config['SECRET_KEY'])
conn=mysql.connect()
cursor=conn.cursor(pymysql.cursors.DictCursor)
cursor.execute('select * from hireme_emp where id=%s',data['id'])
current_user=cursor.fetchone()
except:
return jsonify('invalid token')
finally:
cursor.close()
conn.close()
return f(current_user,*args,**kwargs)
return decorated
#-----------------------------------------------
app.route('/api/view/addmin')
@token_required
def view_addmin(current_user):
try:
conn=mysql.connect()
cursor=conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT * FROM hireme_emp WHERE admin=1")
rows=cursor.fetchall()
resp=jsonify(rows)
resp.status_code=200
return resp
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()这是代码,当我在没有令牌的情况下运行这个端点时,它给出了"token not found“消息,但当我发送令牌时,它显示了这个错误,即
ERROR :line 30, in decorated
cursor.close()
UnboundLocalError: local variable 'cursor' referenced before assignment
127.0.0.1 - - [23/Jul/2021 01:08:53] "GET /api/view/addmin HTTP/1.1" 500 -. 实际上,下面的代码使用SQLAlchemy执行相同的工作,并且正在运行.I我只是试图使用纯mysql重写这段代码,但我不明白我哪里错了。提前感谢你的帮助
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
if not token:
return jsonify({'message' : 'Token is missing!'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
current_user = User.query.filter_by(public_id=data['public_id']).first()
except:
return jsonify({'message' : 'Token is invalid!'}), 401
return f(current_user, *args, **kwargs)
return decorated发布于 2021-07-23 04:47:52
在开始try catch之前定义conn和cursor
此外,您的工作代码显示您使用的是public_id而不是id
我还将代码cursor.execute更改为元组
def token_required(f):
@wraps(f)
def decorated(*args,**kwargs):
token= None
if 'x-acess-token' in request.headers:
token=request.headers['x-acess-token']
if not token:
return jsonify("token not found")
conn=mysql.connect()
cursor=conn.cursor(pymysql.cursors.DictCursor)
try:
data=jwt.decode(token,app.config['SECRET_KEY'])
cursor.execute('select * from hireme_emp where id=%s LIMIT 1',(data['public_id'],))
current_user=cursor.fetchone()
except:
return jsonify('invalid token')
finally:
cursor.close()
conn.close()
return f(current_user,*args,**kwargs)
return decoratedhttps://stackoverflow.com/questions/68490955
复制相似问题