Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Chris McDonough February 15, 2012
file 69 lines (56 sloc) 2.037 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
import os
import mimetypes

mimetypes.add_type('text/html', '.stx')
mimetypes.add_type('application/pdf', '.pdf')

from zope.structuredtext import stx2html

from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound

from pyramid.view import render_view_to_response
from pyramid.view import view_config

from virginia.models import File
from virginia.models import Directory

# default views: router will call these

@view_config(context=File)
def file_view(context, request):
    dirname, filename = os.path.split(context.path)
    name, ext = os.path.splitext(filename)
    result = render_view_to_response(context, request, ext)
    return result

@view_config(context=Directory)
def directory_view(context, request):
    path_info = request.environ['PATH_INFO']
    if not path_info.endswith('/'):
        response = HTTPFound(location=path_info + '/')
        return response

    defaults = ('index.html', 'index.stx', 'index.pt')
    for name in defaults:
        try:
            index = context[name]
        except KeyError:
            continue
        return file_view(index, request)
    response = Response('No default view for %s' % context.path)
    response.content_type = 'text/plain'
    return response

# custom views: FileView will call these

@view_config(context=File, name='.stx')
def structured_text_view(context, request):
    """ Filesystem-based STX view
"""
    result = stx2html(context.source)
    response = Response(result)
    response.content_type = 'text/html'
    return response

@view_config(context=File, name='.html')
@view_config(context=File, name='.pdf')
@view_config(context=File, name='.txt')
@view_config(context=File, name='.jpg')
def raw_view(context, request):
    """ Just return the source raw.
"""
    response = Response(context.source)
    dirname, filename = os.path.split(context.path)
    name, ext = os.path.splitext(filename)
    mt, encoding = mimetypes.guess_type(filename)
    response.content_type = mt or 'text/plain'
    return response
Something went wrong with that request. Please try again.