Skip to content

Commit

Permalink
Merge pull request #385 from gratipay/media_type_default
Browse files Browse the repository at this point in the history
remove request.website
  • Loading branch information
pjz committed Oct 3, 2014
2 parents 27d1b24 + 7bb786d commit 0f60003
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 48 deletions.
15 changes: 5 additions & 10 deletions aspen/algorithms/website.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,27 +54,22 @@ def parse_body_into_request(request, website):
)


def tack_website_onto_request(request, website):
# XXX Why?
request.website = website


def raise_200_for_OPTIONS(request):
"""A hook to return 200 to an 'OPTIONS *' request"""
if request.line.method == "OPTIONS" and request.line.uri == "*":
raise Response(200)


def dispatch_request_to_filesystem(request):
dispatcher.dispatch(request)
def dispatch_request_to_filesystem(website, request):
dispatcher.dispatch(website, request)


def apply_typecasters_to_path(website, request):
typecasting.apply_typecasters(website.typecasters, request.line.uri.path)


def get_resource_for_request(request):
return {'resource': resources.get(request)}
def get_resource_for_request(website, request):
return {'resource': resources.get(website, request)}


def get_response_for_resource(request, resource=None):
Expand Down Expand Up @@ -116,7 +111,7 @@ def delegate_error_to_simplate(website, request, response, resource=None):
if resource is not None:
# Try to return an error that matches the type of the original resource.
request.headers['Accept'] = resource.media_type + ', text/plain; q=0.1'
resource = resources.get(request)
resource = resources.get(website, request)
try:
response = resource.respond(request, response)
except Response as response:
Expand Down
24 changes: 12 additions & 12 deletions aspen/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,15 +219,15 @@ def is_first_index(indices, basedir, name):
return False


def update_neg_type(request, filename):
def update_neg_type(website, request, filename):
media_type = mimetypes.guess_type(filename, strict=False)[0]
if media_type is None:
media_type = request.website.media_type_default
media_type = website.media_type_default
request.headers['X-Aspen-Accept'] = media_type
debug(lambda: "set x-aspen-accept to %r" % media_type)


