aiohttp-jinja2-1.2.0/0000775000372000037200000000000013553343761015211 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/MANIFEST.in0000664000372000037200000000033413553343716016747 0ustar travistravis00000000000000include CHANGES.txt include LICENSE include README.rst include Makefile include requirements-dev.txt include pytest.ini include .coveragerc graft aiohttp_jinja2 graft docs graft examples graft tests global-exclude *.pyc aiohttp-jinja2-1.2.0/docs/0000775000372000037200000000000013553343761016141 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/docs/api.rst0000664000372000037200000001215313553343716017446 0ustar travistravis00000000000000API === Describes the module API with detailed explanations of functions parameters. .. module:: aiohttp_jinja2 .. highlight:: python .. function:: setup(app, *args, app_key=APP_KEY, context_processors=(), \ filters=None, default_helpers=True, **kwargs) Function responsible for initializing templating system on application. It must be called before freezing or running the application in order to use *aiohttp-jinja*. :param app: :class:`aiohttp.web.Application` instance to initialize template system on. :param str app_key: optional key that will be used to access templating environment from application dictionary object. Defaults to `aiohttp_jinja2_environment`. :param context_processors: list of :ref:`aiohttp-web-middlewares`. These are context processors used to rewrite or inject some variables during the processing of a request. :type context_processors: :class:`list` :param filters: extra jinja filters (`link to docs `). :type filters: :class:`list` :param bool default_helpers: whether to use default global helper in templates provided by package :mod:`aiohttp_jinja2.helpers` or not. :param ``*args``: positional arguments passed into environment constructor. :param ``**kwargs``: any arbitrary keyword arguments you want to pass to :class:`jinja2.Environment` environment. .. function:: get_env(app, *, app_key) Get aiohttp-jinja2 environment from an application instance by key. :param app: :class:`aiohttp.web.Application` instance to get variables from. :param str app_key: optional key that will be used to access templating environment from application dictionary object. Defaults to `aiohttp_jinja2_environment`. .. function:: template(template_name, *, app_key, encoding, status) Behaves as a decorator around view functions accepting template name that should be used to render the response. Supports both synchronous and asynchronous functions. :param str template_name: name of the template file that will be looked up by the loader. Raises a 500 error in case template was not found. :param str app_key: optional key that will be used to access templating environment from application dictionary object. Defaults to `aiohttp_jinja2_environment`. :param str encoding: encoding that will be set as a charset property on the response for rendered template, default to utf-8. :params int status: http status code that will be set on resulting response. Example of usage ^^^^^^^^^^^^^^^^ Simple initialization:: import jinja2 import aiohttp_jinja2 from aiohttp import web app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.FileSystemLoader('/path/to/templates/folder'), ) .. function:: render_string(template_name, request, context, *, \ app_key=APP_KEY) Renders template specified and returns resulting string. :param str template_name: Name of the template you want to render. Usually it's a filename without extension on your filesystem. :param request: aiohttp request associated with an application where aiohttp-jinja rendering is configured. :type request: :class:`aiohttp.web.Request` :param dict context: dictionary used as context when rendering the template. :param str app_key: optional key that will be used to access templating environment from application dictionary object. Defaults to `aiohttp_jinja2_environment`. .. function:: render_template(template_name, request, context, *, \ app_key=APP_KEY, encoding='utf-8', status=200) :param str template_name: Name of the template you want to render. :param request: aiohttp request associated with an application where aiohttp-jinja rendering is configured. :type request: :class:`aiohttp.web.Request` :param dict context: dictionary used as context when rendering the template. :param str app_key: optional key that will be used to access templating environment from application dictionary object. Defaults to `aiohttp_jinja2_environment`. :param int status: http status code that will be set on resulting response. Example of usage ^^^^^^^^^^^^^^^^ Assuming the initialization from the example above has been done:: async def handler(request): context = {'foo': 'bar'} response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context) return response app.router.add_get('/tmpl', handler) aiohttp-jinja2-1.2.0/docs/aiohttp-icon.ico0000664000372000037200000000627613553343716021246 0ustar travistravis00000000000000  ( @팋ttt椤lllhhhhhh`r|qOtPakl񋋋kkklllllllllkjjlmnp[T9]t9l:s?]q8IRtZdltuvkkklllRbl5Xmf46HKj~bq|NgyOlBG4]vJ6U]hoa?c}IeyV\z}IlG?e~7|VEd{PizCfSe:^vL{Hj4hA^pqrslqtGbvJdwXkzWkznuz}}}b9@dzGiBd}Ni}Oj~Qj|OhzDcxAavFbtTse=5p4Yq3rW/>oJf{Wiݐz;3CCOlTMaa[rpcsCllbGQSc\W=9l?`z2pHDAK[Rd扔zZZlSQfGEckqnru=]vA_xBayDc{He|If~HgIg~Ig~Gf}Vl}cq{x|`ayPQyUV}\CNHg-=]g5@azGcyIcw7k>s@m?d}EgDf}KfyjrxffyNNyMMxLLwMMuquvRer9c=-4Dc0o:IbwRMOJBd|Ff|DkjjlJJuLLwII{IIcx=lCc|>b{\sHau<\u>^w@^wA_wB`xB_xA^wVgv^ktgounstjpsbjpNao[r:[r;[q:Yp6Vp6TnAYmU`jlllkkk첲;=.*?cH<;2t/g3Zy8Vn3TlO^illljjjllllllwww59VtUOF97,KGߎjjjlllllllllD8<6-4dT0HHKylll]E#76,^kդpaiohttp-jinja2-1.2.0/docs/Makefile0000664000372000037200000001521213553343716017602 0ustar travistravis00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aiohttp_jinja2.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aiohttp_jinja2.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/aiohttp_jinja2" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aiohttp_jinja2" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." aiohttp-jinja2-1.2.0/docs/conf.py0000664000372000037200000002410213553343716017437 0ustar travistravis00000000000000# -*- coding: utf-8 -*- # # aiohttp_jinja2 documentation build configuration file, created by # sphinx-quickstart on Sun Mar 22 12:04:15 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import codecs import re def _get_version_info(): PATH_TO_INIT_PY = \ os.path.join( os.path.dirname(__file__), '..', 'aiohttp_jinja2', '__init__.py' ) with codecs.open(PATH_TO_INIT_PY, 'r', 'latin1') as fp: try: for line in fp.readlines(): if line: line = line.strip() version = \ re.search( r"^__version__ = '" r"(?P\d+)" r"\.(?P\d+)" r"\.(?P\d+)" r"(?P.*)?'$", line, re.M ) if version: return version.groupdict() except IndexError: raise RuntimeError('Unable to determine version.') _version_info = _get_version_info() # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) import alabaster # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.3' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.intersphinx', 'sphinx.ext.viewcode', 'alabaster', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'aiohttp_jinja2' copyright = '2015-2018 Andrew Svetlov and aio-libs team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '{major}.{minor}'.format(**_version_info) # The full version, including alpha/beta/rc tags. release = '{major}.{minor}.{patch}-{tag}'.format(**_version_info) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'logo': 'aiohttp-icon-128x128.png', 'description': 'jinja2 template renderer for aiohttp.web', 'github_user': 'aio-libs', 'github_repo': 'aiohttp_jinja2', 'github_button': True, 'github_banner': True, 'travis_button': 'aio-libs/aiohttp-jinja2', 'pre_bg': '#FFF6E5', 'note_bg': '#E5ECD1', 'note_border': '#BFCF8C', 'body_text': '#482C0A', 'sidebar_text': '#49443E', 'sidebar_header': '#4B4032', } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [alabaster.get_path()] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. html_favicon = 'aiohttp-icon.ico' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. html_sidebars = { '**': [ 'about.html', 'navigation.html', 'searchbox.html', ] } # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'aiohttp_jinja2doc' # -- Options for LaTeX output --------------------------------------------- # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', latex_elements = { } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'aiohttp_jinja2.tex', 'aiohttp\\_jinja2 Documentation', 'Andrew Svetlov', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'aiohttp_jinja2', 'aiohttp_jinja2 Documentation', ['Andrew Svetlov'], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'aiohttp_jinja2', 'aiohttp_jinja2 Documentation', 'Andrew Svetlov', 'aiohttp_jinja2', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/3': None, 'https://aiohttp.readthedocs.io/en/stable': None, 'http://jinja2.pocoo.org/docs/dev': None} aiohttp-jinja2-1.2.0/docs/index.rst0000664000372000037200000002437213553343716020012 0ustar travistravis00000000000000.. aiohttp_jinja2 documentation master file, created by sphinx-quickstart on Sun Mar 22 12:04:15 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. aiohttp_jinja2 ============== .. module:: aiohttp_jinja2 .. currentmodule:: aiohttp_jinja2 .. highlight:: python :term:`jinja2` template renderer for :ref:`aiohttp.web`. Usage ----- Before template rendering you have to setup *jinja2 environment* (:class:`jinja2.Environment`) first:: app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder')) After that you may use template engine in your :term:`web-handlers`. The most convenient way is to decorate a :term:`web-handler`. Using the function based web handlers:: @aiohttp_jinja2.template('tmpl.jinja2') def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} Or the class-based views (:class:`aiohttp.web.View`):: class Handler(web.View): @aiohttp_jinja2.template('tmpl.jinja2') async def get(self): return {'name': 'Andrew', 'surname': 'Svetlov'} On handler call the :func:`template` decorator will pass returned dictionary ``{'name': 'Andrew', 'surname': 'Svetlov'}`` into template named ``"tmpl.jinja2"`` for getting resulting HTML text. More complex template processing can be achieved by modifying the existing `list of global functions `_. Modification of Jinja2's environment can be done via :func:`get_env`. For example, adding the ``zip`` function:: env = aiohttp_jinja2.get_env(app) env.globals.update(zip=zip) Which can now to be used in any template:: {% for value, square in zip(values, squares) %}

