flask: move app to app.py, get templates working, port /responses

flask
Ryan Barrett 2021-07-07 08:07:20 -07:00
rodzic 86a4afdc97
commit 0b7388fed3
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 6BE31FDF4776E9D4
8 zmienionych plików z 48 dodań i 57 usunięć

1
.gitignore vendored
Wyświetl plik

@ -2,6 +2,7 @@
/.well-known/acme-challenge/
datastore.dat*
/docs/_build/
flask_secret_key
/l
/local*
private_notes

35
app.py
Wyświetl plik

@ -1,23 +1,18 @@
"""Main WSGI application. Just URL routes to the other modules."""
import importlib
"""Main Flask application."""
from flask import Flask
from flask_caching import Cache
from oauth_dropins.webutil import appengine_info, appengine_config, handlers, util
from oauth_dropins.webutil import appengine_info, appengine_config, handlers
import webapp2
app = Flask('bridgy-fed')
app.template_folder = './templates'
app.config.from_mapping(
ENV='development' if appengine_info.DEBUG else 'PRODUCTION',
CACHE_TYPE='SimpleCache',
SECRET_KEY=util.read('flask_secret_key'),
)
app.wsgi_app = handlers.ndb_context_middleware(
app.wsgi_app, client=appengine_config.ndb_client)
cache = Cache(app)
routes = []
for module in (
'activitypub',
'add_webmention',
'logs',
'redirect',
'salmon',
'superfeedr',
'webfinger',
'webmention',
):
routes += importlib.import_module(module).ROUTES
application = handlers.ndb_context_middleware(
webapp2.WSGIApplication(routes, debug=appengine_info.DEBUG),
client=appengine_config.ndb_client)
import activitypub, add_webmention, logs, redirect, render, salmon, superfeedr, webfinger, webmention

Wyświetl plik

@ -8,7 +8,7 @@ runtime: python39
# https://cloud.google.com/appengine/docs/standard/python3/runtime#entrypoint_best_practices
# https://docs.gunicorn.org/en/latest/settings.html#timeout
entrypoint: gunicorn --workers 1 --threads 10 --timeout 60 -b :$PORT render:app
entrypoint: gunicorn --workers 1 --threads 10 --timeout 60 -b :$PORT app:app
# background: https://github.com/snarfed/bridgy/issues/578
# https://github.com/snarfed/bridgy/issues/1051

Wyświetl plik

@ -67,6 +67,10 @@ DOMAINS = (PRIMARY_DOMAIN,) + OTHER_DOMAINS
canonicalize_domain = handlers.redirect(OTHER_DOMAINS, PRIMARY_DOMAIN)
def not_5xx(resp):
return isinstance(resp, tuple) and resp[1] // 100 != 5
def requests_get(url, **kwargs):
return _requests_fn(util.requests_get, url, **kwargs)

Wyświetl plik

@ -1,2 +1,8 @@
indexes:
# AUTOGENERATED
# This index.yaml is automatically updated whenever the Cloud Datastore
# emulator detects that a new type of query is run. If you want to manage the
# index.yaml file manually, remove the "# AUTOGENERATED" marker line above.
# If you want to manage some indexes manually, move them above the marker line.

35
logs.py
Wyświetl plik

@ -1,13 +1,12 @@
"""Render recent responses and logs."""
import calendar
import datetime
import urllib.parse
from flask import render_template
from oauth_dropins.webutil import util
from oauth_dropins.webutil.handlers import TemplateHandler
from oauth_dropins.webutil import logs
import webapp2
from app import app
from models import Response
@ -15,29 +14,23 @@ class LogHandler(logs.LogHandler):
VERSION_IDS = ['1']
class ResponsesHandler(TemplateHandler):
@app.route('/responses')
def responses():
"""Renders recent Responses, with links to logs."""
responses = Response.query().order(-Response.updated).fetch(20)
def template_file(self):
return 'templates/responses.html'
for r in responses:
r.source_link = util.pretty_link(r.source())
r.target_link = util.pretty_link(r.target())
r.log_url_path = '/log?' + urllib.parse.urlencode({
'key': r.key.id(),
'start_time': calendar.timegm(r.updated.timetuple()),
})
def template_vars(self):
responses = Response.query().order(-Response.updated).fetch(20)
for r in responses:
r.source_link = util.pretty_link(r.source())
r.target_link = util.pretty_link(r.target())
r.log_url_path = '/log?' + urllib.parse.urlencode({
'key': r.key.id(),
'start_time': calendar.timegm(r.updated.timetuple()),
})
return {
'responses': responses,
}
print(f'@ {app.root_path} {app.template_folder} {app.jinja_loader.searchpath} {repr(app.jinja_loader)}')
return render_template('responses.html', responses=responses)
ROUTES = [
('/log', LogHandler),
('/responses', ResponsesHandler),
]

Wyświetl plik

@ -2,32 +2,22 @@
"""Renders mf2 proxy pages based on stored Responses."""
import datetime
from flask import Flask, request
from flask_caching import Cache
from flask import request
from granary import as2, atom, microformats2
from oauth_dropins.webutil import appengine_config, handlers
from oauth_dropins.webutil.util import json_loads
from app import app, cache
import common
from models import Response
CACHE_TIME = datetime.timedelta(minutes=15)
app = Flask('bridgy-fed')
app.config.from_mapping({'CACHE_TYPE': 'SimpleCache'})
app.wsgi_app = handlers.ndb_context_middleware(
app.wsgi_app, client=appengine_config.ndb_client)
cache = Cache(app)
def not_5xx(resp):
return isinstance(resp, tuple) and resp[1] // 100 != 5
@app.route('/render')
@cache.cached(timeout=CACHE_TIME.total_seconds(), query_string=True,
response_filter=not_5xx)
response_filter=common.not_5xx)
def render():
"""Fetches a stored Response and renders it as HTML."""
source = common.get_required_param(request, 'source')
target = common.get_required_param(request, 'target')

Wyświetl plik

@ -2,8 +2,9 @@
"""Unit tests for render.py."""
from oauth_dropins.webutil.util import json_dumps
from app import app, cache
from models import Response
from render import app, cache
import render
from . import testutil
client = app.test_client()
@ -13,6 +14,7 @@ class RenderTest(testutil.TestCase):
def setUp(self):
super(RenderTest, self).setUp()
app.testing = True
cache.clear()
self.as2 = {
'@context': 'https://www.w3.org/ns/activitystreams',