def dispatch(request, pure_dispatch=False):
def dispatch(website, request, pure_dispatch=False):
"""Concretize dispatch_abstract.
This is all side-effecty on the request object, setting, at the least,
Expand All @@ -245,9 +245,9 @@ def dispatch(request, pure_dispatch=False):
listnodes = os.listdir
is_leaf = os.path.isfile
traverse = os.path.join
find_index = lambda x: match_index(request.website.indices, x)
noext_matched = lambda x: update_neg_type(request, x)
startdir = request.website.www_root
find_index = lambda x: match_index(website.indices, x)
noext_matched = lambda x: update_neg_type(website, request, x)
startdir = website.www_root

# Dispatch!
# =========
Expand All @@ -266,10 +266,10 @@ def dispatch(request, pure_dispatch=False):
if result.match:
debug(lambda: "result.match is true" )
matchbase, matchname = result.match.rsplit(os.path.sep,1)
if pathparts[-1] != '' and matchname in request.website.indices and \
is_first_index(request.website.indices, matchbase, matchname):
if pathparts[-1] != '' and matchname in website.indices and \
is_first_index(website.indices, matchbase, matchname):
# asked for something that maps to a default index file; redirect to / per issue #175
debug(lambda: "found default index '%s' maps into %r" % (pathparts[-1], request.website.indices))
debug(lambda: "found default index '%s' maps into %r" % (pathparts[-1], website.indices))
uri = request.line.uri
location = uri.path.raw[:-len(pathparts[-1])]
if uri.querystring.raw:
Expand All @@ -285,7 +285,7 @@ def dispatch(request, pure_dispatch=False):
if request.line.uri.path.raw == '/favicon.ico':
if result.status != DispatchStatus.okay:
path = request.line.uri.path.raw[1:]
request.fs = request.website.find_ours(path)
request.fs = website.find_ours(path)
return


Expand All @@ -305,9 +305,9 @@ def dispatch(request, pure_dispatch=False):

if result.status == DispatchStatus.okay:
if result.match.endswith('/'): # autoindex
if not request.website.list_directories:
if not website.list_directories:
raise Response(404)
autoindex = request.website.ours_or_theirs('autoindex.html.spt')
autoindex = website.ours_or_theirs('autoindex.html.spt')
assert autoindex is not None # sanity check
request.headers['X-Aspen-AutoIndexDir'] = result.match
request.fs = autoindex
Expand Down
13 changes: 7 additions & 6 deletions aspen/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def get_declaration(line):
# Core loaders
# ============

def load(request, mtime):
def load(website, request, mtime):
"""Given a Request and a mtime, return a Resource object (w/o caching).
"""

Expand All @@ -139,7 +139,7 @@ def load(request, mtime):
guess_with = guess_with[:-4]
fs_media_type = mimetypes.guess_type(guess_with, strict=False)[0]
if fs_media_type is None:
media_type = request.website.media_type_default
media_type = website.media_type_default
else:
media_type = fs_media_type

Expand All @@ -154,14 +154,15 @@ def load(request, mtime):
else: # negotiated
Class = NegotiatedResource

resource = Class(request.website, request.fs, raw, media_type, mtime)
resource = Class(website, request.fs, raw, media_type, mtime)
return resource


def get(request):
def get(website, request):
"""Given a Request, return a Resource object (with caching).
We need the request because it carries media_type_default.
We need the request to pass through to the Resource constructor. That's
where it's placed into the simplate execution context.
"""

Expand All @@ -188,7 +189,7 @@ def get(request):
raise entry.exc
else: # cache miss
try:
entry.resource = load(request, mtime)
entry.resource = load(website, request, mtime)
except: # capture any Exception
entry.exc = (LoadError(traceback.format_exc())
, sys.exc_info()[2]
Expand Down
4 changes: 2 additions & 2 deletions aspen/www/autoindex.html.spt
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _get_time(stats):
fspath = request.headers.get('X-Aspen-AutoIndexDir', os.path.dirname(__file__))
assert os.path.isdir(fspath) # sanity check

urlpath = fspath[len(request.website.www_root):] + os.sep
urlpath = fspath[len(website.www_root):] + os.sep
urlpath = '/'.join(urlpath.split(os.sep))
title = urlpath and urlpath or '/'

Expand Down Expand Up @@ -90,7 +90,7 @@ dirs.sort()
files.sort()
others.sort()

updir = "" if fspath == request.website.www_root else """
updir = "" if fspath == website.www_root else """
<tr>
<td class="odd"><a href="../">../</a></td>
<td>&nbsp;</td>
Expand Down
2 changes: 1 addition & 1 deletion aspen/www/error.spt
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ except ImportError:
style = ''
msg = status_strings.get(response.code, 'Sorry')
msg = msg[0].upper() + msg[1:].lower()
if request.website.show_tracebacks:
if website.show_tracebacks:
err_ascii = response.body
if pygmentize:
# Pygments does HTML escaping
Expand Down
4 changes: 2 additions & 2 deletions doc/.aspen/aspen_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
opts = {} # populate this in configure-aspen.py


def add_stuff_to_request_context(request):
def add_stuff_to_request_context(website, request):

# Define some closures for generating image markup.
# =================================================

def translate(src):
if src[0] != '/':
rel = dirname(request.fs)[len(request.website.www_root):]
rel = dirname(request.fs)[len(website.www_root):]
src = '/'.join([rel, src])
src = opts['base'] + src
return src
Expand Down
30 changes: 15 additions & 15 deletions tests/test_negotiated_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ def test_get_renderer_factory_can_raise_syntax_error(get):

# get_response

def get_response(request, response):
def get_response(website, request, response):
context = { 'request': request
, 'response': response
}
resource = resources.load(request, 0)
resource = resources.load(website, request, 0)
return resource.get_response(context)

NEGOTIATED_RESOURCE = """\
Expand All @@ -129,49 +129,49 @@ def test_get_response_gets_response(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
response = Response()
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
actual = get_response(request, response)
actual = get_response(harness.client.website, request, response)
assert actual is response

def test_get_response_is_happy_not_to_negotiate(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
actual = get_response(request, Response()).body
actual = get_response(harness.client.website, request, Response()).body
assert actual == "Greetings, program!\n"

def test_get_response_sets_content_type_when_it_doesnt_negotiate(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
actual = get_response(request, Response()).headers['Content-Type']
actual = get_response(harness.client.website, request, Response()).headers['Content-Type']
assert actual == "text/plain; charset=UTF-8"

def test_get_response_doesnt_reset_content_type_when_not_negotiating(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
response = Response()
response.headers['Content-Type'] = 'never/mind'
actual = get_response(request, response).headers['Content-Type']
actual = get_response(harness.client.website, request, response).headers['Content-Type']
assert actual == "never/mind"

def test_get_response_negotiates(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'text/html'
actual = get_response(request, Response()).body
actual = get_response(harness.client.website, request, Response()).body
assert actual == "<h1>Greetings, program!</h1>\n"

def test_handles_busted_accept(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
# Set an invalid Accept header so it will return default (text/plain)
request.headers['Accept'] = 'text/html;'
actual = get_response(request, Response()).body
actual = get_response(harness.client.website, request, Response()).body
assert actual == "Greetings, program!\n"

def test_get_response_sets_content_type_when_it_negotiates(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'text/html'
actual = get_response(request, Response()).headers['Content-Type']
actual = get_response(harness.client.website, request, Response()).headers['Content-Type']
assert actual == "text/html; charset=UTF-8"

def test_get_response_doesnt_reset_content_type_when_negotiating(harness):
Expand All @@ -180,24 +180,24 @@ def test_get_response_doesnt_reset_content_type_when_negotiating(harness):
request.headers['Accept'] = 'text/html'
response = Response()
response.headers['Content-Type'] = 'never/mind'
actual = get_response(request, response).headers['Content-Type']
actual = get_response(harness.client.website, request, response).headers['Content-Type']
response = Response()
response.headers['Content-Type'] = 'never/mind'
actual = get_response(request, response).headers['Content-Type']
actual = get_response(harness.client.website, request, response).headers['Content-Type']
assert actual == "never/mind"

def test_get_response_raises_406_if_need_be(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'cheese/head'
actual = raises(Response, get_response, request, Response()).value.code
actual = raises(Response, get_response, harness.client.website, request, Response()).value.code
assert actual == 406

def test_get_response_406_gives_list_of_acceptable_types(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'cheese/head'
actual = raises(Response, get_response, request, Response()).value.body
actual = raises(Response, get_response, harness.client.website, request, Response()).value.body
expected = "The following media types are available: text/plain, text/html."
assert actual == expected

Expand All @@ -223,14 +223,14 @@ def test_can_override_default_renderers_by_mimetype(harness):
harness.fs.www.mk(('index.spt', NEGOTIATED_RESOURCE),)
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'text/plain'
actual = get_response(request, Response()).body
actual = get_response(harness.client.website, request, Response()).body
assert actual == "glubber"

def test_can_override_default_renderer_entirely(harness):
harness.fs.project.mk(('configure-aspen.py', OVERRIDE_SIMPLATE))
request = harness.make_request(filepath='index.spt', contents=NEGOTIATED_RESOURCE)
request.headers['Accept'] = 'text/plain'
actual = get_response(request, Response()).body
actual = get_response(harness.client.website, request, Response()).body
assert actual == "glubber"


Expand Down

0 comments on commit 0f60003

Please sign in to comment.