diff options
| author | 2013-11-20 16:58:50 -0300 | |
|---|---|---|
| committer | 2013-11-20 16:58:50 -0300 | |
| commit | ca94afc07df55cb7fc6fe3b4f3011877b7881195 (patch) | |
| tree | d81e1f275aa77545f33740723f307a83dde2e0b4 /nikola/plugins/command/serve.py | |
| parent | f794eee787e9cde54e6b8f53e45d69c9ddc9936a (diff) | |
Imported Upstream version 6.2.1upstream/6.2.1
Diffstat (limited to 'nikola/plugins/command/serve.py')
| -rw-r--r-- | nikola/plugins/command/serve.py | 153 |
1 files changed, 153 insertions, 0 deletions
diff --git a/nikola/plugins/command/serve.py b/nikola/plugins/command/serve.py new file mode 100644 index 0000000..07403d4 --- /dev/null +++ b/nikola/plugins/command/serve.py @@ -0,0 +1,153 @@ +# -*- coding: utf-8 -*- + +# Copyright © 2012-2013 Roberto Alsina and others. + +# Permission is hereby granted, free of charge, to any +# person obtaining a copy of this software and associated +# documentation files (the "Software"), to deal in the +# Software without restriction, including without limitation +# the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the +# Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice +# shall be included in all copies or substantial portions of +# the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS +# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR +# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +from __future__ import print_function +import os +try: + from BaseHTTPServer import HTTPServer + from SimpleHTTPServer import SimpleHTTPRequestHandler +except ImportError: + from http.server import HTTPServer # NOQA + from http.server import SimpleHTTPRequestHandler # NOQA + +from nikola.plugin_categories import Command +from nikola.utils import get_logger + + +class CommandBuild(Command): + """Start test server.""" + + name = "serve" + doc_usage = "[options]" + doc_purpose = "start the test webserver" + logger = None + + cmd_options = ( + { + 'name': 'port', + 'short': 'p', + 'long': 'port', + 'default': 8000, + 'type': int, + 'help': 'Port nummber (default: 8000)', + }, + { + 'name': 'address', + 'short': 'a', + 'long': '--address', + 'type': str, + 'default': '127.0.0.1', + 'help': 'Address to bind (default: 127.0.0.1)', + }, + ) + + def _execute(self, options, args): + """Start test server.""" + self.logger = get_logger('serve', self.site.loghandlers) + out_dir = self.site.config['OUTPUT_FOLDER'] + if not os.path.isdir(out_dir): + self.logger.error("Missing '{0}' folder?".format(out_dir)) + else: + os.chdir(out_dir) + httpd = HTTPServer((options['address'], options['port']), + OurHTTPRequestHandler) + sa = httpd.socket.getsockname() + self.logger.notice("Serving HTTP on {0} port {1} ...".format(*sa)) + httpd.serve_forever() + + +class OurHTTPRequestHandler(SimpleHTTPRequestHandler): + extensions_map = dict(SimpleHTTPRequestHandler.extensions_map) + extensions_map[""] = "text/plain" + + # NOTICE: this is a patched version of send_head() to disable all sorts of + # caching. `nikola serve` is a development server, hence caching should + # not happen to have access to the newest resources. + # + # The original code was copy-pasted from Python 2.7. Python 3.3 contains + # the same code, missing the binary mode comment. + # + # Note that it might break in future versions of Python, in which case we + # would need to do even more magic. + def send_head(self): + """Common code for GET and HEAD commands. + + This sends the response code and MIME headers. + + Return value is either a file object (which has to be copied + to the outputfile by the caller unless the command was HEAD, + and must be closed by the caller under all circumstances), or + None, in which case the caller has nothing further to do. + + """ + path = self.translate_path(self.path) + f = None + if os.path.isdir(path): + if not self.path.endswith('/'): + # redirect browser - doing basically what apache does + self.send_response(301) + self.send_header("Location", self.path + "/") + # begin no-cache patch + # For redirects. With redirects, caching is even worse and can + # break more. Especially with 301 Moved Permanently redirects, + # like this one. + self.send_header("Cache-Control", "no-cache, no-store, " + "must-revalidate") + self.send_header("Pragma", "no-cache") + self.send_header("Expires", "0") + # end no-cache patch + self.end_headers() + return None + for index in "index.html", "index.htm": + index = os.path.join(path, index) + if os.path.exists(index): + path = index + break + else: + return self.list_directory(path) + ctype = self.guess_type(path) + try: + # Always read in binary mode. Opening files in text mode may cause + # newline translations, making the actual size of the content + # transmitted *less* than the content-length! + f = open(path, 'rb') + except IOError: + self.send_error(404, "File not found") + return None + self.send_response(200) + self.send_header("Content-type", ctype) + fs = os.fstat(f.fileno()) + self.send_header("Content-Length", str(fs[6])) + self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) + # begin no-cache patch + # For standard requests. + self.send_header("Cache-Control", "no-cache, no-store, " + "must-revalidate") + self.send_header("Pragma", "no-cache") + self.send_header("Expires", "0") + # end no-cache patch + self.end_headers() + return f |