The square of {{ value }} is {{ square }}.

{% endfor %} In some cases, finer control over the dataflow may also be required. This can be worked out by explicitly asking for template to be rendered using :func:`render_template`. Explicit rendering will allow to possibly pass some context to the renderer and also to modify its response on the fly. This can for example be used to set response headers:: async def handler(request): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context) response.headers['Content-Language'] = 'ru' return response This, again, can also be done with a class-based view (:class:`aiohttp.web.View`):: class Handler(web.View): async def get(self): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', self.request, context) response.headers['Content-Language'] = 'ru' return response Context processors is a way to add some variables to each template context. It works like :attr:`jinja2.Environment().globals`, but calculate variables each request. So if you need to add global constants it will be better to use :attr:`jinja2.Environment().globals` directly. But if you variables depends of request (e.g. current user) you have to use context processors. Context processors is following last-win strategy. Therefore a context processor could rewrite variables delivered with previous one. In order to use context processors create required processors:: async def foo_processor(request): return {'foo': 'bar'} And pass them into :func:`setup`:: aiohttp_jinja2.setup( app, context_processors=[foo_processor, aiohttp_jinja2.request_processor], loader=loader) As you can see, there is a built-in :func:`request_processor`, which adds current :class:`aiohttp.web.Request` into context of templates under ``'request'`` name. Here is an example of how to add current user dependant logic to template (requires ``aiohttp_security`` library):: from aiohttp_security import authorized_userid async def current_user_ctx_processor(request): userid = await authorized_userid(request) is_anonymous = not bool(userid) return {'current_user': {'is_anonymous': is_anonymous}} Template::
{% if current_user.is_anonymous %} Login {% else %} Logout {% endif %}
Default Globals ............... .. highlight:: html+jinja ``app`` is always made in templates via :attr:`jinja2.Environment().globals`::

Welcome to {{ app['name'] }}

