Created
July 21, 2014 00:53
-
-
Save chrisguitarguy/901f787395d3f21cafeb to your computer and use it in GitHub Desktop.
How to use a "default document" with static https://github.com/lukearno/static
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
""" | |
Sometimes you want all not found requests to go to a default file. A single page | |
JS app, for example, might use a client side router to show the appropriate view | |
from a single ``index.html``. | |
This is a simple example of accomplishing something like that with static: | |
https://github.com/lukearno/static | |
Not suitable for production, but works well enough for development. | |
""" | |
from email.utils import formatdate | |
import os.path as path | |
import time | |
from wsgiref.simple_server import make_server | |
from wsgiref.util import FileWrapper | |
import static | |
DEFAULT_BLOCK_SIZE = 16 * 4096 | |
class DefaultFile: | |
def __init__(self, file_path, headers=None, blocksize=None): | |
self.file_path = file_path | |
self.headers = headers or list() | |
self.blocksize = blocksize or DEFAULT_BLOCK_SIZE | |
def __call__(self, environ, start_response): | |
headers = self.headers[:] | |
headers.append(('Date', formatdate(time.time()),)) | |
sender = environ.get('wsgi.file_wrapper', FileWrapper) | |
start_response('200 OK', headers) | |
return sender(open(self.file_path, 'rb'), self.blocksize) | |
if __name__ == '__main__': | |
root = path.join(path.abspath(path.dirname(__file__)), 'web') | |
app = static.Cling(root, not_found=DefaultFile(path.join(root, 'index.txt'), [ | |
('Content-Type', 'text/plain',), | |
])) | |
server = make_server('localhost', 5000, app) | |
server.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment