def login(self, req):
     """
     The login form.
     """
     if not self.check_ip(req):
         template = HTMLTemplate.from_filename(os.path.join(os.path.dirname(__file__), 'ip_denied.html'))
         return Response(template.substitute(req=req), status='403 Forbidden')
     if req.method == 'POST':
         username = req.str_POST['username']
         password = req.str_POST['password']
         if not self.check_login(username, password):
             msg = 'Invalid username or password'
         else:
             resp = exc.HTTPFound(location=req.params.get('back') or req.application_url)
             resp.set_cookie('__devauth', self.create_cookie(req, username))
             return resp
     else:
         msg = req.params.get('msg')
     back = req.params.get('back') or req.application_url
     if msg == 'expired':
         msg = 'Your session has expired.  You can log in again, or just <a href="%s">return to your previous page</a>' % (
             html_escape(back))
     template = HTMLTemplate.from_filename(os.path.join(os.path.dirname(__file__), 'login.html'))
     resp = Response(template.substitute(req=req, msg=msg, back=back, middleware=self))
     try:
         if req.cookies.get('__devauth'):
             self.read_cookie(req, req.str_cookies['__devauth'])
     except exc.HTTPException:
         # This means the cookie is invalid
         resp.delete_cookie('__devauth')
     return resp
示例#2
0
def rebuild_static_files():
    """
    Rebuilds static files
    """
    public_html_path = join(current_path(), '..', 'public_html')
    if not exists(public_html_path):
        os.mkdir(public_html_path)

    # Create index.html
    template = HTMLTemplate.from_filename(join(current_path(), '..',
                                               'templates' , 'index.html'))
    products_data = load_products_data()
    all_products = sorted(products_data,
           key=lambda product: product['version'][0]['publish_time'])
    all_products.reverse()

    # Build index html files
    # First remove any existing files
    html_files_list = glob(join(public_html_path, 'index.html.*'))
    for html_filename in html_files_list:
        os.unlink(html_filename)
    # Create per page files
    for i in xrange(0, len(all_products), 5):
        products = all_products[i:i+5]
        page_nr = (i/5)+1
        next_page_nr = page_nr + 1 if len(all_products) > i+5 else 0
        prev_page_nr = page_nr - 1 if page_nr > 1 else 0
        index_fname = join(public_html_path, 'index.html.%d' % page_nr)
        with open(index_fname, 'w') as index_html_file:
            index_html_file.write(template.substitute(locals()))

    # Build per product files
    template = HTMLTemplate.from_filename(join(current_path(), '..',
                                               'templates' , 'product.html'))

    products_path = join(public_html_path, 'products')
    if not exists(products_path):
        os.mkdir(products_path)
    html_files_list = glob(join(products_path, '*.html'))
    # First remove any existing files
    for html_filename in html_files_list:
        os.unlink(html_filename)
    for product in all_products:
        index_name = basename(product['index_name'])
        product_fname = join(products_path, '%s.html' % index_name)
        with open(product_fname, 'w') as html_file:
           html_file.write(template.substitute(locals()))

    # Create/update screenshot thumbnails
    update_thumbs()
示例#3
0
 def __init__(self, application, global_conf=None,
              error_template_filename=None,
              xmlhttp_key=None, media_paths=None, 
              templating_formatters=None, head_html='', footer_html='',
              reporters=None, libraries=None,
              **params):
     self.libraries = libraries or []
     self.application = application
     self.debug_infos = {}
     self.templating_formatters = templating_formatters or []
     self.head_html = HTMLTemplate(head_html)
     self.footer_html = HTMLTemplate(footer_html)
     if error_template_filename is None:
         error_template_filename = resource_filename( "weberror", 
                                                      "eval_template.html" )
     if xmlhttp_key is None:
         if global_conf is None:
             xmlhttp_key = '_'
         else:
             xmlhttp_key = global_conf.get('xmlhttp_key', '_')
     self.xmlhttp_key = xmlhttp_key
     self.media_paths = media_paths or {}
     self.error_template = HTMLTemplate.from_filename(error_template_filename)
     if reporters is None:
         reporters = []
     self.reporters = reporters
示例#4
0
    def __init__(self, template, language=None):
        if language:
            translation(language)

        self._page = HTMLTemplate.from_filename(template)
        # Render full page
        self._full = True
示例#5
0
 def find_template(self, template):
     """find a template of a given name"""
     # TODO: make this faster; the application should probably cache
     # a dict of the (loaded) templates unless (e.g.) debug is given
     
     for d in self.template_dirs:
         path = os.path.join(d, template)
         if os.path.exists(path):
             return HTMLTemplate.from_filename(path)
