forked from liberapay/liberapay.com
/
__init__.py
49 lines (38 loc) · 1.58 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from __future__ import print_function, unicode_literals
from mimetypes import guess_type
from . import constants
# canonizer
# =========
# This is an Aspen hook to ensure that requests are served on a certain root
# URL, even if multiple domains point to the application.
class X: pass
canonical_scheme = None
canonical_host = None
def canonize(request, website):
"""Enforce a certain scheme and hostname.
"""
scheme = request.headers.get('X-Forwarded-Proto', 'http') # per Heroku
host = request.headers['Host']
bad_scheme = scheme != canonical_scheme
bad_host = bool(canonical_host) and (host != canonical_host)
# '' and False => ''
if bad_scheme or bad_host:
url = '%s://%s' % (canonical_scheme, canonical_host)
if request.line.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
# Redirect to a particular path for idempotent methods.
url += request.line.uri.path.raw
if request.line.uri.querystring:
url += '?' + request.line.uri.querystring.raw
else:
# For non-idempotent methods, redirect to homepage.
url += '/'
website.redirect(url)
def insert_constants():
return {'constants': constants}
def fill_accept_header(state, request, accept_header):
"""Work around aspen's content negotiation weirdness
This sets `accept_header` to `application/json` when the requested URL ends
in `.json` and the `Accept` header is missing.
"""
if not accept_header:
state['accept_header'] = guess_type(request.path.raw, strict=False)[0]