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
profile.py · 1.6 KB · 47 lines
| 1 | from dbbasic.tsv import TSV |
| 2 | from dbbasic_web.responses import html, json_error |
| 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 | username = request.path_param(1) |
| 22 | if not username: |
| 23 | return json_error("Invalid path", status=404) |
| 24 | |
| 25 | current_user = get_current_user(request) |
| 26 | profile_user = accounts.get_user(username=username) |
| 27 | |
| 28 | if not profile_user: |
| 29 | return json_error("User not found", status=404) |
| 30 | |
| 31 | user_posts = list(posts.query(username=username)) |
| 32 | user_posts.reverse() |
| 33 | |
| 34 | is_following = False |
| 35 | if current_user: |
| 36 | is_following = follows.query_one(follower=current_user.username, following=username) is not None |
| 37 | |
| 38 | follower_count = follows.count(following=username) |
| 39 | following_count = follows.count(follower=username) |
| 40 | |
| 41 | return html(render('profile.html', |
| 42 | current_user=current_user, |
| 43 | profile_user=profile_user, |
| 44 | posts=user_posts, |
| 45 | is_following=is_following, |
| 46 | follower_count=follower_count, |
| 47 | following_count=following_count)) |