gpt4 book ai didi

python - token 名称 'app' 未定义。 flask

转载 作者:行者123 更新时间:2023-12-01 01:48:11 27 4
gpt4 key购买 nike

我正在尝试使用工厂设计模式实现 flask 应用程序。由于此错误,无法运行应用程序

127.0.0.1 - - [24/Jun/2018 18:07:14] "OPTIONS /api/v1/users/register HTTP/1.1" 200 -
token name 'app' is not defined
127.0.0.1 - - [24/Jun/2018 18:07:15] "POST /api/v1/users/register HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb)
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/_compat.py", line 35, in
reraise raise value
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/jacobo/.local/share/virtualenvs/alen-yVjuFfoa/lib/python3.5/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/mnt/c/Users/Jacobo/Projects/alen/server/users/api.py", line 25, in register
'token': token.decode()
AttributeError: 'NameError' object has no attribute 'decode'

我的项目结构如下:

/ myapp
/users
api.py
models.py
app.py
database.py
extensions.py
settings.py
run.py

我认为问题是应用程序无法识别应用程序配置。但我不知道如何让它发挥作用。

app.py

from flask import Flask, render_template
from server import users
from server.extensions import bcrypt, db, migrate, cors
from server.settings import DevConfig


def create_app(config_object=DevConfig):
app = Flask(__name__,
static_folder="../frontend/public",
template_folder="../frontend/public")
app.config.from_object(config_object)
register_extensions(app)
register_blueprints(app)
return app


def register_extensions(app):
bcrypt.init_app(app)
db.init_app(app)
migrate.init_app(app, db)
cors.init_app(app)
return None


def register_blueprints(app):
app.register_blueprint(users.api.blueprint)
return None

settings.py

import os


class Config(object):

SECRET_KEY = 'p9Bv<3Eid9%$i01'
APP_DIR = os.path.abspath(os.path.dirname(__file__)) # This directory
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
BCRYPT_LOG_ROUNDS = 13
DEBUG_TB_ENABLED = False
DEBUG_TB_INTERCEPT_REDIRECTS = False
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = database


class ProdConfig(Config):
ENV = 'prod'
DEBUG = False
DEBUG_TB_ENABLED = False

class DevConfig(Config):
ENV = 'dev'
DEBUG = True
DEBUG_TB_ENABLED = True

/users/api.py

from flask import Blueprint, jsonify, request, make_response
from .models import User
from server.extensions import db
from sqlalchemy.exc import IntegrityError

blueprint = Blueprint('user', __name__, url_prefix='/api/v1/users')


@blueprint.route("/register", methods=['POST'])
def register():
data = request.get_json()
user = User.query.filter_by(email=data.get('email')).first()
if not user:
user = User(
email=data["email"],
password=data["password"]
)
db.session.add(user)
db.session.commit()
token = user.encode_auth_token(user.id)
print('token', token)
responseObject = {
'status': 'success',
'message': 'Succesfully registered.',
'token': token.decode()
}
return make_response(jsonify(responseObject)), 201

else:
responseObject = {
'status': 'fail',
'message': 'User already exists. Please log in.'
}
return make_response(jsonify(responseObject)), 202

/users/models.py

import datetime as dt
import jwt

from server.database import Column, Model, SurrogatePK
from server.database import db, reference_col, relationship
from server.extensions import bcrypt


class Role(SurrogatePK, Model):

__tablename__ = 'roles'
name = Column(db.String(80), unique=True, nullable=False)
user_id = reference_col('users', nullable=True)
user = relationship('User', backref='roles')

def __init__(self, name, **kwargs):
db.Model.__init__(self, name=name, **kwargs)

def __repr__(self):
"""Represent instance as a unique string."""
return '<Role({name})>'.format(name=self.name)


class User(SurrogatePK, Model):

__tablename__ = 'users'
email = Column(db.String(80), unique=True, nullable=False)
password = Column(db.String(255), nullable=True)
created_at = Column(db.DateTime, nullable=False,
default=dt.datetime.utcnow)
active = Column(db.Boolean(), default=False)
is_admin = Column(db.Boolean(), default=False)

def __init__(self, email, password=None, **kwargs):
db.Model.__init__(self, email=email, **kwargs)
if password:
self.set_password(password)
else:
self.password = None

def set_password(self, password):
self.password = bcrypt.generate_password_hash(password).decode()

def check_password(self, value):
return bcrypt.check_password_hash(self.password, value)

def __repr__(self):
return '<User({email!r})>'.format(email=self.email)

def encode_auth_token(self, user_id):
try:
payload = {
'exp': dt.datetime.utcnow() + dt.timedelta(days=0, seconds=5),
'iat': dt.datetime.utcnow(),
'sub': user_id
}
return jwt.encode(
payload,
app.config.get('SECRET_KEY'),
algorithm='HS256'
)
except Exception as e:
return e

@staticmethod
def decode_auth_token(auth_token):
"""
Validates the auth token
:param auth_token:
:return: integer|string
"""
try:
payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
if is_blacklisted_token:
return 'Token blacklisted. Please log in again.'
else:
return payload['sub']
except jwt.ExpiredSignatureError:
return 'Signature expired. Please log in again.'
except jwt.InvalidTokenError:
return 'Invalid token. Please log in again.'

提前致谢

最佳答案

问题很清楚,与 Flask 本身无关。

  File "/mnt/c/Users/Jacobo/Projects/alen/server/users/api.py", line 25, in register 
'token': token.decode()
AttributeError: 'NameError' object has no attribute 'decode'

对象token不是具有解码的东西(我假设它应该是字节);它是一个 NameError 对象。

如果我们追溯到 token 的来源,它来自您的 defencode_auth_token(self, user_id): 函数 – 问题是任何异常都是 < em>返回而不是被正确处理(或者更确切地说,没有处理,所以他们会引发异常):

    except Exception as e:
return e

我建议完全删除该异常处理,以便您可以找到根本原因(例如SECRET_KEY必须是字节,而不是字符串,但您会发现这一点) .

关于python - token 名称 'app' 未定义。 flask ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017310/

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