Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove request.website #386

Merged
merged 6 commits into from
Oct 3, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
75 changes: 53 additions & 22 deletions aspen/dispatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,15 @@ def get_wildleaf_fallback():

# check all the possibilities:
# node.html, node.html.spt, node.spt, node.html/, %node.html/ %*.html.spt, %*.spt
subnodes = set([ n for n in listnodes(curnode) if not n.startswith('.') ]) # don't serve hidden files

# don't serve hidden files
subnodes = set([ n for n in listnodes(curnode) if not n.startswith('.') ])

node_noext, node_ext = splitext(node)

maybe_wild_nodes = [ n for n in sorted(subnodes) if n.startswith("%") ] # only maybe because non-spt files aren't wild
# only maybe because non-spt files aren't wild
maybe_wild_nodes = [ n for n in sorted(subnodes) if n.startswith("%") ]

wild_leaf_ns = [ n for n in maybe_wild_nodes if is_leaf_node(n) and is_spt(n) ]
wild_nonleaf_ns = [ n for n in maybe_wild_nodes if not is_leaf_node(n) ]

Expand All @@ -132,7 +137,8 @@ def get_wildleaf_fallback():
if node == '': # dir request
debug(lambda: "...last node is empty")
path_so_far = traverse(curnode, node)
# return either an index file or have the path end in '/' which means 404 or autoindex as appropriate
# return either an index file or have the path end in '/' which means 404 or
# autoindex as appropriate
found_n = find_index(path_so_far)
if found_n is None:
found_n = ""
Expand All @@ -145,13 +151,19 @@ def get_wildleaf_fallback():
elif node in subnodes and is_leaf_node(node):
debug(lambda: "...found exact file, must be static")
if is_spt(node):
return DispatchResult(DispatchStatus.missing, None, None, "Node %r Not Found" % node)
return DispatchResult( DispatchStatus.missing
, None
, None
, "Node %r Not Found" % node
)
else:
found_n = node
elif node + ".spt" in subnodes and is_leaf_node(node + ".spt"):
debug(lambda: "...found exact spt")
found_n = node + ".spt"
elif node_noext + ".spt" in subnodes and is_leaf_node(node_noext + ".spt") and node_ext: # node has an extension
elif node_noext + ".spt" in subnodes and is_leaf_node(node_noext + ".spt") \
and node_ext:
# node has an extension
debug(lambda: "...found indirect spt")
# indirect match
noext_matched(node)
Expand All @@ -166,16 +178,28 @@ def get_wildleaf_fallback():
curnode = traverse(curnode, found_n)
result = get_wildleaf_fallback()
if not result:
return DispatchResult(DispatchStatus.non_leaf, curnode, None, "Tried to access non-leaf node as leaf.")
return DispatchResult( DispatchStatus.non_leaf
, curnode
, None
, "Tried to access non-leaf node as leaf."
)
return result
elif node in subnodes:
debug(lambda: "exact dirmatch")
return DispatchResult(DispatchStatus.non_leaf, curnode, None, "Tried to access non-leaf node as leaf.")
return DispatchResult( DispatchStatus.non_leaf
, curnode
, None
, "Tried to access non-leaf node as leaf."
)
else:
debug(lambda: "fallthrough")
result = get_wildleaf_fallback()
if not result:
return DispatchResult(DispatchStatus.missing, None, None, "Node %r Not Found" % node)
return DispatchResult( DispatchStatus.missing
, None
, None
, "Node %r Not Found" % node
)
return result

if not last_node: # not at last path seg in request
Expand All @@ -185,7 +209,8 @@ def get_wildleaf_fallback():
debug(lambda: "Exact match " + repr(node))
curnode = traverse(curnode, found_n)
elif wild_nonleaf_ns:
# need to match a wildnode, and we're not the last node, so we should match non-leaf first, then leaf
# need to match a wildnode, and we're not the last node, so we should match
# non-leaf first, then leaf
found_n = wild_nonleaf_ns[0]
wildvals[found_n[1:]] = node
debug(lambda: "Wildcard match %r = %r " % (found_n, node))
Expand All @@ -194,7 +219,11 @@ def get_wildleaf_fallback():
debug(lambda: "No exact match for " + repr(node))
result = get_wildleaf_fallback()
if not result:
return DispatchResult(DispatchStatus.missing, None, None, "Node %r Not Found" % node)
return DispatchResult( DispatchStatus.missing
, None
, None
, "Node %r Not Found" % node
)
return result

return DispatchResult(DispatchStatus.okay, curnode, wildvals, "Found.")
Expand All @@ -219,15 +248,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 +274,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 +295,12 @@ 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 +316,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 +336,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
Loading