示例#6
0
def render_template(filename, namespace, filters_module=None):                    
    # Install template filters if given
    if filters_module:
        filters_namespace = {}
        for name in filters_module.__all__:
            filter = getattr(filters_module, name)
            filters_namespace[filter.name] = filter
        # @@HACK Remove conflicting filter with HTMLTemplate
        del filters_namespace['html'] 
        # Update namespace, possibly overriding names
        namespace.update(filters_namespace)
    return HTMLTemplate.from_filename(filename, namespace=namespace).substitute()
示例#7
0
def render_template(filename, namespace, filters_module=None):                    
    # Install template filters if given
    if filters_module:
        filters_namespace = {}
        for name in filters_module.__all__:
            filter = getattr(filters_module, name)
            filters_namespace[filter.name] = filter
        # @@HACK Remove conflicting filter with HTMLTemplate
        del filters_namespace['html'] 
        # Update namespace, possibly overriding names
        namespace.update(filters_namespace)
    return HTMLTemplate.from_filename(filename, namespace=namespace).substitute()
示例#8
0
 def find_template(self, name):
     """find a template of a given name"""
     # the application caches a dict of the templates if app.reload is False
     if name in self.template_cache:
         return self.template_cache[name]
     
     for d in self.template_dirs:
         path = os.path.join(d, name)
         if os.path.exists(path):
             template = HTMLTemplate.from_filename(path)
             if not self.app.reload:
                 self.template_cache[name] = template
             return template
示例#9
0
 def __init__(
     self,
     application,
     global_conf=None,
     error_template_filename=None,
     xmlhttp_key=None,
     media_paths=None,
     templating_formatters=None,
     head_html="",
     footer_html="",
     reporters=None,
     libraries=None,
     debug_url_prefix=None,
     **params
 ):
     self.libraries = libraries or []
     self.application = application
     self.debug_infos = {}
     self.templating_formatters = templating_formatters or []
     self.head_html = HTMLTemplate(head_html)
     self.footer_html = HTMLTemplate(footer_html)
     if error_template_filename is None:
         error_template_filename = resource_filename("weberror", "eval_template.html")
     if xmlhttp_key is None:
         if global_conf is None:
             xmlhttp_key = "_"
         else:
             xmlhttp_key = global_conf.get("xmlhttp_key", "_")
     self.xmlhttp_key = xmlhttp_key
     if debug_url_prefix is None:
         if global_conf is None:
             debug_url_prefix = "_debug"
         else:
             debug_url_prefix = global_conf.get("debug_url_prefix", "_debug")
     self.debug_url_prefix = debug_url_prefix.split("/")
     self.media_paths = media_paths or {}
     self.error_template = HTMLTemplate.from_filename(error_template_filename)
     if reporters is None:
         reporters = []
     self.reporters = reporters
示例#10
0
文件: wsgiapp.py 项目: ianb/emailit
from formencode.api import Invalid
from lxml import html
try:
    # Python 2.5:
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
except ImportError:
    # Python 2.4:
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
import smtplib

here = os.path.dirname(__file__)

## FIXME: these don't auto-reload or restart the server on edit:
form_html = HTMLTemplate.from_filename(os.path.join(here, 'form.html'))
result_html = HTMLTemplate.from_filename(os.path.join(here, 'result.html'))

class EmailIt(object):

    ## FIXME: should have some kind of host restriction, like ScriptTranscluder
    def __init__(self, smtp_server='localhost', smtp_username=None, smtp_password=None, smtp_use_tls=False):
        self.smtp_server = smtp_server
        self.smtp_username = smtp_username
        self.smtp_password = smtp_password
        self.smtp_use_tls = smtp_use_tls

    def __call__(self, environ, start_response):
        req = Request(environ)
        if req.method == 'GET':
            meth = self.form
示例#11
0
def render_template(filename, namespace):                    
    return HTMLTemplate.from_filename(filename, namespace=namespace).substitute()