Two more helpers are also enabled by default: ``url`` and ``static``. ``url`` can be used with just a view name:: Index Page Or with arguments:: User Page A query can be added to the url with the special ``query_`` keyword argument:: User Page For a view defined by ``app.router.add_get('/user-profile/{id}/', user, name='user')``, the above would give:: User Page This is useful as it would allow your static path to switch in deployment or testing with just one line. The ``static`` function has similar usage, except it requires you to set ``static_root_url`` on the app .. code-block:: ruby app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder')) app['static_root_url'] = '/static' Then in the template:: Would result in:: Both ``url`` and ``static`` can be disabled by passing ``default_helpers=False`` to ``aiohttp_jinja2.setup``. Library Installation -------------------- The :mod:`aiohttp_jinja2` can be installed by pip:: $ pip3 install aiohttp_jinja2 Source code ----------- The project is hosted on `GitHub `_. Please feel free to file an issue on `bug tracker `_ if you have found a bug or have some suggestion for library improvement. The library uses `Travis `_ for Continuous Integration. IRC channel ----------- You can discuss the library on Freenode_ at **#aio-libs** channel. .. _Freenode: http://freenode.net .. _aiohttp_jinja2-reference: Reference --------- .. data:: APP_KEY The key name in :class:`aiohttp.web.Application` dictionary, ``'aiohttp_jinja2_environment'`` for storing :term:`jinja2` environment object (:class:`jinja2.Environment`). Usually you don't need to operate with *application* manually, left it to :mod:`aiohttp_jinja2` functions. .. function:: get_env(app, app_key=APP_KEY) Return :class:`jinja2.Environment` object which has stored in the *app* (:class:`aiohttp.web.Application` instance). *app_key* is an optional key for application dict, :const:`APP_KEY` by default. .. function:: render_string(template_name, request, context, *, \ app_key=APP_KEY) Return :class:`str` which contains template *template_name* filled with *context*. *request* is a parameter from :term:`web-handler`, :class:`aiohttp.web.Request` instance. *app_key* is an optional key for application dict, :const:`APP_KEY` by default. .. function:: render_template(template_name, request, context, *, \ app_key=APP_KEY, encoding='utf-8', status=200) Return :class:`aiohttp.web.Response` which contains template *template_name* filled with *context*. *request* is a parameter from :term:`web-handler`, :class:`aiohttp.web.Request` instance. *app_key* is an optional key for application dict, :const:`APP_KEY` by default. *encoding* is response encoding, ``'utf-8'`` by default. Returned response has *Content-Type* header set to ``'text/html'``. .. function:: setup(app, *args, app_key=APP_KEY, autoescape=True, \ context_processors=(), filters=None, \ deault_helpers=True, **kwargs) Initialize :class:`jinja2.Environment` object. *app* is :class:`aiohttp.web.Application` instance. *args* and *kawargs* are passed into environment constructor. *app_key* is an optional key for application dict, :const:`APP_KEY` by default. *autoescape* is passed to :class:`jinja2.Environemnt`, see `Autoescaping` for more details. *context_processors* is a collection of context processors to be called before rendering a template. *filters* is a collection of custom filters, see :ref:`writing-filters` for details. *default_helpers* is a boolean flag, ``static_url`` and ``url`` jinja2 functions are added to environment if ``True`` (default). .. decorator:: template(template_name, *, app_key=APP_KEY, encoding='utf-8',\ status=200) Decorate :term:`web-handler` to convert returned :class:`dict` context into :class:`aiohtttp.web.Response` filled with *template_name* template. *app_key* is an optional key for application dict, :const:`APP_KEY` by default. *encoding* is response encoding, ``'utf-8'`` by default. *status* is *HTTP status code* for returned response, *200* (OK) by default. Returned response has *Content-Type* header set to ``'text/html'``. License ------- :mod:`aiohttp_jinja2` is offered under the Apache 2 license. Glossary -------- .. if you add new entries, keep the alphabetical sorting! .. glossary:: jinja2 A modern and designer-friendly templating language for Python. See http://jinja.pocoo.org/ web-handler An endpoint that returns http response. Contents -------- .. toctree:: :maxdepth: 2 api Indices and tables ------------------ * :ref:`genindex` * :ref:`search` aiohttp-jinja2-1.2.0/docs/_static/0000775000372000037200000000000013553343761017567 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/docs/_static/aiohttp-icon-128x128.png0000664000372000037200000005131513553343716023633 0ustar travistravis00000000000000PNG  IHDRL\gAMA a cHRMz&u0`:pQ<bKGD pHYs  tIME%}QIDATxeٕ[k3CYCJURju=!6Ag>D`C@؀inm5-%UI<{Ň}yTULp"f=g[k_kVm"z,;P9x=ɀbſ,~N@CpyËE*^"c9w%?.=9ޫjZ̆Ykgp_$9眈EQEu];wb9/At8O'ZЈ|x~"8OKwuJ}Vql-L6&̧DUUu]jEAğҗe霳&I'/'nzFnƻ2XcH  gpLL ۶]7I˲[k@4?99yÇ]r1 0Ӹg(pmIv"E}ԿmG:@Cqř^-Nᚸs:U:+(0*hTg$22-x^5YoD6>X?,{Ç777[S0{」~ڵh_`0Xc}v#b kܑp}F|1?W~\D?;vI?%KnѶaVHKLJ+ ϔLSn g!+~'^Z9)NeEY־u5" GkP AB ("Cu~XDK7sixGYSj666VVVvww3L?~i$nw{{8876^7$ ~}`*ԳP*tz\QZzrǿm몪B%}VVd:%EEӄqJ(JAk)i:P8i^8_$J{`A766^oeen ʡ5q~tbKFgob1$ 4qD!^O[6aO}E wN~@J J-JCiAfia# QDs Kl&;&nl^ @t:^oiiiccիQg(TOp†p8 2TvLqPe!Bp @U)Ջ8ԁ"t6ήI'lADyqsUj}Z遈@5'@UgoWq$( =60ݳZһW3Բ1&MvvR$ό߿[ť|C8Gf'*eSiGКT@̠̅Ɍy2)k?"&Wj D'{s"Hl"ɺ\U  6B  TEEw=]qVs6cfiP۷o|yy .ߥ@7|뭷?~\Ex E/ďw싙4N?6i5hlyN}"HMEk(Ͼd@IL ՈD2T5?Dq6Xc5p\u>14?Af UMM(0*@95۶ wyWX'=zo;eY6? GnkjXrg4 LtJZC%D.Sԥ}CH4SpDd?90B̜ utPg,.`cS'yhˀ-!Qb_B}) 8# Z}j#ƒNFڗ$IyUU! zyy3 ^|EE&~Ry)̹@: 8g) AL#bP},3U>Hei:y@s ٙ[cRMa%ēmKќ@3Ȱruvu׉sהDz #ju'~#xvTq:ǔyD2ڵkv:'*爌.h A9;D؀@R\)@d t)l~|0P7k) U2j")9خ&LEyEcGQky[^iu:acLDO+Il[qԩ7ZۑbjI'US˓⯆[ ƀz!b1o; 6Kԟye鬓0ݣ @Llt+~&>!>J4`H$k#Cff%=Tҟa4F]D˃ؚ$IljEHo]ODD(kO׿l!p=gaL1Mo{hؾ;z0)W2D< D_t6&7y{%i1Y9G3jv8iE448mYZ;;[7@EVyݛIl_#I۝ ʼ"Mw!!×MCNS>>Vo4e 쳀5;$jo<͗9J@f!)PwbnSd*l Q~6'@UqUm"U4_Oo'7L/YUο~7LZ6|V@&2Dwu2׶I5\' *70O` Rwoto}NAY%I!Oл,}'% XkϽ|:ysTyȉ@ZD/촏˓=RO^H!vbl.:4 -Yƨ{GtZHy%T&7דKɵk۾rjW/XAx_.iB507L&׫rbmEm YgmJ] {s+;eYȧ84y*ew'Ҙ~㳯~t2q۩uVu@y0,K6;{ޫ3E kVڢY-W'q0J3,wl;8VpkͦKz7nRE5YUuekAK0dלH{ש7 9r 8b$鴪(/JB\UUA=M5`fӏUmVu•pˢvd Qo?X`s᫊HbuXoz u#PTb՗6'2 DAz4>.UbV#^u6BށmTy B0 ѩ;UDKv!WJ@cW?yvU)z)"D F+ZvBx^2!zQĹ /&2yDcZ3l|>8YD \vҕbCDQڒ|8r؛1S-?))3s1e 0&]}x(T*,c"1Y_7zM~:,&{'U]׵O(?L̋*٠x~a@P>Sh?i*vlO0tto;@jSHB3\ wtowkYLe2v0-! Nܠ9Ťd-cR1^IUTDht,D2/UHؘBdzV֕7,ːoD^2\Wv`P#;"N\ZhF]Qyz8 Y"]i{y;W+zʐ%ӎig Fe bz2԰}Gco9)?R2#y.sM6̩5Ni4TD!;rKୁQg|Kgꫮۦ,PM}I&Q>g|o&(TR?Q#ys?{ LCD̦ԝNv><҇!HKmǁ8YgYg9"3C腢bWuj =_.DD0$d4&<|bGgxyopA%0k yxnpKK`"H5ˆ FU5}E][ctd\jP_ӻ-P"UD(]&  (1G񼿀.( T|e9G`*q{.i YY[X`Zd["WWuQ񅆋91 ?W$! TH f""C!ɧ0]Lv 3.mumMZgS#TC"۠vb,xG3T!5to8K-.nX'hVUEԅTTgQk DEn}U\VaVz XT5qTlidZc-cElpEԩ//f3`Ɏ/gANI,'[D,]k혽m_ڙH>2#Hf1 pB&494ڜs,T,Ӽ`CDSLNUS N<}`h̩ Ɇ&iЧvI_,ip |}fG.P42U+,99R~@NrLC-@NDuZaRM[i+ڄ }`01LaK6!6"&ipelUbc⾪JUW~'1d]4U(Hw_+[3<ߵ\|?f_;d,uh|~&̀ {RD\b 6w(r\Z^0xYab 2 ܃S{h;ݗnIf" ҈ :o&X/f9q ]6lrO>lW39~\9R2erU+\9>;ێ-=>}/f~M(j5x; .R.N/EUP8IqZM_0lɦ {JZ'g#JOcKhc;1l7QJbEnSgQҢZ}1tMdTͥbADW9|?*rBH"peQ Ʒ"ĺ>BPGP"*~2qQfkXUWwq~3Y&UAuBZ5? ؖjL&]l\|Rie5M( #߮ǻ܊2=ShF?I:.L#"ɗ:̐K~T*T.=˰i>7boDEMV%2\T|TEZUx$y/+5)ggÑl2Qnﵮ*UN/ׯ}ZO¢a"Q!P:觸),밀c &͊D4Au}~ݮt"KP/T"Fu'~dRtɹ\]*+g1sk<=KN.JJNr,2<0PDispOa j*N=".lmt~pfI깗hc5^zk70Q'&5 ^4ΦvT| WP1|񍊊 \ğPdp,NUtrWW[/<~JM`c^Jfkk[!G#& 6lL<EɺwwGX 11FRWVº_sVM`w*!&mW6km=|CLD bk!Q.7XJ"lJ?W9KıVF$+]"zqZk'^؞m.ϟP\R^"ۑ|Kꕸk>&#Elƒܵdkֺ_ !-BF<2 "%(ش%C.^Nr\{C-ko()T$ďV:rg^\ѕđlAvf` bN$1$)YӺT35xUZ#<8 3ܗOV:ٰC7{(Nn*_捁^qg `*-Z9xb'ٷxLu7 I[_kfhmŭxg(IŕOtxy"m&McBAD,Gw|'q\)^Q[Rqxc__xT '.ˍfqE3ձJITd] tBV,Vuk99;G>ϧެWDhENohM.'"*Ĺ V_p^>B S` Q8,ug /^?BhNm@ܵ˷^((J_W\ztwv$@^i9u\x4̲lk^47"=RZv̽~DLRAj Sb}aLIKN-nޗ)J'!{VO?CFaeͫ'Y*dDqwNvjP DX{-b]@ƨөӊz)fH4׽1;$&4oy)f]S.M^Z f,4wμߪ%*9xN T)eJ>8$M,$5}*x/];ϧeB2.(2pzDHE2`(Jd ⠪RK5˅UNp e0D댺W ٝ%K>~ɏb>fZ S+|kxtQmVn@m8Q5DL MHka? ;BFLxdYZHz UN(m!YA{˛M{.X2جz΀6Nmk;T3yKU! C=Ç 9BDxZi~gM /Ǐ]X9Va7~Kn 0hѨBkp@U(: ucDd㔙Ua:mTg[V&!nMK!]UV(6I0Z ֪j $+ʑ;ÔMhmRܛK1ͱ<njIhT$ta<ӆm4*[kh)7ڏ@uɲrWQ A#@Ą\y …fx(SJWB/gv/K.ʢ.3WWEo~~tܦiW^-> ڛԻIaTD a@}  dZ` l|P4-6DB$K` -B5&%.nPG&Y@^JP6t>Q R ]^\L*aV /MIO9 r:p4#ىmrۿl ġP*n7sb̈"Rn܀TZeLdY< Lxk 1 iZQE2 7S-nv Q(>D{Ѻzll4"zun롳qƋ..8 d=x+o"FB&wRVuʲlZ^4ywݙx&rϲ"no8Ift6;! 2(Lk"#TS̪Z׵F$&m@G'~T2AT^DQSM"Ny Ua_ eN>76b !G"Ks- {q 9L:W[Wt>!CҥqҸw24 HwnIjڈ:ڵk/Rpmッ5N8*UC emĉ5 -j?wǤ,=z4/%ooow?[6)}R[h\Q 7L֡Wp}- wIYVɛ;t0*{G1^_(fᇇ~@CҎ-h᪢~.^< $I&IlnkaVc&0 bmmlokU?|x[;2MXD&_~qITY~x_Nگh< S ޽Y;Xol~&U7ȐWFЊ٧GeSU{cTD\ h1I1)bufm^@xWY^WYaqϏAcL&++36Y^{[h6S0|QTpcT_tS1|~_iZI5O>>ꦖPvAWy5<΁~4ہXCZ6c6^\ET`ρ! k'5WƟ|inPnIEkn(ʢt'wL&A¸F %I2cLT~9).sK̢(4yW1s5B5dcm!Nzǻމ̆БQ[2|V^+u.tUb'2C4܋u\%_Ɗ<];a䑂 L*G/8Rt)Bd7L}cȝ{b"Ou$wp!L sPQVUmg6?ug_qwka"Lr9 R 9~WtU}/T$Ɨ2_*=PgNġUՕ*Q˷תZ{rr^FݤP83*%LݙbIW7W~!j8I ^7_h ~bӱyR֏lIi^U%jfOOU2i%P'IlWc9˜%WhW7帋h2=qMW?g~7-sb㿇ɏ[:d[Z;D%"rmEȍf}KյY^z/z8I<~jcM9x#VmE̝}uv '|{lՙVM/۩|v|yFkTHlԡ?vR/HJUjpSt#(ݛ|/abp RMyz hϏjk!WJJqWjb2H-+ntE{ϧ[٘$IΚ{ CђQVo'W_zߑǿeL+rWU\OJ%|9#II+ۀ13YPB&DT=8SWdZ+饭Uz7ut|T5;@!*EJ%Jmv.B"y P fv%l7vEDa?fx3 cW5Smɍ7"UZG8YSTb"U^ԇYh* C3@v F ktĤ|a~q''d@*E*z@e=٬p~^9M-(j;pMו킇J'P#֐Zʊa{F",Lh8R*e/[˶:Mu2UHd S9Z!ËqZZCO`(!ǩ^P"6"ImӢڥ%,azbnzXKQO'%? UJ &F|{ 1iyĈC&ZflqDDˍwyplUdQU"oDUf}==e/` d2L& r25o:JR?d,qaYH6iMFƐ&VGSÑ&Eo_@i"aq!5\8U޴s.Yh{,kQ=d|8I5U8'[f)5\̆ '|v^%g T䕸s@ZH& "%}>Vՠ?q'> / <mA4LPobvLIz|RPD*Q9o䬱M _9!_RT֜CZXR=E}i,(t8D[3m8TO +C L} %m9fiumX Bb}SER&8)#c8'7R3r7/Y ejq2Ok +CiaT5`E]ovF425p΅qYvI'w h $)^ιq륻;'ra yxbm[݌EUUbSa>ZkvÀ5dzZDPTtLP!Sͪc& u?~QZk^cnIh[o=|pwwPZ Kzvvo| RE8A?ly<:%U|#{8]5 !WnnnYԧ^l?7@2RAq6; Ɏ!oAϧJEPOzag3mV li* 4UHM-&}8*W.?q/́ {g~̷Ҧy8Dfpv7pww0ZOpelKme"ƏքUTi{}JVU [Y4@ vt⡢D M˝˸:V3*LwX*e6N|&]ځTEiEK(-azj*ܭV+TvO=9G&G#8Y@\2ڱYFFqqv4gf]fRqZOkGeJ=$:~_01Ql l$Z :HQ x&FUxO?ԥz7͕/|Չ~.Pzn78O19$/ ,}eY)46\,IZ_$7bzʼnSNjćo"1R(Vb&2d&_˶ N;J 7 $e93 ́V(4-2 M" ,e fn.q._L4W_,ŕk+TW$O%-ل(" $Z]|/Ɲb/*5f6󳳳<ϳ,;>>^YYshj!Ԋh0looʕ+W\ 絙z ?eӟՈgcUϯڗ$IB7(ey޽ZkիW_}) B.3›H/͸1oZ_=E`a%0he.^M'V_`XdFyz*a ?ZvTFק]OZKWCEgOǥYHYKƀwKtxY2H%tEXtdate:create2018-10-06T17:06:46+00:004%tEXtdate:modify2018-10-06T17:06:46+00:00i?xIENDB`aiohttp-jinja2-1.2.0/docs/make.bat0000664000372000037200000001507513553343716017556 0ustar travistravis00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. xml to make Docutils-native XML files echo. pseudoxml to make pseudoxml-XML files for display purposes echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) %SPHINXBUILD% 2> nul if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\aiohttp_jinja2.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\aiohttp_jinja2.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdf" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "latexpdfja" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex cd %BUILDDIR%/latex make all-pdf-ja cd %BUILDDIR%/.. echo. echo.Build finished; the PDF files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) if "%1" == "xml" ( %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml if errorlevel 1 exit /b 1 echo. echo.Build finished. The XML files are in %BUILDDIR%/xml. goto end ) if "%1" == "pseudoxml" ( %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml if errorlevel 1 exit /b 1 echo. echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. goto end ) :end aiohttp-jinja2-1.2.0/CHANGES.txt0000664000372000037200000000550113553343716017023 0ustar travistravis00000000000000CHANGES ======= 1.2.0 (2019-10-21) ------------------ - Add type hints #285 1.1.1 (2019-04-25) ------------------ - Bump minimal supported ``jinja2`` version to 2.10.1 to avoid security vulnerability problem. 1.1.0 (2018-09-05) ------------------ - Bump minimal supported ``aiohttp`` version to 3.2 - Use ``request.config_dict`` for accessing ``jinja2`` environment. It allows to reuse jinja rendering engine from parent application. 1.0.0 (2018-03-12) ------------------- - Allow context_processors to compose from parent apps #195 0.17.0 (2018-03-12) ------------------- - Auto-cast ``int`` values in ``url()`` jinja function to ``str`` #191 0.16.0 (2018-02-12) ------------------- - Pin to aiohttp 3.0+ - Deprecate non-async handlers support 0.15.0 (2018-01-30) ------------------- - Upgrade middleware to new style from aiohttp 2.3+ #182 - Autoescape all templates by default #179 0.13.0 (2016-12-14) ------------------- - Avoid subtle errors by copying context processor data #51 0.12.0 (2016-12-02) ------------------- - Add autodeploy script #46 0.11.0 (2016-11-24) ------------------- - Add jinja2 filters support #41 0.10.0 (2016-10-20) ------------------- - Rename package to aiohttp-jinja2 #31 0.9.0 (2016-09-26) ------------------ - Fix reason parameter in HTTPInternalServerError when template is not found #33 0.8.0 (2016-07-12) ------------------ - Add ability to render template without context #28 0.7.0 (2015-12-30) ------------------ - Add ability to decorate class based views (available in aiohttp 0.20) #18 - Upgrade aiohttp requirement to version 0.20.0+ 0.6.2 (2015-11-22) ------------------ - Make app_key parameter from render_string coroutine optional 0.6.0 (2015-10-29) ------------------ - Fix a bug in middleware (missed coroutine decorator) #16 - Drop Python 3.3 support (switched to aiohttp version v0.18.0) - Simplify context processors initialization by adding parameter to `setup()` 0.5.0 (2015-07-09) ------------------ - Introduce context processors #14 - Bypass StreamResponse #15 0.4.3 (2015-06-01) ------------------ - Fix distribution building: add manifest file 0.4.2 (2015-05-21) ------------------ - Make HTTPInternalServerError exceptions more verbose on console output 0.4.1 (2015-04-05) ------------------ - Documentation update 0.4.0 (2015-04-02) ------------------ - Add `render_string` method 0.3.1 (2015-04-01) ------------------ - Don't allow non-mapping context - Fix tiny documentation issues - Change the library logo 0.3.0 (2015-03-15) ------------------ - Documentation release 0.2.1 (2015-02-15) ------------------ - Fix `render_template` function 0.2.0 (2015-02-05) ------------------ - Migrate to aiohttp 0.14 - Add `status` parameter to template decorator - Drop optional `response` parameter 0.1.0 (2015-01-08) ------------------ - Initial release aiohttp-jinja2-1.2.0/PKG-INFO0000664000372000037200000002150313553343761016307 0ustar travistravis00000000000000Metadata-Version: 1.2 Name: aiohttp-jinja2 Version: 1.2.0 Summary: jinja2 template renderer for aiohttp.web (http server for asyncio) Home-page: https://github.com/aio-libs/aiohttp_jinja2/ Author: Andrew Svetlov Author-email: andrew.svetlov@gmail.com License: Apache 2 Description: aiohttp_jinja2 ============== .. image:: https://travis-ci.org/aio-libs/aiohttp-jinja2.svg?branch=master :target: https://travis-ci.org/aio-libs/aiohttp-jinja2 .. image:: https://codecov.io/gh/aio-libs/aiohttp-jinja2/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiohttp-jinja2 .. image:: https://img.shields.io/pypi/v/aiohttp-jinja2.svg :target: https://pypi.python.org/pypi/aiohttp-jinja2 .. image:: https://readthedocs.org/projects/aiohttp-jinja2/badge/?version=latest :target: http://aiohttp-jinja2.readthedocs.io/en/latest/?badge=latest jinja2_ template renderer for `aiohttp.web`__. .. _jinja2: http://jinja.pocoo.org .. _aiohttp_web: https://aiohttp.readthedocs.io/en/latest/web.html __ aiohttp_web_ Installation ------------ Install from PyPI:: pip install aiohttp-jinja2 Developing ---------- Install requirement and launch tests:: pip install -r requirements-dev.txt py.test tests Usage ----- Before template rendering you have to setup *jinja2 environment* first: .. code-block:: python app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder')) Import: .. code-block:: python import aiohttp_jinja2 import jinja2 After that you may to use template engine in your *web-handlers*. The most convenient way is to decorate a *web-handler*. Using the function based web handlers: .. code-block:: python @aiohttp_jinja2.template('tmpl.jinja2') def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} Or for `Class Based Views `: .. code-block:: python class Handler(web.View): @aiohttp_jinja2.template('tmpl.jinja2') async def get(self): return {'name': 'Andrew', 'surname': 'Svetlov'} On handler call the ``aiohttp_jinja2.template`` decorator will pass returned dictionary ``{'name': 'Andrew', 'surname': 'Svetlov'}`` into template named ``tmpl.jinja2`` for getting resulting HTML text. If you need more complex processing (set response headers for example) you may call ``render_template`` function. Using a function based web handler: .. code-block:: python async def handler(request): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context) response.headers['Content-Language'] = 'ru' return response Or, again, a class based view: .. code-block:: python class Handler(web.View): async def get(self): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', self.request, context) response.headers['Content-Language'] = 'ru' return response License ------- ``aiohttp_jinja2`` is offered under the Apache 2 license. CHANGES ======= 1.2.0 (2019-10-21) ------------------ - Add type hints #285 1.1.1 (2019-04-25) ------------------ - Bump minimal supported ``jinja2`` version to 2.10.1 to avoid security vulnerability problem. 1.1.0 (2018-09-05) ------------------ - Bump minimal supported ``aiohttp`` version to 3.2 - Use ``request.config_dict`` for accessing ``jinja2`` environment. It allows to reuse jinja rendering engine from parent application. 1.0.0 (2018-03-12) ------------------- - Allow context_processors to compose from parent apps #195 0.17.0 (2018-03-12) ------------------- - Auto-cast ``int`` values in ``url()`` jinja function to ``str`` #191 0.16.0 (2018-02-12) ------------------- - Pin to aiohttp 3.0+ - Deprecate non-async handlers support 0.15.0 (2018-01-30) ------------------- - Upgrade middleware to new style from aiohttp 2.3+ #182 - Autoescape all templates by default #179 0.13.0 (2016-12-14) ------------------- - Avoid subtle errors by copying context processor data #51 0.12.0 (2016-12-02) ------------------- - Add autodeploy script #46 0.11.0 (2016-11-24) ------------------- - Add jinja2 filters support #41 0.10.0 (2016-10-20) ------------------- - Rename package to aiohttp-jinja2 #31 0.9.0 (2016-09-26) ------------------ - Fix reason parameter in HTTPInternalServerError when template is not found #33 0.8.0 (2016-07-12) ------------------ - Add ability to render template without context #28 0.7.0 (2015-12-30) ------------------ - Add ability to decorate class based views (available in aiohttp 0.20) #18 - Upgrade aiohttp requirement to version 0.20.0+ 0.6.2 (2015-11-22) ------------------ - Make app_key parameter from render_string coroutine optional 0.6.0 (2015-10-29) ------------------ - Fix a bug in middleware (missed coroutine decorator) #16 - Drop Python 3.3 support (switched to aiohttp version v0.18.0) - Simplify context processors initialization by adding parameter to `setup()` 0.5.0 (2015-07-09) ------------------ - Introduce context processors #14 - Bypass StreamResponse #15 0.4.3 (2015-06-01) ------------------ - Fix distribution building: add manifest file 0.4.2 (2015-05-21) ------------------ - Make HTTPInternalServerError exceptions more verbose on console output 0.4.1 (2015-04-05) ------------------ - Documentation update 0.4.0 (2015-04-02) ------------------ - Add `render_string` method 0.3.1 (2015-04-01) ------------------ - Don't allow non-mapping context - Fix tiny documentation issues - Change the library logo 0.3.0 (2015-03-15) ------------------ - Documentation release 0.2.1 (2015-02-15) ------------------ - Fix `render_template` function 0.2.0 (2015-02-05) ------------------ - Migrate to aiohttp 0.14 - Add `status` parameter to template decorator - Drop optional `response` parameter 0.1.0 (2015-01-08) ------------------ - Initial release Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Development Status :: 5 - Production/Stable Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: AsyncIO Requires-Python: >=3.5.3 aiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/0000775000372000037200000000000013553343761021610 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/PKG-INFO0000664000372000037200000002150313553343761022706 0ustar travistravis00000000000000Metadata-Version: 1.2 Name: aiohttp-jinja2 Version: 1.2.0 Summary: jinja2 template renderer for aiohttp.web (http server for asyncio) Home-page: https://github.com/aio-libs/aiohttp_jinja2/ Author: Andrew Svetlov Author-email: andrew.svetlov@gmail.com License: Apache 2 Description: aiohttp_jinja2 ============== .. image:: https://travis-ci.org/aio-libs/aiohttp-jinja2.svg?branch=master :target: https://travis-ci.org/aio-libs/aiohttp-jinja2 .. image:: https://codecov.io/gh/aio-libs/aiohttp-jinja2/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiohttp-jinja2 .. image:: https://img.shields.io/pypi/v/aiohttp-jinja2.svg :target: https://pypi.python.org/pypi/aiohttp-jinja2 .. image:: https://readthedocs.org/projects/aiohttp-jinja2/badge/?version=latest :target: http://aiohttp-jinja2.readthedocs.io/en/latest/?badge=latest jinja2_ template renderer for `aiohttp.web`__. .. _jinja2: http://jinja.pocoo.org .. _aiohttp_web: https://aiohttp.readthedocs.io/en/latest/web.html __ aiohttp_web_ Installation ------------ Install from PyPI:: pip install aiohttp-jinja2 Developing ---------- Install requirement and launch tests:: pip install -r requirements-dev.txt py.test tests Usage ----- Before template rendering you have to setup *jinja2 environment* first: .. code-block:: python app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder')) Import: .. code-block:: python import aiohttp_jinja2 import jinja2 After that you may to use template engine in your *web-handlers*. The most convenient way is to decorate a *web-handler*. Using the function based web handlers: .. code-block:: python @aiohttp_jinja2.template('tmpl.jinja2') def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} Or for `Class Based Views `: .. code-block:: python class Handler(web.View): @aiohttp_jinja2.template('tmpl.jinja2') async def get(self): return {'name': 'Andrew', 'surname': 'Svetlov'} On handler call the ``aiohttp_jinja2.template`` decorator will pass returned dictionary ``{'name': 'Andrew', 'surname': 'Svetlov'}`` into template named ``tmpl.jinja2`` for getting resulting HTML text. If you need more complex processing (set response headers for example) you may call ``render_template`` function. Using a function based web handler: .. code-block:: python async def handler(request): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context) response.headers['Content-Language'] = 'ru' return response Or, again, a class based view: .. code-block:: python class Handler(web.View): async def get(self): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', self.request, context) response.headers['Content-Language'] = 'ru' return response License ------- ``aiohttp_jinja2`` is offered under the Apache 2 license. CHANGES ======= 1.2.0 (2019-10-21) ------------------ - Add type hints #285 1.1.1 (2019-04-25) ------------------ - Bump minimal supported ``jinja2`` version to 2.10.1 to avoid security vulnerability problem. 1.1.0 (2018-09-05) ------------------ - Bump minimal supported ``aiohttp`` version to 3.2 - Use ``request.config_dict`` for accessing ``jinja2`` environment. It allows to reuse jinja rendering engine from parent application. 1.0.0 (2018-03-12) ------------------- - Allow context_processors to compose from parent apps #195 0.17.0 (2018-03-12) ------------------- - Auto-cast ``int`` values in ``url()`` jinja function to ``str`` #191 0.16.0 (2018-02-12) ------------------- - Pin to aiohttp 3.0+ - Deprecate non-async handlers support 0.15.0 (2018-01-30) ------------------- - Upgrade middleware to new style from aiohttp 2.3+ #182 - Autoescape all templates by default #179 0.13.0 (2016-12-14) ------------------- - Avoid subtle errors by copying context processor data #51 0.12.0 (2016-12-02) ------------------- - Add autodeploy script #46 0.11.0 (2016-11-24) ------------------- - Add jinja2 filters support #41 0.10.0 (2016-10-20) ------------------- - Rename package to aiohttp-jinja2 #31 0.9.0 (2016-09-26) ------------------ - Fix reason parameter in HTTPInternalServerError when template is not found #33 0.8.0 (2016-07-12) ------------------ - Add ability to render template without context #28 0.7.0 (2015-12-30) ------------------ - Add ability to decorate class based views (available in aiohttp 0.20) #18 - Upgrade aiohttp requirement to version 0.20.0+ 0.6.2 (2015-11-22) ------------------ - Make app_key parameter from render_string coroutine optional 0.6.0 (2015-10-29) ------------------ - Fix a bug in middleware (missed coroutine decorator) #16 - Drop Python 3.3 support (switched to aiohttp version v0.18.0) - Simplify context processors initialization by adding parameter to `setup()` 0.5.0 (2015-07-09) ------------------ - Introduce context processors #14 - Bypass StreamResponse #15 0.4.3 (2015-06-01) ------------------ - Fix distribution building: add manifest file 0.4.2 (2015-05-21) ------------------ - Make HTTPInternalServerError exceptions more verbose on console output 0.4.1 (2015-04-05) ------------------ - Documentation update 0.4.0 (2015-04-02) ------------------ - Add `render_string` method 0.3.1 (2015-04-01) ------------------ - Don't allow non-mapping context - Fix tiny documentation issues - Change the library logo 0.3.0 (2015-03-15) ------------------ - Documentation release 0.2.1 (2015-02-15) ------------------ - Fix `render_template` function 0.2.0 (2015-02-05) ------------------ - Migrate to aiohttp 0.14 - Add `status` parameter to template decorator - Drop optional `response` parameter 0.1.0 (2015-01-08) ------------------ - Initial release Platform: UNKNOWN Classifier: License :: OSI Approved :: Apache Software License Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Development Status :: 5 - Production/Stable Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: AsyncIO Requires-Python: >=3.5.3 aiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/dependency_links.txt0000664000372000037200000000000113553343761025656 0ustar travistravis00000000000000 aiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/top_level.txt0000664000372000037200000000001713553343761024340 0ustar travistravis00000000000000aiohttp_jinja2 aiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/SOURCES.txt0000664000372000037200000000117413553343761023477 0ustar travistravis00000000000000.coveragerc CHANGES.txt LICENSE MANIFEST.in Makefile README.rst pytest.ini requirements-dev.txt setup.py aiohttp_jinja2/__init__.py aiohttp_jinja2/helpers.py aiohttp_jinja2/py.typed aiohttp_jinja2.egg-info/PKG-INFO aiohttp_jinja2.egg-info/SOURCES.txt aiohttp_jinja2.egg-info/dependency_links.txt aiohttp_jinja2.egg-info/requires.txt aiohttp_jinja2.egg-info/top_level.txt docs/Makefile docs/aiohttp-icon.ico docs/api.rst docs/conf.py docs/index.rst docs/make.bat docs/_static/aiohttp-icon-128x128.png tests/conftest.py tests/test_context_processors.py tests/test_jinja_filters.py tests/test_jinja_globals.py tests/test_simple_renderer.pyaiohttp-jinja2-1.2.0/aiohttp_jinja2.egg-info/requires.txt0000664000372000037200000000003613553343761024207 0ustar travistravis00000000000000aiohttp>=3.2.0 jinja2>=2.10.1 aiohttp-jinja2-1.2.0/requirements-dev.txt0000664000372000037200000000034113553343716021247 0ustar travistravis00000000000000attrs==19.3.0 flake8==3.7.8 coverage==4.5.4 sphinx==2.2.0 alabaster>=0.6.2 aiohttp==3.6.2 jinja2==2.10.3 pytest==5.2.1 pytest-cov==2.8.1 yarl==1.3.0 multidict==4.5.2 pytest-aiohttp==0.3.0 pytest-sugar==0.9.2 mypy==0.740 -e . aiohttp-jinja2-1.2.0/Makefile0000664000372000037200000000145013553343716016651 0ustar travistravis00000000000000# Some simple testing tasks (sorry, UNIX only). flake: flake8 aiohttp_jinja2 tests mypy --strict aiohttp_jinja2 test: flake py.test -s ./tests/ cov cover coverage: py.test --cov=aiohttp_jinja2 --cov-report=html --cov-report=term ./tests/ @echo "open file://`pwd`/htmlcov/index.html" clean: rm -rf `find . -name __pycache__` rm -f `find . -type f -name '*.py[co]' ` rm -f `find . -type f -name '*~' ` rm -f `find . -type f -name '.*~' ` rm -f `find . -type f -name '@*' ` rm -f `find . -type f -name '#*#' ` rm -f `find . -type f -name '*.orig' ` rm -f `find . -type f -name '*.rej' ` rm -f .coverage rm -rf coverage rm -rf build rm -rf cover doc: make -C docs html @echo "open file://`pwd`/docs/_build/html/index.html" .PHONY: all build venv flake test vtest testloop cov clean doc aiohttp-jinja2-1.2.0/pytest.ini0000664000372000037200000000004313553343716017237 0ustar travistravis00000000000000[pytest] filterwarnings= error aiohttp-jinja2-1.2.0/aiohttp_jinja2/0000775000372000037200000000000013553343761020116 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/aiohttp_jinja2/py.typed0000664000372000037200000000001013553343716021604 0ustar travistravis00000000000000# markeraiohttp-jinja2-1.2.0/aiohttp_jinja2/__init__.py0000664000372000037200000001126313553343716022232 0ustar travistravis00000000000000import asyncio import functools import warnings import jinja2 from collections.abc import Mapping from typing import Any, Awaitable, Callable, Dict, Iterable, Optional, cast from aiohttp import web from aiohttp.abc import AbstractView from .helpers import GLOBAL_HELPERS __version__ = '1.2.0' __all__ = ('setup', 'get_env', 'render_template', 'render_string', 'template') APP_CONTEXT_PROCESSORS_KEY = 'aiohttp_jinja2_context_processors' APP_KEY = 'aiohttp_jinja2_environment' REQUEST_CONTEXT_KEY = 'aiohttp_jinja2_context' def setup( app: web.Application, *args: Any, app_key: str = APP_KEY, context_processors: Iterable[Callable[[web.Request], Dict[str, Any]]] = (), filters: Optional[Iterable[Callable[..., str]]] = None, default_helpers: bool = True, **kwargs: Any ) -> jinja2.Environment: kwargs.setdefault("autoescape", True) env = jinja2.Environment(*args, **kwargs) if default_helpers: env.globals.update(GLOBAL_HELPERS) if filters is not None: env.filters.update(filters) app[app_key] = env if context_processors: app[APP_CONTEXT_PROCESSORS_KEY] = context_processors app.middlewares.append(context_processors_middleware) env.globals['app'] = app return env def get_env( app: web.Application, *, app_key: str = APP_KEY ) -> jinja2.Environment: return cast(jinja2.Environment, app.get(app_key)) def render_string( template_name: str, request: web.Request, context: Dict[str, Any], *, app_key: str = APP_KEY ) -> str: env = request.config_dict.get(app_key) if env is None: text = ("Template engine is not initialized, " "call aiohttp_jinja2.setup(..., app_key={}) first" "".format(app_key)) # in order to see meaningful exception message both: on console # output and rendered page we add same message to *reason* and # *text* arguments. raise web.HTTPInternalServerError(reason=text, text=text) try: template = env.get_template(template_name) except jinja2.TemplateNotFound as e: text = "Template '{}' not found".format(template_name) raise web.HTTPInternalServerError(reason=text, text=text) from e if not isinstance(context, Mapping): text = "context should be mapping, not {}".format(type(context)) # same reason as above raise web.HTTPInternalServerError(reason=text, text=text) if request.get(REQUEST_CONTEXT_KEY): context = dict(request[REQUEST_CONTEXT_KEY], **context) text = template.render(context) return text def render_template( template_name: str, request: web.Request, context: Dict[str, Any], *, app_key: str = APP_KEY, encoding: str = 'utf-8', status: int = 200 ) -> web.Response: response = web.Response(status=status) if context is None: context = {} text = render_string(template_name, request, context, app_key=app_key) response.content_type = 'text/html' response.charset = encoding response.text = text return response def template( template_name: str, *, app_key: str = APP_KEY, encoding: str = 'utf-8', status: int = 200 ) -> Any: def wrapper(func: Any) -> Any: @functools.wraps(func) async def wrapped(*args: Any) -> web.StreamResponse: if asyncio.iscoroutinefunction(func): coro = func else: warnings.warn("Bare functions are deprecated, " "use async ones", DeprecationWarning) coro = asyncio.coroutine(func) context = await coro(*args) if isinstance(context, web.StreamResponse): return context # Supports class based views see web.View if isinstance(args[0], AbstractView): request = args[0].request else: request = args[-1] response = render_template(template_name, request, context, app_key=app_key, encoding=encoding) response.set_status(status) return response return wrapped return wrapper @web.middleware async def context_processors_middleware( request: web.Request, handler: Callable[[web.Request], Awaitable[web.StreamResponse]] ) -> web.StreamResponse: if REQUEST_CONTEXT_KEY not in request: request[REQUEST_CONTEXT_KEY] = {} for processor in request.config_dict[APP_CONTEXT_PROCESSORS_KEY]: request[REQUEST_CONTEXT_KEY].update(await processor(request)) return await handler(request) async def request_processor(request: web.Request) -> Dict[str, web.Request]: return {'request': request} aiohttp-jinja2-1.2.0/aiohttp_jinja2/helpers.py0000664000372000037200000000421313553343716022132 0ustar travistravis00000000000000""" useful context functions, see http://jinja.pocoo.org/docs/dev/api/#jinja2.contextfunction """ from typing import Any, Dict, cast import jinja2 from aiohttp import web from yarl import URL @jinja2.contextfunction # type: ignore def url_for(context: Dict[str, Any], __route_name: str, **parts: Any) -> URL: """Filter for generating urls. Usage: {{ url('the-view-name') }} might become "/path/to/view" or {{ url('item-details', id=123, query={'active': 'true'}) }} might become "/items/1?active=true". """ app = cast(web.Application, context['app']) query = None if 'query_' in parts: query = parts.pop('query_') for key in parts: val = parts[key] if isinstance(val, str): # if type is inherited from str expilict cast to str makes sense # if type is exactly str the operation is very fast val = str(val) elif type(val) is int: # int inherited classes like bool are forbidden val = str(val) else: raise TypeError("argument value should be str or int, " "got {} -> [{}] {!r}".format(key, type(val), val)) parts[key] = val url = app.router[__route_name].url_for(**parts) if query: url = url.with_query(query) return url @jinja2.contextfunction # type: ignore def static_url(context: Dict[str, Any], static_file_path: str) -> str: """Filter for generating urls for static files. NOTE: you'll need to set app['static_root_url'] to be used as the root for the urls returned. Usage: {{ static('styles.css') }} might become "/static/styles.css" or "http://mycdn.example.com/styles.css" """ app = context['app'] try: static_url = app['static_root_url'] except KeyError: raise RuntimeError( "app does not define a static root url " "'static_root_url', you need to set the url root " "with app['static_root_url'] = ''.") from None return '{}/{}'.format(static_url.rstrip('/'), static_file_path.lstrip('/')) GLOBAL_HELPERS = dict( url=url_for, static=static_url, ) aiohttp-jinja2-1.2.0/setup.cfg0000664000372000037200000000004613553343761017032 0ustar travistravis00000000000000[egg_info] tag_build = tag_date = 0 aiohttp-jinja2-1.2.0/LICENSE0000664000372000037200000002610713553343716016224 0ustar travistravis00000000000000Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015-2018 Andrew Svetlov and aio-libs team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. aiohttp-jinja2-1.2.0/.coveragerc0000664000372000037200000000007113553343716017330 0ustar travistravis00000000000000# .coveragerc to control coverage.py [run] branch = True aiohttp-jinja2-1.2.0/README.rst0000664000372000037200000000612513553343716016704 0ustar travistravis00000000000000aiohttp_jinja2 ============== .. image:: https://travis-ci.org/aio-libs/aiohttp-jinja2.svg?branch=master :target: https://travis-ci.org/aio-libs/aiohttp-jinja2 .. image:: https://codecov.io/gh/aio-libs/aiohttp-jinja2/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiohttp-jinja2 .. image:: https://img.shields.io/pypi/v/aiohttp-jinja2.svg :target: https://pypi.python.org/pypi/aiohttp-jinja2 .. image:: https://readthedocs.org/projects/aiohttp-jinja2/badge/?version=latest :target: http://aiohttp-jinja2.readthedocs.io/en/latest/?badge=latest jinja2_ template renderer for `aiohttp.web`__. .. _jinja2: http://jinja.pocoo.org .. _aiohttp_web: https://aiohttp.readthedocs.io/en/latest/web.html __ aiohttp_web_ Installation ------------ Install from PyPI:: pip install aiohttp-jinja2 Developing ---------- Install requirement and launch tests:: pip install -r requirements-dev.txt py.test tests Usage ----- Before template rendering you have to setup *jinja2 environment* first: .. code-block:: python app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder')) Import: .. code-block:: python import aiohttp_jinja2 import jinja2 After that you may to use template engine in your *web-handlers*. The most convenient way is to decorate a *web-handler*. Using the function based web handlers: .. code-block:: python @aiohttp_jinja2.template('tmpl.jinja2') def handler(request): return {'name': 'Andrew', 'surname': 'Svetlov'} Or for `Class Based Views `: .. code-block:: python class Handler(web.View): @aiohttp_jinja2.template('tmpl.jinja2') async def get(self): return {'name': 'Andrew', 'surname': 'Svetlov'} On handler call the ``aiohttp_jinja2.template`` decorator will pass returned dictionary ``{'name': 'Andrew', 'surname': 'Svetlov'}`` into template named ``tmpl.jinja2`` for getting resulting HTML text. If you need more complex processing (set response headers for example) you may call ``render_template`` function. Using a function based web handler: .. code-block:: python async def handler(request): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', request, context) response.headers['Content-Language'] = 'ru' return response Or, again, a class based view: .. code-block:: python class Handler(web.View): async def get(self): context = {'name': 'Andrew', 'surname': 'Svetlov'} response = aiohttp_jinja2.render_template('tmpl.jinja2', self.request, context) response.headers['Content-Language'] = 'ru' return response License ------- ``aiohttp_jinja2`` is offered under the Apache 2 license. aiohttp-jinja2-1.2.0/setup.py0000664000372000037200000000365713553343716016736 0ustar travistravis00000000000000import codecs import os import re from setuptools import setup def _get_version(): PATH_TO_INIT_PY = \ os.path.join( os.path.abspath(os.path.dirname(__file__)), 'aiohttp_jinja2', '__init__.py' ) with codecs.open(PATH_TO_INIT_PY, 'r', 'latin1') as fp: try: for line in fp.readlines(): if line: line = line.strip() version = re.findall( r"^__version__ = '([^']+)'$", line, re.M ) if version: return version[0] except IndexError: raise RuntimeError('Unable to determine version.') version = _get_version() def read(f): return open(os.path.join(os.path.dirname(__file__), f)).read().strip() install_requires = ['aiohttp>=3.2.0', 'jinja2>=2.10.1'] setup(name='aiohttp-jinja2', version=version, description=("jinja2 template renderer for aiohttp.web " "(http server for asyncio)"), long_description='\n\n'.join((read('README.rst'), read('CHANGES.txt'))), classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Development Status :: 5 - Production/Stable', 'Topic :: Internet :: WWW/HTTP', 'Framework :: AsyncIO', ], author='Andrew Svetlov', author_email='andrew.svetlov@gmail.com', url='https://github.com/aio-libs/aiohttp_jinja2/', license='Apache 2', packages=['aiohttp_jinja2'], python_requires='>=3.5.3', install_requires=install_requires, include_package_data=True) aiohttp-jinja2-1.2.0/tests/0000775000372000037200000000000013553343761016353 5ustar travistravis00000000000000aiohttp-jinja2-1.2.0/tests/test_jinja_filters.py0000664000372000037200000000115713553343716022613 0ustar travistravis00000000000000import jinja2 from aiohttp import web import aiohttp_jinja2 async def test_jinja_filters(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} def add_2(value): return value + 2 app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.DictLoader({'tmpl.jinja2': "{{ 5|add_2 }}"}), filters={'add_2': add_2} ) app.router.add_route('GET', '/', index) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '7' == txt aiohttp-jinja2-1.2.0/tests/test_context_processors.py0000664000372000037200000001001313553343716023725 0ustar travistravis00000000000000import jinja2 from aiohttp import web import aiohttp_jinja2 async def test_context_processors(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'bar': 2} app = web.Application(middlewares=[ aiohttp_jinja2.context_processors_middleware]) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': 'foo: {{ foo }}, bar: {{ bar }}, path: {{ request.path }}'})) async def processor(request): return {'foo': 1, 'bar': 'should be overwriten'} app['aiohttp_jinja2_context_processors'] = ( aiohttp_jinja2.request_processor, processor, ) app.router.add_get('/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'foo: 1, bar: 2, path: /' == txt async def test_nested_context_processors(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'bar': 2} subapp = web.Application(middlewares=[ aiohttp_jinja2.context_processors_middleware]) aiohttp_jinja2.setup(subapp, loader=jinja2.DictLoader( {'tmpl.jinja2': 'foo: {{ foo }}, bar: {{ bar }}, ' 'baz: {{ baz }}, path: {{ request.path }}'})) async def subprocessor(request): return {'foo': 1, 'bar': 'should be overwriten'} subapp['aiohttp_jinja2_context_processors'] = ( aiohttp_jinja2.request_processor, subprocessor, ) subapp.router.add_get('/', func) app = web.Application(middlewares=[ aiohttp_jinja2.context_processors_middleware]) aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({})) async def processor(request): return {'baz': 5} app['aiohttp_jinja2_context_processors'] = ( aiohttp_jinja2.request_processor, processor, ) app.add_subapp('/sub/', subapp) client = await aiohttp_client(app) resp = await client.get('/sub/') assert 200 == resp.status txt = await resp.text() assert 'foo: 1, bar: 2, baz: 5, path: /sub/' == txt async def test_context_is_response(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): raise web.HTTPForbidden() app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "template"})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 403 == resp.status async def test_context_processors_new_setup_style(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'bar': 2} async def processor(request): return {'foo': 1, 'bar': 'should be overwriten'} app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.DictLoader( {'tmpl.jinja2': 'foo: {{ foo }}, bar: {{ bar }}, ' 'path: {{ request.path }}'}), context_processors=(aiohttp_jinja2.request_processor, processor) ) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'foo: 1, bar: 2, path: /' == txt async def test_context_not_tainted(aiohttp_client): global_context = {'version': 1} @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return global_context async def processor(request): return {'foo': 1} app = web.Application() aiohttp_jinja2.setup( app, loader=jinja2.DictLoader({'tmpl.jinja2': 'foo: {{ foo }}'}), context_processors=[processor]) app.router.add_get('/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'foo: 1' == txt assert 'foo' not in global_context aiohttp-jinja2-1.2.0/tests/test_simple_renderer.py0000664000372000037200000002160713553343716023151 0ustar travistravis00000000000000import jinja2 import pytest from aiohttp import web from aiohttp.test_utils import make_mocked_request import aiohttp_jinja2 async def test_func(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'head': 'HEAD', 'text': 'text'} template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_render_class_based_view(aiohttp_client): class MyView(web.View): @aiohttp_jinja2.template('tmpl.jinja2') async def get(self): return {'head': 'HEAD', 'text': 'text'} template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', MyView) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_meth(aiohttp_client): class Handler: @aiohttp_jinja2.template('tmpl.jinja2') async def meth(self, request): return {'head': 'HEAD', 'text': 'text'} template = '

