Created
August 3, 2017 06:31
-
-
Save IlyaSkriblovsky/37f10b975e13176aabaf9767ad8ea648 to your computer and use it in GitHub Desktop.
yet another approach to composable Klein apps
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
from twisted.internet import defer | |
from klein import Klein | |
from mocked_db import Database | |
def users_aspect(app: Klein, db: Database): | |
@app.route('/') | |
@defer.inlineCallbacks | |
def users_list(request): | |
users = yield db.load_users() | |
return ''.join( | |
'<a href="{}">{}</a><br/>\n'.format( | |
app.url_for(request, user_page.__name__, {'id': user.id}), | |
user.name | |
) | |
for user in users | |
) | |
@app.route('/<id>', endpoint='user_page') | |
@defer.inlineCallbacks | |
def user_page(request, id): | |
user = yield db.user_by_id(int(id)) | |
return "<h1>Welcome to {}'s page</h1>\n".format(user.name) | |
def posts_aspect(app: Klein, db: Database): | |
@app.route('/') | |
@defer.inlineCallbacks | |
def posts_list(request): | |
posts = yield db.load_posts() | |
return ''.join( | |
'<a href="{}">{}</a><br/>\n'.format( | |
app.url_for(request, view_post.__name__, {'id': post.id}), | |
post.title | |
) | |
for post in posts | |
) | |
@app.route('/<id>') | |
@defer.inlineCallbacks | |
def view_post(request, id): | |
post = yield db.post_by_id(int(id)) | |
signature = '<p>by <a href="{}">{}</a></p>'.format( | |
app.url_for(request, 'user_page', {'id': post.user.id}), | |
post.user.name | |
) | |
return '<h1>{}</h1>{}{}'.format(post.title, post.body, signature) | |
db = Database() | |
app = Klein() | |
with app.subroute('/users'): | |
users_aspect(app, db) | |
with app.subroute('/posts'): | |
posts_aspect(app, db) | |
app.run('localhost', 8080) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment