Exemple #1
0
    def setup(self, config):

        # Listen for HTTP connections
        port = 6280
        iface = None

        if config is not None:
            if 'port' in config:
                port = int(config['port'])
            if 'interface' in config:
                iface = config['interface']

        if iface is None:
            iface = '0.0.0.0'

        templateLoader = PackageLoader('downpour.web', 'templates')
        self.templateFactory = Environment(loader=templateLoader)
        templateDir = os.path.dirname(templateLoader.get_source(
                self.templateFactory, 'base.html')[1]);

        # Custom filters for templateFactory
        self.templateFactory.filters['progressbar'] = self.progressbar
        self.templateFactory.filters['healthmeter'] = self.healthmeter
        self.templateFactory.filters['intervalformat'] = self.intervalformat
        self.templateFactory.filters['timestampformat'] = self.timestampformat
        self.templateFactory.filters['urlencode'] = urllib.quote
        self.templateFactory.filters['workinglink'] = self.workinglink
        self.templateFactory.filters['librarylink'] = self.librarylink

        root = SiteRoot(templateDir + '/media', self.application)
        site = server.Site(root)
        site.requestFactory = requestFactory(self)
        site.sessionFactory = sessionFactory(self)

        self.tryListen(port, site, get_interface(iface))
Exemple #2
0
def display(input: TextIO) -> None:
    import seaborn as sns

    # Load view JSON.
    input_data: dict = json.load(input)
    input.close()

    loader = PackageLoader('mockdown.display', 'templates')
    env = Environment(loader=loader,
                      autoescape=select_autoescape(['html', 'xml']))

    # Kind of a hack. Using importlib.resources is probably more Pythonic but...
    kiwi_js_src = loader.get_source(env, 'js/flightlessbird.all.js')[0]

    input_meta = input_data.get('meta', {})
    scrape_meta = input_data.get('scrape', {})

    # Utility for convenience.
    # todo: move elsewhere
    def get_meta(*keys: str, subject=input_meta, default=None):
        if len(keys) == 0:
            return input_meta

        k, ks = keys[0], keys[1:]
        result = input_meta.get(k, default)

        if not ks:
            return result
        else:
            return get_meta(*ks, subject=result, default=default)

    examples = input_data['examples']

    observed_bounds = {
        'min_width': min(e['rect'][2] - e['rect'][0] for e in examples),
        'max_width': max(e['rect'][2] - e['rect'][0] for e in examples),
        'min_height': min(e['rect'][3] - e['rect'][1] for e in examples),
        'max_height': max(e['rect'][3] - e['rect'][1] for e in examples),
    }

    context = {
        'examples': examples,
        'origin': get_meta('scrape', 'origin', default=None),
        'colors': sns.color_palette('bright', len(examples)).as_hex(),
        **observed_bounds
    }

    template = env.get_template('default.html.jinja2')
    html = template.render(**context)

    # Write the result to a temporary file, and open it in the user's web browser.
    tmp = tempfile.NamedTemporaryFile(mode='w',
                                      prefix='fnord-',
                                      suffix='.html',
                                      delete=False)
    tmp.write(html)
    tmp.flush()
    tmp.close()

    webbrowser.open(f"file://{tmp.name}")
Exemple #3
0
def test_package_zip_omit_curdir(package_zip_loader, package_path):
    """PackageLoader should not add or include "." or "./" in the root
    path, it is invalid in zip paths.
    """
    loader = PackageLoader("t_pack", package_path)
    assert loader.package_path == ""
    source, _, _ = loader.get_source(None, "templates/foo/test.html")
    assert source.rstrip() == "FOO"
Exemple #4
0
def export(request, rhp_id):
    try:
        rhp = Rhp.objects.get(pk=rhp_id)
    except Rhp.DoesNotExist:
        raise Http404

    # create the jinja2 evironment for latex response
    # loader = FileSystemLoader('/path/to/templates')

    loader = PackageLoader('rhp', 'templates/latex')
    latex_helper = LatexHelper(loader)

    context = {
        'rhp': rhp,
        'vlu': rhp.vlu,
        'fragen': Frage.objects.select_related(),
        'fragensets': Fragenset.objects.select_related(),
        'optionen': Option.objects.select_related(),
        'vorlesungen': rhp.vlu.vorlesungen.select_related(),
        'artikel': rhp.artikel.all(),
        }

    files = []
    tmpfiles = []
    for tpl in latex_helper.env.list_templates():
        if tpl and (tpl.find('.tex') > 0 or tpl.find('.sty') > 0):
            template = latex_helper.env.get_template(tpl)
            f = tempfile.NamedTemporaryFile()
            f.write(template.render(context).encode('utf8'))
            f.flush()
            tmpfiles.append((tpl, f))
        else:
            files.append((tpl, loader.get_source(latex_helper.env,
                         tpl)[1]))

    # return as a zip file. from here: https://code.djangoproject.com/wiki/CookBookDynamicZip

    response = HttpResponse(mimetype='application/zip')
    response['Content-Disposition'] = 'filename=' + rhp.name + '.zip'

    buffer = StringIO()
    zip = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED)

    for (name, f) in tmpfiles:
        zip.write(f.name, rhp.name + '/' + name)
        f.close()

    for (name, f) in files:
        zip.write(f, rhp.name + '/' + name)

    zip.close()
    buffer.flush()

    response.write(buffer.getvalue())
    buffer.close()
    return response