{{head}}

{{text}}' handler = Handler() app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', handler.meth) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_convert_func_to_coroutine(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'head': 'HEAD', 'text': 'text'} template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') txt = await resp.text() assert '

HEAD

text' == txt async def test_render_not_initialized(): async def func(request): return aiohttp_jinja2.render_template('template', request, {}) app = web.Application() app.router.add_route('GET', '/', func) req = make_mocked_request('GET', '/', app=app) msg = "Template engine is not initialized, " \ "call aiohttp_jinja2.setup(..., app_key={}" \ ") first".format(aiohttp_jinja2.APP_KEY) with pytest.raises(web.HTTPInternalServerError) as ctx: await func(req) assert msg == ctx.value.text async def test_set_status(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2', status=201) async def func(request): return {'head': 'HEAD', 'text': 'text'} template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 201 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_render_template(aiohttp_client): async def func(request): return aiohttp_jinja2.render_template( 'tmpl.jinja2', request, {'head': 'HEAD', 'text': 'text'}) template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_render_template_custom_status(aiohttp_client): async def func(request): return aiohttp_jinja2.render_template( 'tmpl.jinja2', request, {'head': 'HEAD', 'text': 'text'}, status=404) template = '

{{head}}

{{text}}' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({ 'tmpl.jinja2': template })) app.router.add_route('*', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 404 == resp.status txt = await resp.text() assert '

