-
Notifications
You must be signed in to change notification settings - Fork 45
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2d21eab
commit 6c1104b
Showing
13 changed files
with
228 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,51 @@ | ||
from pathlib import Path | ||
# {% if template_engine.is_jinja2 %} | ||
import aiohttp_jinja2 | ||
from aiohttp_jinja2 import APP_KEY as JINJA2_APP_KEY | ||
import jinja2 | ||
# {% endif %} | ||
from aiohttp import web | ||
from .routes import routes | ||
|
||
from .routes import setup_routes | ||
|
||
THIS_DIR = Path(__file__).parent | ||
# {% if template_engine.is_jinja2 %} | ||
|
||
@jinja2.contextfilter | ||
def reverse_url(context, name, **parts): | ||
app = context['app'] | ||
|
||
kwargs = {} | ||
if 'query' in parts: | ||
kwargs['query'] = parts.pop('query') | ||
if parts: | ||
kwargs['parts'] = parts | ||
return app.router[name].url(**kwargs) | ||
|
||
|
||
@jinja2.contextfilter | ||
def static_url(context, static_file): | ||
app = context['app'] | ||
try: | ||
static_url = app['static_url'] | ||
except KeyError: | ||
raise RuntimeError('app does not define a static root url "static_url"') | ||
return '{}/{}'.format(static_url.rstrip('/'), static_file.lstrip('/')) | ||
# {% endif %} | ||
|
||
|
||
def create_app(loop): | ||
app = web.Application(loop=loop) | ||
[app.router.add_route(*args) for args in routes] | ||
app['name'] = '{{ name }}' | ||
# {% if template_engine.is_jinja2 %} | ||
|
||
jinja2_loader = jinja2.FileSystemLoader(str(THIS_DIR / 'templates')) | ||
aiohttp_jinja2.setup(app, loader=jinja2_loader, app_key=JINJA2_APP_KEY) | ||
app[JINJA2_APP_KEY].filters.update( | ||
url=reverse_url, | ||
static=static_url, | ||
) | ||
# {% endif %} | ||
|
||
setup_routes(app) | ||
return app |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,6 @@ | ||
from .views import index | ||
|
||
routes = [ | ||
('/', index), | ||
] | ||
from .views import index, messages | ||
|
||
|
||
def setup_routes(app): | ||
app.router.add_get('/', index, name='index') | ||
app.router.add_route('*', '/messages', messages, name='messages') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,15 @@ | ||
{% if template_engine.is_jinja %} | ||
{% if template_engine.is_jinja2 %} | ||
{% raw %} | ||
{% extends 'base.jinja' %} | ||
|
||
{% block content %} | ||
hello | ||
<p>{{ message }}</p> | ||
<p> | ||
To demonstrate a little of the functionality of aiohttp this app implements a very simple message board. | ||
</p> | ||
<b> | ||
<a href="{{ 'messages'|url }}">View and add messages</a> | ||
</b> | ||
{% endblock %} | ||
{% endraw %} | ||
{% endif %} |
32 changes: 32 additions & 0 deletions
32
aiohttp_devtools/start/template/app/templates/messages.jinja
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
{% if template_engine.is_jinja2 %} | ||
{% raw %} | ||
{% extends 'base.jinja' %} | ||
|
||
{% block content %} | ||
<h2>Add a new message:</h2> | ||
<form method="post" action="{{ 'messages'|url }}"> | ||
{% if form_errors %} | ||
<div class="form-errors"> | ||
{{ form_errors }} | ||
</div> | ||
{% endif %} | ||
<p> | ||
<label for="username">Your name:</label> | ||
<input type="text" name="username" id="username" placeholder="fred blogs"> | ||
<label for="message">Message:</label> | ||
<input type="text" name="message" id="message" placeholder="hello there"> | ||
</p> | ||
<button type="submit">Post Message</button> | ||
</form> | ||
|
||
<h2>Messages:</h2> | ||
<ul> | ||
{% for message in messages %} | ||
<li><b>{{ message.username }}:</b> {{ message.message }}, ({{ message.timestamp }})</li> | ||
{% else %} | ||
<li>No messages found.</li> | ||
{% endfor %} | ||
</ul> | ||
{% endblock %} | ||
{% endraw %} | ||
{% endif %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,100 @@ | ||
from datetime import datetime | ||
from pathlib import Path | ||
|
||
from aiohttp import web | ||
# {% if template_engine.is_jinja %} | ||
from aiohttp.hdrs import METH_POST | ||
# {% if template_engine.is_jinja2 %} | ||
from aiohttp.web_exceptions import HTTPFound | ||
from aiohttp_jinja2 import template | ||
# {% endif %} | ||
|
||
# {% if template_engine.is_jinja %} | ||
# if no database is available we use a plain old file to store messages. Don't do this kind of thing in production! | ||
MESSAGE_FILE = Path('messages.txt') | ||
|
||
# {% if template_engine.is_jinja2 %} | ||
|
||
@template('index.jinja') | ||
async def index(request): | ||
return {'foo': 'bar'} | ||
""" | ||
This is the view handler for the "/" url. | ||
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request | ||
:return: context for the template. Not: we return a dict not a response because of the @template decorator | ||
""" | ||
return { | ||
'title': request.app['name'], | ||
'message': "Success! you've setup a basic aiohttp app.", | ||
} | ||
|
||
|
||
# {% else %} | ||
|
||
async def index(request): | ||
""" | ||
This is the view handler for the "/" url. | ||
:param request: the request object see http://aiohttp.readthedocs.io/en/stable/web_reference.html#request | ||
:return: aiohttp.web.Response object | ||
""" | ||
content = """\ | ||
<!DOCTYPE html> | ||
<head> | ||
<title>{title}</title> | ||
<link href="{styles_css}" rel="stylesheet"> | ||
</head> | ||
<body> | ||
<h1>{title}</h1> | ||
<p>{message}</p> | ||
</body>""" | ||
return web.Response(text='<body>hello</body>', content_type='text/html') | ||
# {% endif %} | ||
|
||
|
||
async def process_form(request): | ||
new_message, missing_fields = {}, [] | ||
fields = ['username', 'message'] | ||
data = await request.post() | ||
for f in fields: | ||
new_message[f] = data.get(f) | ||
if not new_message[f]: | ||
missing_fields.append(f) | ||
|
||
if missing_fields: | ||
return 'Invalid form submission, missing fields: {}'.format(', '.join(missing_fields)) | ||
|
||
# hack: this very simple storage uses "|" to split fields so we need to replace it in username | ||
new_message['username'] = new_message['username'].replace('|', '') | ||
with MESSAGE_FILE.open('a') as f: | ||
now = datetime.now().isoformat() | ||
f.write('{username}|{timestamp:%Y-%m-%d %H:%M}|{message}'.format(timestamp=now, **new_message)) | ||
raise HTTPFound(request.app.router['messages'].url()) | ||
|
||
|
||
# {% if template_engine.is_jinja2 %} | ||
@template('messages.jinja') | ||
# {% endif %} | ||
async def messages(request): | ||
if request.method == METH_POST: | ||
# the 302 redirect is processed as an exception, so if this coroutine returns there's a form error | ||
form_errors = await process_form(request) | ||
else: | ||
form_errors = None | ||
|
||
messages = [] | ||
if MESSAGE_FILE.exists(): | ||
lines = MESSAGE_FILE.read_text().split('\n') | ||
for line in reversed(lines): | ||
if not line: | ||
continue | ||
username, ts, message = line.split('|', 2) | ||
ts = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.strptime(ts, '%Y-%m-%dT%H:%M:%S.%f')) | ||
messages.append({'username': username, 'timestamp': ts, 'message': message}) | ||
# {% if template_engine.is_jinja2 %} | ||
return { | ||
'title': 'Message board', | ||
'form_errors': form_errors, | ||
'messages': messages, | ||
} | ||
# {% else %} | ||
raise NotImplementedError() | ||
# {% endif %} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
html, body { | ||
font-family: Garamond, Georgia, serif; | ||
margin: 0; | ||
} | ||
|
||
main { | ||
margin: 0 auto; | ||
max-width: 940px; | ||
background-color: white; | ||
padding: 20px 20px; | ||
} | ||
|
||
.form-errors { | ||
background-color: #f2dede; | ||
padding: 5px 10px; | ||
border: 1px solid red; | ||
border-radius: 3px; | ||
color: #79312f; | ||
} |