pythonflaskflask-socketiopython-socketio

AttributeError: module 'secrets' has no attribute 'token_bytes'


I am trying to set up a simple flask/socketio application however when I try and run it I get this error:

File "C:\Users\tompi\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask\app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\tompi\AppData\Local\Programs\Python\Python39\Lib\site-packages\flask_socketio\__init__.py", line 45, in __call__
    return super(_SocketIOMiddleware, self).__call__(environ,
    return self.engineio_app.handle_request(environ, start_response)
    return self.eio.handle_request(environ, start_response)
  File "C:\Users\tompi\AppData\Local\Programs\Python\Python39\Lib\site-packages\engineio\server.py", line 379, in handle_request
    r = self._handle_connect(environ, start_response,
  File "C:\Users\tompi\AppData\Local\Programs\Python\Python39\Lib\site-packages\engineio\server.py", line 530, in _handle_connect
    sid = self.generate_id()
  File "C:\Users\tompi\AppData\Local\Programs\Python\Python39\Lib\site-packages\engineio\server.py", line 504, in generate_id
    secrets.token_bytes(12) + self.sequence_number.to_bytes(3, 'big'))
AttributeError: module 'secrets' has no attribute 'token_bytes'

and I can't figure out why. Any ideas?

Here is the code:

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)

app.config['SECRET_KEY'] = 'abc'
socketio = SocketIO(app)


@app.route('/')
def index():
    return 'hello world'
    

if __name__ == '__main__':
    socketio.run(app, debug=True)

Solution

  • Something like this happened to me while I was executing black (the code formatter), even without arguments:

    C:\GIT\myprogram>c:\Python310-64\python.exe -m black
    Traceback (most recent call last):
      File "c:\Python310-64\lib\runpy.py", line 187, in _run_module_as_main
        mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
      File "c:\Python310-64\lib\runpy.py", line 146, in _get_module_details
        return _get_module_details(pkg_main_name, error)
      File "c:\Python310-64\lib\runpy.py", line 110, in _get_module_details
        __import__(pkg_name)
      File "src\black\__init__.py", line 45, in <module>
      File "c:\Python310-64\lib\site-packages\black\files.py", line 34, in <module>
        from black.handle_ipynb_magics import jupyter_dependencies_are_installed
      File "src\black\handle_ipynb_magics.py", line 49, in <module>
    AttributeError: module 'secrets' has no attribute 'token_hex'
    

    I hade a file named secrets.py in my current directory, which triggered this issue.