How to use 'Blueprint' and 'Jinja2' together?

When I want to use “Blueprint” and “Jinja2” together, how do I import it in the “app1.py” file and use the “jinja” created in “server.py”?

  • Below is my file path
    image

  • server.py

# sever.py

from sanic import Sanic

from sanic_session import Session, InMemorySessionInterface
from sanic_jinja2 import SanicJinja2

app = Sanic('server')

session = Session(app, interface=InMemorySessionInterface())

jinja = SanicJinja2(app, session=session)

from apps.app1.app1 import app1
app.blueprint(app1)

if __name__ == '__main__':
    app.run()

  • app1.py
# app1.py

from sanic import Blueprint

app1 = Blueprint('app1', url_prefix='/app1')

  • In addition, when I run “server.py”, I will receive the following error
G:\Python\python.exe C:/Users/hoshi/Desktop/site/server.py
Traceback (most recent call last):
  File "C:\Users\hoshi\Desktop\site\server.py", line 12, in <module>
    jinja = SanicJinja2(app, session=session)
  File "G:\Python\lib\site-packages\sanic_jinja2\__init__.py", line 95, in __init__
    self.init_app(app, loader, pkg_name or app.name, pkg_path)
  File "G:\Python\lib\site-packages\sanic_jinja2\__init__.py", line 119, in init_app
    loader = PackageLoader(
  File "G:\Python\lib\site-packages\jinja2\loaders.py", line 285, in __init__
    import_module(package_name)
  File "G:\Python\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 855, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\hoshi\Desktop\site\server.py", line 8, in <module>
    app = Sanic('server')
  File "G:\Python\lib\site-packages\sanic\app.py", line 190, in __init__
    self.__class__.register_app(self)
  File "G:\Python\lib\site-packages\sanic\app.py", line 1308, in register_app
    raise SanicException(f'Sanic app name "{name}" already in use.')
sanic.exceptions.SanicException: Sanic app name "server" already in use.

Yes, it happened to me today too

Sorry for the delay on this. I was on vacation for a few days and missed it.

Are you importing server.py somewhere?

If you need access to your app instance somewhere, you can get it from the request object (if it is available), or using this:

from sanic import Sanic

app = Sanic.get_app()

This will only work though if your application has already been created.