Sanic learning to step on the pit record: the first pit - sanic_jinja2 application error ModuleNotFoundError: No module named 'AppName'

I just started learning to use sanic, and I found some pitfalls, so I recorded them casually; for later generations to learn together and avoid stepping on pitfalls;

# 使用的软件版本
python        3.8.10
sanic         21.9.3
sanic-jinja2  0.10.0

The first pit: sanic_jinja2 application error

I just started to learn, followed https://blog.csdn.net/Mr_Gorgre/article/details/103242844  for testing, but it keeps reporting errors when running; ModuleNotFoundError: No module named 'MyApp'

Where 'MyApp' is app = Sanic(name='MyApp'), the name you named yourself.

(VENV) PS E:\wim\project\pyweb\asyncWeb> & e:/wim/project/pyweb/asyncWeb/VENV/Scripts/python.exe e:/wim/project/pyweb/asyncWeb/views/sanic_web.py
Traceback (most recent call last):
  File "e:/wim/project/pyweb/asyncWeb/views/sanic_web.py", line 39, in <module>
    tp = sj2(app, session=session)
  File "E:\wim\project\pyweb\asyncWeb\VENV\lib\site-packages\sanic_jinja2\__init__.py", line 95, in __init__
  File "E:\wim\project\pyweb\asyncWeb\VENV\lib\site-packages\sanic_jinja2\__init__.py", line 119, in init_app
  File "d:\python\lib\site-packages\jinja2\loaders.py", line 287, in __init__
    import_module(package_name)
  File "d:\python\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'MyApp'

According to the error prompt, locate the error point:

tp = sj2(app, session=session)

Baidu searched, but did not find a solution. The basic ones found are as follows:

# 通常是这种模式
tp = sj2(app)

# 还有这种模式
tp = sj2(app, session=session)

# 尝试之后都不行,也尝试将
app = Sanic(name='MyApp')
# 改为
app = Sanic()
# 或者改为
app = Sanic(__name__)
# 这种模式也都不行,新版本sanic要求必须添加APP名称,不然会报错

sanic.exceptions.SanicException: Sanic instance cannot be unnamed. Please use Sanic(name='your_application_name') instead.

Finally, intelligently look through the code of the library file to find a solution;

(class) SanicJinja2(app=None, loader=None, pkg_name=None, pkg_path=None, context_processors=None, session=None, **kwargs)

It was found that some parameters were missing, and the pkg_name parameter was added again, and finally it can run normally.

tp = sj2(app, app.name, session=session)

Baidu has not found this place for a long time, so I recorded it and shared it with you.

Guess you like

Origin blog.csdn.net/theorycao/article/details/121560215