示例#12
0
class Editor(object):

    def __init__(self, base_dir=None, filename=None,
                 title=None, force_syntax=None):
        assert base_dir or filename
        assert not base_dir or not filename
        if base_dir:
            self.base_dir = os.path.normcase(os.path.abspath(base_dir))
        else:
            self.base_dir = None
        self.filename = filename
        self.title = title
        self.force_syntax = force_syntax

    def __call__(self, environ, start_response):
        req = Request(environ)
        if req.path_info_peek() == '.media':
            req.path_info_pop()
            app = StaticURLParser(os.path.join(os.path.dirname(__file__), 'media'))
            return app(environ, start_response)
        if self.base_dir:
            filename = os.path.join(self.base_dir, req.path_info.lstrip('/'))
            assert filename.startswith(self.base_dir)
        else:
            filename = self.filename
        if req.method not in ('GET', 'POST'):
            resp = exc.HTTPMethodNotAllowed('Bad method: %s' % req.method,
                                            allow='GET,POST')
        elif os.path.isdir(filename):
            if req.method == 'POST':
                resp = self.save_create(req, filename)
            else:
                if not req.path.endswith('/'):
                    resp = exc.HTTPMovedPermanently(add_slash=True)
                else:
                    resp = self.view_dir(req, filename)
        else:
            if req.method == 'POST':
                resp = self.save_file(req, filename)
            elif req.method == 'GET':
                resp = self.edit_file(req, filename)
        return resp(environ, start_response)

    def edit_url(self, req, filename):
        if self.filename:
            assert self.filename == filename
            return req.application_url
        else:
            assert filename.startswith(self.base_dir)
            filename = filename[len(self.base_dir):].lstrip('/').lstrip('\\')
            return req.application_url + '/' + filename

    def save_file(self, req, filename):
        content = req.POST['content']
        f = open(filename, 'wb')
        f.write(content)
        f.close()
        return exc.HTTPFound(
            location=self.edit_url(req, filename))

    syntax_map = {
        '.c': 'c',
        '.cf': 'coldfusion',
        '.cpp': 'cpp',
        '.c++': 'cpp',
        '.css': 'css',
        '.html': 'html',
        '.htm': 'html',
        '.xhtml': 'html',
        '.js': 'js',
        '.pas': '******',
        '.pl': 'perl',
        '.php': 'php',
        '.py': 'python',
        'robots.txt': 'robotstxt',
        '.rb': 'ruby',
        '.sql': 'sql',
        '.tsql': 'tsql',
        '.vb': 'vb',
        '.xml': 'xml',
        }

    def syntax_for_filename(self, filename):
        if self.force_syntax:
            return self.force_syntax
        basename = os.path.basename(filename)
        if basename in self.syntax_map:
            return self.syntax_map[basename]
        else:
            ext = os.path.splitext(filename)[1].lower()
            if ext in self.syntax_map:
                return self.syntax_map[ext]
        mimetype, enc = mimetypes.guess_type(os.path.splitext(filename)[1])
        if mimetype.startswith('application/') and mimetype.endswith('+xml'):
            return 'xml'
        return None

    def edit_file(self, req, filename):
        f = open(filename, 'rb')
        content = f.read()
        f.close()
        title = self.title or filename
        syntax = self.syntax_for_filename(filename)
        body = self.edit_template.substitute(
            content=content, filename=filename, title=title, 
            req=req, edit_url=self.edit_url(req, filename),
            syntax=syntax)
        resp = Response(body=body)
        resp.cache_expires()
        return resp

    edit_template = HTMLTemplate.from_filename(
        os.path.join(os.path.dirname(__file__), 'editor_template.html'))

    def save_create(self, req, dir):
        file = req.POST.get('file')
        if file is None or file == '':
            content = req.POST['content']
            filename = req.POST['filename']
        else:
            content = file.value
            filename = req.POST.get('filename') or file.filename
        filename = filename.replace('\\', '/')
        filename = os.path.basename(os.path.normpath(filename))
        filename = os.path.join(dir, filename)
        if os.path.exists(filename):
            return exc.HTTPForbidden(
                "The file %s already exists, you cannot upload over it" % filename)
        f = open(filename, 'wb')
        f.write(content)
        f.close()
        return exc.HTTPFound(
            location=self.edit_url(req, filename))

    skip_files = ['.svn', 'CVS', '.hg']

    def view_dir(self, req, dir):
        dir = os.path.normpath(dir)
        show_parent = dir != self.base_dir
        children = [os.path.join(dir, name) for name in os.listdir(dir)
                    if name not in self.skip_files]
        def edit_url(filename):
            return self.edit_url(req, filename)
        title = self.title or dir
        body = self.view_dir_template.substitute(
            req=req,
            dir=dir,
            show_parent=show_parent,
            title=title,
            basename=os.path.basename,
            dirname=os.path.dirname,
            isdir=os.path.isdir,
            children=children,
            edit_url=edit_url,
            )
        resp = Response(body=body)
        resp.cache_expires()
        return resp

    view_dir_template = HTMLTemplate.from_filename(
        os.path.join(os.path.dirname(__file__), 'view_dir_template.html'))
示例#13
0
def render_template(filename, namespace):
    return HTMLTemplate.from_filename(filename,
                                      namespace=namespace).substitute()
示例#14
0
 def homepage(self, req):
     tmpl = HTMLTemplate.from_filename(os.path.join(here, 'homepage.html'))
     resp = tmpl.substitute(app=self, req=req, appIncludeJs=self.appinclude_js)
     return Response(body=resp)