使用Flask-Login时Python中的字节和整数出现问题

时间:2019-03-31 08:21:05

标签: python flask flask-sqlalchemy flask-login

基本上,我正在尝试使用flask-login定义用户加载器,并因此必须传递用户的数据库ID。我收到某种无效的文字错误。

我尝试转换此“字节?”从整数到字符串以及各种形式,我都尝试使用UTF-8之类的几种方法对其进行解码,但仍然没有运气。

@login_manager.user_loader
def load_user(id):
    return accounts.query.get(int(str(id)))

这是控制台抛出的错误。

Traceback (most recent call last):
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\utils.py", line 259, in decorated_view
    elif not current_user.is_authenticated:
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\werkzeug\local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\werkzeug\local.py", line 307, in _get_current_object
    return self.__local()
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\utils.py", line 26, in <lambda>
    current_user = LocalProxy(lambda: _get_user())
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\utils.py", line 335, in _get_user
    current_app.login_manager._load_user()
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\login_manager.py", line 359, in _load_user
    return self.reload_user()
  File "d:\Programming\Python (Flask)\MRP UCP\env\lib\site-packages\flask_login\login_manager.py", line 321, in reload_user
    user = self.user_callback(user_id)
  File "D:\Programming\Python (Flask)\MRP UCP\app.py", line 25, in load_user
    return accounts.query.get(int(str(id)))
ValueError: invalid literal for int() with base 10: "b'5'"
127.0.0.1 - - [31/Mar/2019 09:12:10] "GET /home HTTP/1.1" 500 -

我正在使用sqlalchemyflask-sqlalchemyflask-login的最新版本。我还在脚本中使用了bcrypt和脚本中的其他几项,例如urandom作为密钥,并花了一些时间来跟踪它们。

我们将不胜感激:)

1 个答案:

答案 0 :(得分:0)

您要将字节b'5'转换为字符串"b'5'",因此您的字符串包含字母b和单引号。 int不理解这样的凌乱字符串,您只需要删除str函数即可:

return accounts.query.get(int(id))