HEAD

text' == txt async def test_template_not_found(): async def func(request): return aiohttp_jinja2.render_template('template', request, {}) app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({})) app.router.add_route('GET', '/', func) req = make_mocked_request('GET', '/', app=app) with pytest.raises(web.HTTPInternalServerError) as ctx: await func(req) t = "Template 'template' not found" assert t == ctx.value.text assert t == ctx.value.reason async def test_render_not_mapping(): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return 123 app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': 'tmpl'})) app.router.add_route('GET', '/', func) req = make_mocked_request('GET', '/', app=app) msg = "context should be mapping, not " with pytest.raises(web.HTTPInternalServerError) as ctx: await func(req) assert msg == ctx.value.text async def test_render_without_context(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): pass template = '

{{text}}

' app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': template})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '

' == txt async def test_render_default_is_autoescaped(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'text': ''} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': '{{text}}'})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '<script>alert(1)</script>' == txt async def test_render_can_disable_autoescape(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return {'text': ''} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': '{{text}}'}), autoescape=False) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '' == txt async def test_render_bare_funcs_deprecated(aiohttp_client): def wrapper(func): async def wrapped(request): with pytest.warns(DeprecationWarning, match='Bare functions are deprecated'): return await func(request) return wrapped @wrapper @aiohttp_jinja2.template('tmpl.jinja2') def func(request): return {'text': 'OK'} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': '{{text}}'})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'OK' == txt async def test_skip_render_for_response_from_handler(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def func(request): return web.Response(text='OK') app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': '{{text}}'})) app.router.add_route('GET', '/', func) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert 'OK' == txt aiohttp-jinja2-1.2.0/tests/test_jinja_globals.py0000664000372000037200000001102613553343716022562 0ustar travistravis00000000000000import jinja2 import pytest from aiohttp import web import aiohttp_jinja2 def test_get_env(): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "tmpl"})) env = aiohttp_jinja2.get_env(app) assert isinstance(env, jinja2.Environment) assert env is aiohttp_jinja2.get_env(app) async def test_url(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} async def other(request): return app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ url('other', name='John_Doe')}}"})) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/user/{name}', other, name='other') client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '/user/John_Doe' == txt async def test_url_with_query(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ url('index', query_={'foo': 'bar'})}}"})) app.router.add_get('/', index, name='index') client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '/?foo=bar' == txt async def test_url_int_param(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} async def other(request): return app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ url('other', arg=1)}}"})) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/uid/{arg}', other, name='other') client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '/uid/1' == txt async def test_url_param_forbidden_type(aiohttp_client): async def index(request): with pytest.raises(TypeError, match=(r"argument value should be str or int, " r"got arg -> \[\] True")): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response() async def other(request): return app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ url('other', arg=True)}}"})) app.router.add_route('GET', '/', index) app.router.add_route('GET', '/uid/{arg}', other, name='other') client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status async def test_helpers_disabled(aiohttp_client): async def index(request): with pytest.raises(jinja2.UndefinedError, match="'url' is undefined"): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response() app = web.Application() aiohttp_jinja2.setup( app, default_helpers=False, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ url('index')}}"}) ) app.router.add_route('GET', '/', index) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status async def test_static(aiohttp_client): @aiohttp_jinja2.template('tmpl.jinja2') async def index(request): return {} app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ static('whatever.js') }}"})) app['static_root_url'] = '/static' app.router.add_route('GET', '/', index) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status txt = await resp.text() assert '/static/whatever.js' == txt async def test_static_var_missing(aiohttp_client, caplog): async def index(request): with pytest.raises(RuntimeError, match='static_root_url'): aiohttp_jinja2.render_template('tmpl.jinja2', request, {}) return web.Response() app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.DictLoader( {'tmpl.jinja2': "{{ static('whatever.js') }}"})) app.router.add_route('GET', '/', index) client = await aiohttp_client(app) resp = await client.get('/') assert 200 == resp.status # static_root_url is not set aiohttp-jinja2-1.2.0/tests/conftest.py0000664000372000037200000000000013553343716020540 0ustar travistravis00000000000000