This repository has been archived by the owner on Jun 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
app.py
106 lines (87 loc) · 2.85 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/env python3
import aiohttp_jinja2
import aioredis
import jinja2
import os
from aiohttp import web
from datetime import datetime
from subconscious.model import RedisModel, Column
from uuid import uuid4
# For simplicity all of this is in one file
# Typically, you'd pull a lot of this out into models.py, views.py and perhaps even forms.py
class Paste(RedisModel):
uuid = Column(type=str, primary_key=True)
created_at = Column(type=str, required=True, sort=True)
title = Column(type=str, required=True)
body = Column(type=str, required=True)
@aiohttp_jinja2.template('index.jinja2')
async def index(request):
recent_pastes = [x async for x in Paste.all(
db=request.app['db'],
order_by='-created_at',
limit=5)
]
return {'recent_pastes': recent_pastes}
@aiohttp_jinja2.template('get_paste.jinja2')
async def get_paste(request):
uuid = request.match_info.get('uuid')
if not uuid:
return {}
paste_obj = await Paste.get_object_or_none(
db=request.app['db'],
uuid=uuid,
)
if paste_obj:
# Render the page
return {'paste_obj': paste_obj.as_dict()}
else:
# Redirect to homepage
return web.HTTPFound('/')
@aiohttp_jinja2.template('save_paste.jinja2')
async def save_paste(request):
post_data = await request.post()
if post_data:
title = post_data.get('title')
body = post_data.get('body', '')
if title:
paste_obj = Paste(
uuid=str(uuid4()),
created_at=str(datetime.utcnow().isoformat()),
title=title,
body=body,
)
await paste_obj.save(request.app['db'])
# redirect to paste page
return web.HTTPFound('/pastes/{}'.format(paste_obj.uuid))
return {}
async def flush_db(request):
""" Undocumented endpoint to wipe the DB """
await request.app['db'].flushdb()
return web.HTTPFound('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
async def init_app(app):
app['db'] = await aioredis.create_redis(
address=(
os.getenv('REDIS_HOST', 'redis'),
int(os.getenv('REDIS_PORT', 6379))
),
db=int(os.getenv('REDIS_DB', 1)),
loop=None,
encoding='utf-8',
)
# flush the DB (not very production safe):
await app['db'].flushdb()
return app
def create_app():
app = web.Application()
app.on_startup.append(init_app)
app.router.add_get('/', index)
app.router.add_route('*', '/pastes', save_paste)
app.router.add_get('/pastes/{uuid}', get_paste)
app.router.add_get('/flush', flush_db)
templates_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates')
aiohttp_jinja2.setup(
app,
loader=jinja2.FileSystemLoader(templates_dir),
autoescape=True,
)
return app