- commit
- 1a8ab535f5d2bc13d3824138f1794a756472b5e2
- parent
- 732a22ea275bee77b5dbb63ccf7d2e2bb3170dcd
- Author
- Tobias Bengfort <tobias.bengfort@posteo.de>
- Date
- 2023-10-03 03:44
port server to aiohttp
Diffstat
M | neddit.py | 33 | ++++++++++++++------------------- |
1 files changed, 14 insertions, 19 deletions
diff --git a/neddit.py b/neddit.py
@@ -4,11 +4,8 @@ from datetime import datetime 4 4 5 5 import requests 6 6 import jinja27 -1 from flask import Flask8 -1 from flask import request9 -1 from flask import abort-1 7 from aiohttp import web 10 811 -1 app = Flask(__name__)12 9 env = jinja2.Environment( 13 10 loader=jinja2.FileSystemLoader('templates'), 14 11 autoescape=jinja2.select_autoescape(default=True), @@ -58,14 +55,15 @@ env.filters['dash_resize'] = dash_resize 58 55 59 56 60 57 def fetch(url, **params):61 -1 app.logger.debug('fetch %s' % url)62 58 r = requests.get( 63 59 url, 64 60 headers={'User-agent': 'neddit'}, 65 61 params={**params, 'raw_json': 1}, 66 62 ) 67 63 if r.status_code != 200:68 -1 abort(r.status_code)-1 64 if r.status == 404: -1 65 raise web.HTTPNotFound -1 66 r.raise_for_status() 69 67 return r.json() 70 68 71 69 @@ -74,17 +72,17 @@ def fetch_subreddit(name): 74 72 return fetch('https://www.reddit.com/r/%s/about.json' % name) 75 73 76 7477 -1 @app.route('/<path:path>/')78 -1 def generic(path):-1 75 async def generic(request): -1 76 path = request.match_info['path'] or 'hot' 79 77 context = {80 -1 'params': request.args,-1 78 'params': request.query, 81 79 } 82 80 83 81 if path.startswith('r/'): 84 82 subreddit = path.split('/')[1] 85 83 context['subreddit'] = fetch_subreddit(subreddit) 86 8487 -1 a = fetch('https://www.reddit.com/%s/.json' % path, **request.args)-1 85 a = fetch('https://www.reddit.com/%s/.json' % path, **request.query) 88 86 if isinstance(a, list): 89 87 tpl = env.get_template('comments.html') 90 88 context['post'] = a[0]['data']['children'][0] @@ -93,14 +91,11 @@ def generic(path): 93 91 tpl = env.get_template('listing.html') 94 92 context.update(a) 95 9396 -1 return tpl.render(**context)-1 94 return web.Response(body=tpl.render(**context), content_type='text/html') 97 95 98 9699 -1 @app.route('/')100 -1 def root():101 -1 return generic('hot')102 -1103 -1104 -1 @app.route('/favicon.ico')105 -1 def favicon():106 -1 return '', 404-1 97 def create_app(argv=[]): -1 98 app = web.Application() -1 99 app.router.add_static('/static', 'static') -1 100 app.router.add_route('GET', '/{path:.*}', generic) -1 101 return app