Exemple #5
0
def export(request, rhp_id):
    try:
        rhp = Rhp.objects.get(pk=rhp_id)
    except Rhp.DoesNotExist:
        raise Http404

    # create the jinja2 evironment for latex response
    # loader = FileSystemLoader('/path/to/templates')

    loader = PackageLoader('rhp', 'templates/latex')
    latex_helper = LatexHelper(loader)

    context = {
        'rhp': rhp,
        'vlu': rhp.vlu,
        'fragen': Frage.objects.select_related(),
        'fragensets': Fragenset.objects.select_related(),
        'optionen': Option.objects.select_related(),
        'vorlesungen': rhp.vlu.vorlesungen.select_related(),
        'artikel': rhp.artikel.all(),
    }

    files = []
    tmpfiles = []
    for tpl in latex_helper.env.list_templates():
        if tpl and (tpl.find('.tex') > 0 or tpl.find('.sty') > 0):
            template = latex_helper.env.get_template(tpl)
            f = tempfile.NamedTemporaryFile()
            f.write(template.render(context).encode('utf8'))
            f.flush()
            tmpfiles.append((tpl, f))
        else:
            files.append((tpl, loader.get_source(latex_helper.env, tpl)[1]))

    # return as a zip file. from here: https://code.djangoproject.com/wiki/CookBookDynamicZip

    response = HttpResponse(mimetype='application/zip')
    response['Content-Disposition'] = 'filename=' + rhp.name + '.zip'

    buffer = StringIO()
    zip = zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED)

    for (name, f) in tmpfiles:
        zip.write(f.name, rhp.name + '/' + name)
        f.close()

    for (name, f) in files:
        zip.write(f, rhp.name + '/' + name)

    zip.close()
    buffer.flush()

    response.write(buffer.getvalue())
    buffer.close()
    return response
Exemple #6
0
 def get_source(self, environment, template):
     if template[:1] == '!':
         template = template[1:]
     else:
         pieces = split_path_safely(template)
         if pieces is None:
             raise TemplateNotFound()
         theme = get_theme()
         if theme is None:
             raise RuntimeError('theme not found')
         fn = path.join(theme.template_path, *pieces)
         if path.isfile(fn):
             with open(fn, 'r') as f:
                 contents = f.read().decode(self.encoding)
             mtime = path.getmtime(fn)
             def uptodate():
                 try:
                     return path.getmtime(fn) == mtime
                 except OSError:
                     return False
             return contents, fn, uptodate
     return PackageLoader.get_source(self, environment, template)
Exemple #7
0
    def get_source(self, environment, template):
        if template[:1] == '!':
            template = template[1:]
        else:
            pieces = split_path_safely(template)
            if pieces is None:
                raise TemplateNotFound()
            theme = get_theme()
            if theme is None:
                raise RuntimeError('theme not found')
            fn = path.join(theme.template_path, *pieces)
            if path.isfile(fn):
                with open(fn, 'r') as f:
                    contents = f.read().decode(self.encoding)
                mtime = path.getmtime(fn)

                def uptodate():
                    try:
                        return path.getmtime(fn) == mtime
                    except OSError:
                        return False

                return contents, fn, uptodate
        return PackageLoader.get_source(self, environment, template)
Exemple #8
0
 def get_source(self, environment, template):
     try:
         return PackageLoader.get_source(self, environment, template)
     except TemplateNotFound:
         template = 'default/' + template
         return PackageLoader.get_source(self, environment, template)
Exemple #9
0
 def get_source(self, environment, template):
     try:
         return PackageLoader.get_source(self, environment, template)
     except TemplateNotFound:
         template = 'default/' + template
         return PackageLoader.get_source(self, environment, template)