askrobots / dbbasic-examples
Public
Example DBBasic apps (an API, a blog and a microblog) and a template for new DBBasic modules.
danq9
Add official module template for creating DBBasic packages
17cf88a
1 year, 1 month ago
History
api.py · 1.1 KB · 35 lines
| 1 | from dbbasic.tsv import TSV |
| 2 | from dbbasic_web.responses import html |
| 3 | from dbbasic_web.templating import render |
| 4 | from dbbasic_sessions import get_session |
| 5 | from dbbasic_accounts import Accounts |
| 6 | |
| 7 | accounts = Accounts('.', domain='localhost') |
| 8 | posts = TSV("posts", ["id", "username", "content", "created"]) |
| 9 | follows = TSV("follows", ["follower", "following", "created"]) |
| 10 | |
| 11 | def get_current_user(request): |
| 12 | token = request.cookie('session') |
| 13 | if not token: |
| 14 | return None |
| 15 | user_id = get_session(token) |
| 16 | if not user_id: |
| 17 | return None |
| 18 | return accounts.get_user(user_id=int(user_id)) |
| 19 | |
| 20 | def handle(request): |
| 21 | user = get_current_user(request) |
| 22 | |
| 23 | if not user: |
| 24 | return html(render('welcome.html')) |
| 25 | |
| 26 | all_posts = list(posts.all()) |
| 27 | all_posts.reverse() |
| 28 | |
| 29 | following_list = [f['following'] for f in follows.query(follower=user.username)] |
| 30 | timeline_posts = [p for p in all_posts if p['username'] in following_list or p['username'] == user.username] |
| 31 | |
| 32 | if not timeline_posts: |
| 33 | timeline_posts = all_posts[:20] |
| 34 | |
| 35 | return html(render('index.html', user=user, posts=timeline_posts[:50])) |