Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(99)

Side by Side Diff: chrome/common/extensions/docs/server2/render_servlet.py

Issue 14273035: Docserver: refactor the Handler/ServerInstance relationship into a servlet (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: done Created 7 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 from fnmatch import fnmatch
6 import logging
7 import mimetypes
8 import os
9 import traceback
10
11 from appengine_wrappers import IsDevServer
12 from branch_utility import BranchUtility
13 from file_system import FileNotFoundError
14 from server_instance import ServerInstance
15 from servlet import Servlet, Response
16 import svn_constants
17
18 _DEFAULT_CHANNEL = 'stable'
19
20 _ALWAYS_ONLINE = IsDevServer()
21
22 def _IsBinaryMimetype(mimetype):
23 return any(mimetype.startswith(prefix)
24 for prefix in ['audio', 'image', 'video'])
25
26 def AlwaysOnline(fn):
27 '''A function decorator which forces the rendering to be always online rather
28 than the default offline behaviour. Useful for testing.
29 '''
30 def impl(*args, **optargs):
31 global _ALWAYS_ONLINE
32 was_always_online = _ALWAYS_ONLINE
33 try:
34 _ALWAYS_ONLINE = True
35 return fn(*args, **optargs)
36 finally:
37 _ALWAYS_ONLINE = was_always_online
38 return impl
39
40 class RenderServlet(Servlet):
41 '''Servlet which renders templates.
42 '''
43 def Get(self, server_instance=None):
44 path_with_channel, headers = (self._request.path.lstrip('/'),
45 self._request.headers)
46
47 # Redirect "extensions" and "extensions/" to "extensions/index.html", etc.
48 if (os.path.splitext(path_with_channel)[1] == '' and
49 path_with_channel.find('/') == -1):
50 path_with_channel += '/'
51 if path_with_channel.endswith('/'):
52 return Response.Redirect(path_with_channel + 'index.html')
53
54 channel, path = BranchUtility.SplitChannelNameFromPath(path_with_channel)
55
56 if channel == _DEFAULT_CHANNEL:
57 return Response.Redirect('/%s' % path)
58
59 if channel is None:
60 channel = _DEFAULT_CHANNEL
61
62 # AppEngine instances should never need to call out to SVN. That should
63 # only ever be done by the cronjobs, which then write the result into
64 # DataStore, which is as far as instances look. To enable this, crons can
65 # pass a custom (presumably online) ServerInstance into Get().
66 #
67 # Why? SVN is slow and a bit flaky. Cronjobs failing is annoying but
68 # temporary. Instances failing affects users, and is really bad.
69 #
70 # Anyway - to enforce this, we actually don't give instances access to SVN.
71 # If anything is missing from datastore, it'll be a 404. If the cronjobs
72 # don't manage to catch everything - uhoh. On the other hand, we'll figure
73 # it out pretty soon, and it also means that legitimate 404s are caught
74 # before a round trip to SVN.
75 if server_instance is None:
76 # The ALWAYS_ONLINE thing is for tests and preview.py that shouldn't need
77 # to run the cron before rendering things.
78 constructor = (ServerInstance.CreateOnline if _ALWAYS_ONLINE else
79 ServerInstance.GetOrCreateOffline)
80 server_instance = constructor(channel)
81
82 canonical_path = server_instance.path_canonicalizer.Canonicalize(path)
83 if path != canonical_path:
84 return self.Redirect(canonical_path if channel is None else
85 '%s/%s' % (channel, canonical_path))
86
87 templates = server_instance.template_data_source_factory.Create(
88 self._request, path)
89
90 content = None
91 content_type = None
92
93 try:
94 if fnmatch(path, 'extensions/examples/*.zip'):
95 content = server_instance.example_zipper.Create(
96 path[len('extensions/'):-len('.zip')])
97 content_type = 'application/zip'
98 elif path.startswith('extensions/examples/'):
99 mimetype = mimetypes.guess_type(path)[0] or 'text/plain'
100 content = server_instance.content_cache.GetFromFile(
101 '%s/%s' % (svn_constants.DOCS_PATH, path[len('extensions/'):]),
102 binary=_IsBinaryMimetype(mimetype))
103 content_type = mimetype
104 elif path.startswith('static/'):
105 mimetype = mimetypes.guess_type(path)[0] or 'text/plain'
106 content = server_instance.content_cache.GetFromFile(
107 ('%s/%s' % (svn_constants.DOCS_PATH, path)),
108 binary=_IsBinaryMimetype(mimetype))
109 content_type = mimetype
110 elif path.endswith('.html'):
111 content = templates.Render(path)
112 content_type = 'text/html'
113 except FileNotFoundError as e:
114 logging.warning(traceback.format_exc())
115 content = None
116
117 headers = {'x-frame-options': 'sameorigin'}
118 if content is None:
119 return Response.NotFound(templates.Render('404'), headers=headers)
120
121 if not content:
122 logging.error('%s had empty content' % path)
123
124 headers.update({
125 'content_type': content_type,
126 'cache_control': 'max-age=300',
127 })
128 return Response.Ok(content, headers=headers)
OLDNEW
« no previous file with comments | « chrome/common/extensions/docs/server2/preview.py ('k') | chrome/common/extensions/docs/server2/samples_data_source_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698