need to package jinja2 template for python

后端 未结 3 956
北海茫月
北海茫月 2021-01-21 23:37

(UPDATE: I\'ve made a better question with a better answer here. I was going to delete this question, but some of the answers might prove useful to future searchers.)

M

相关标签:
3条回答
  • 2021-01-21 23:45

    I don't know the process involved with packaging but I figure since Jinja2 is written in Python, the process would be the same as packaging any other application in Python.

    Here are a few links that may be useful to you:

    • The Hitchhiker's Guide to Python (great resource): Packaging Explained
    • Alternatives to Packaging: freeze your application
    • Python Packaging User Guide (probably the most useful to you)

    I hope this helps.

    0 讨论(0)
  • 2021-01-21 23:51

    Maybe an issue is in PYTHONPATH . According to Python documantation https://docs.python.org/2.7/tutorial/modules.html#the-module-search-path it searches for modules in :

    • the directory containing the input script (or the current directory).
    • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    • the installation-dependent default.

    You can add some code to your application - printing sys.path variable to make sure your applcation's path is also there.

    import sys
    from jinja2 import Environment, PackageLoader # no prob, jinja2 correctly installed using pip
    print sys.path # printing your sys.path
    env = Environment(loader=PackageLoader('mypkg', 'template')) # causes server error
    

    If it's not You can add by

    sys.path.append(path_to_your_application) 
    
    0 讨论(0)
  • 2021-01-22 00:02

    I've discovered a WORKAROUND, here. In this usage, the template is not part of a module or package; it is loaded directly from the file system. File system:

    ./index.py
    ./template.html
    

    index.py:

    #!/usr/bin/python
    import jinja2
    
    templateLoader = jinja2.FileSystemLoader( searchpath="." )
    templateEnv = jinja2.Environment( loader=templateLoader )
    TEMPLATE_FILE = "template.html"
    template = templateEnv.get_template( TEMPLATE_FILE )
    outputText = template.render( ) # this is where to put args to the template renderer
    
    print ("Content-type: text/html\r\n\r\n")
    print(outputText)
    
    0 讨论(0)
提交回复
热议问题