Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type annotations #285

Merged
merged 1 commit into from
Oct 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,6 @@ coverage/
.pytest_cache

# code editors
.vscode
.vscode

.mypy_cache
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ include 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
Expand Down
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

flake:
flake8 aiohttp_jinja2 tests
mypy --strict aiohttp_jinja2

test: flake
py.test -s ./tests/
Expand Down
64 changes: 49 additions & 15 deletions aiohttp_jinja2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
import functools
import warnings
import jinja2
from collections import Mapping
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
Expand All @@ -18,10 +19,17 @@
REQUEST_CONTEXT_KEY = 'aiohttp_jinja2_context'


def setup(app, *args, app_key=APP_KEY, context_processors=(),
filters=None, default_helpers=True, autoescape=True,
**kwargs):
env = jinja2.Environment(*args, autoescape=autoescape, **kwargs)
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:
Expand All @@ -36,11 +44,21 @@ def setup(app, *args, app_key=APP_KEY, context_processors=(),
return env


def get_env(app, *, app_key=APP_KEY):
return app.get(app_key)
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, request, context, *, app_key=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, "
Expand All @@ -65,8 +83,15 @@ def render_string(template_name, request, context, *, app_key=APP_KEY):
return text


def render_template(template_name, request, context, *,
app_key=APP_KEY, encoding='utf-8', status=200):
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 = {}
Expand All @@ -77,11 +102,17 @@ def render_template(template_name, request, context, *,
return response


def template(template_name, *, app_key=APP_KEY, encoding='utf-8', status=200):
def template(
template_name: str,
*,
app_key: str = APP_KEY,
encoding: str = 'utf-8',
status: int = 200
) -> Any:

def wrapper(func):
def wrapper(func: Any) -> Any:
@functools.wraps(func)
async def wrapped(*args):
async def wrapped(*args: Any) -> web.StreamResponse:
if asyncio.iscoroutinefunction(func):
coro = func
else:
Expand All @@ -107,7 +138,10 @@ async def wrapped(*args):


@web.middleware
async def context_processors_middleware(request, handler):
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] = {}
Expand All @@ -116,5 +150,5 @@ async def context_processors_middleware(request, handler):
return await handler(request)


async def request_processor(request):
async def request_processor(request: web.Request) -> Dict[str, web.Request]:
return {'request': request}
14 changes: 9 additions & 5 deletions aiohttp_jinja2/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@
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
def url_for(context, __route_name, **parts):
@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 = context['app']
app = cast(web.Application, context['app'])

query = None
if 'query_' in parts:
Expand All @@ -39,8 +43,8 @@ def url_for(context, __route_name, **parts):
return url


@jinja2.contextfunction
def static_url(context, static_file_path):
@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
Expand Down
1 change: 1 addition & 0 deletions aiohttp_jinja2/py.typed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# marker
1 change: 1 addition & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ yarl==1.3.0
multidict==4.5.2
pytest-aiohttp==0.3.0
pytest-sugar==0.9.2
mypy==0.740
-e .