Skip to content
This repository has been archived by the owner on Mar 16, 2020. It is now read-only.

Commit

Permalink
much improved 404 handling
Browse files Browse the repository at this point in the history
  • Loading branch information
peterbe committed Nov 7, 2011
1 parent c775009 commit a39bc5b
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
5 changes: 5 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ def __init__(self, database_name=None):
twitter_consumer_key=settings.TWITTER_CONSUMER_KEY,
twitter_consumer_secret=settings.TWITTER_CONSUMER_SECRET,
)
if 1 or not options.debug:
routed_handlers.append(
tornado.web.url('/.*?', handlers.PageNotFoundHandler,
name='page_not_found')
)
super(Application, self).__init__(routed_handlers, **app_settings)

self.redis = redis.client.Redis(settings.REDIS_HOST,
Expand Down
13 changes: 13 additions & 0 deletions handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,3 +936,16 @@ class LookupsJSONHandler(LookupsHandler):
def get(self):
data = self.get_lookups()
self.write_json(data)

# this handler gets automatically appended last to all handlers inside app.py
class PageNotFoundHandler(BaseHandler):

def get(self):
path = self.request.path
if not path.endswith('/'):
new_url = '%s/' % path
if self.request.query:
new_url += '?%s' % self.request.query
self.redirect(new_url)
return
raise HTTPError(404, path)
11 changes: 11 additions & 0 deletions tests/test_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -830,6 +830,17 @@ def test_suggest_tweet(self):
#self.assertTrue(struct['text'].endswith('#toocool'))
self.assertTrue('@peterbestwin' in struct['text'])

def test_default_page_not_found(self):
url = '/does/not/exist'
response = self.client.get(url)
self.assertEqual(response.code, 302)
self.assertEqual(response.headers['location'], '/does/not/exist/')

url = '/does/not/exist/'
response = self.client.get(url)
self.assertEqual(response.code, 404)
self.assertTrue('restart your computer' in response.body)

def make_twitter_get_authenticated_user_callback(struct):
def twitter_get_authenticated_user(self, callback, **kw):
callback(struct)
Expand Down

0 comments on commit a39bc5b

Please sign in to comment.