Пример #1
1
    def render(self, context):
        """ Return rendered ODF (webodt.ODFDocument instance)"""
        # create temp output directory
        tmpdir = tempfile.mkdtemp()
        self.handler.unpack(tmpdir)
        # store updated content.xml
        for f_to_process in self.get_files_to_process():
            template = self.get_file(f_to_process)
            for preprocess_func in list_preprocessors(self.preprocessors):
                template = preprocess_func(template)
            template = Template(template)
            xml_result = template.render(context)
            filename = os.path.join(tmpdir, f_to_process)
            with open(filename, "w") as result_fd:
                result_fd.write(smart_str(xml_result))

        lowlevel_fd, tmpfile = tempfile.mkstemp(suffix=".odt", dir=WEBODT_TMP_DIR)
        os.close(lowlevel_fd)
        tmpzipfile = zipfile.ZipFile(tmpfile, "w")
        for root, _, files in os.walk(tmpdir):
            for fn in files:
                path = os.path.join(root, fn)
                os.utime(path, (self._fake_timestamp, self._fake_timestamp))
                fn = os.path.relpath(path, tmpdir)
                tmpzipfile.write(path, fn)
        tmpzipfile.close()
        # remove directory tree
        shutil.rmtree(tmpdir)
        # return ODF document
        return ODFDocument(tmpfile)
Пример #2
0
def report_queue_entry_submitted(queue_entries):
    mail_template = Template(
        """

Automatic report from Global Tag Collector
--
Hostname:{{hostname}}
Production Level: {{production_level}}
{% for queue_entry in queue_entries %}
--
Global Tag Queue entry submitted.
Queue:{{queue_entry.queue}}
Tag:{{queue_entry.tag}}
Record:{{queue_entry.record}}
Label:{{queue_entry.label}}
Comment:{{queue_entry.comment}}
Status:{{queue_entry.status}}
Submitter:{{queue_entry.submitter}}
Submitting time:{{queue_entry.submitting_time}}
https://{{hostname}}/{% url gt_queue_entries queue_id=queue_entry.queue.pk %}
{% endfor %}
"""
    )
    recipients = ["global-tag-administrators@cern.ch", queue_entries[0].submitter.email]
    c = Context(
        {"hostname": settings.HOSTNAME, "queue_entries": queue_entries, "production_level": settings.PRODUCTION_LEVEL}
    )
    message_text = mail_template.render(c)
    recipients = ["global-tag-administrators@cern.ch", queue_entries[0].submitter.email]
    try:
        print message_text
        send_mail(subject="Queue entry submitted", body=message_text, recipient_list=recipients)
    except Exception as e:
        logger.error("Message could not be sent")
        logger.error(e)
Пример #3
0
    def test_userpage_hook(self):
        """Testing UserPage sidebar extension hooks"""
        subentry = {"label": "Sub Hook", "url": "sub-foo-url"}
        entry = {"label": "User Hook", "url": "foo-url", "subitems": [subentry]}

        hook = UserPageSidebarHook(extension=self.extension, entries=[entry])
        context = Context({"userpage_hook": hook})

        entries = hook.entries
        self.assertEqual(len(entries), 1)
        self.assertEqual(entries[0], entry)
        self.assertEqual(len(entries[0]["subitems"]), 1)
        self.assertEqual(entries[0]["subitems"][0], subentry)

        t = Template(
            "{% load rb_extensions %}"
            "{% for hook in userpage_hook.entries %}"
            "{{hook.label}} - {{hook.url}}"
            "{% for subhook in hook.subitems %}"
            " -- {{subhook.label}} - {{subhook.url}}"
            "{% endfor %}"
            "{% endfor %}"
        )

        self.assertEqual(
            t.render(context).strip(),
            "%s - %s -- %s - %s"
            % (entry["label"], entry["url"], entry["subitems"][0]["label"], entry["subitems"][0]["url"]),
        )
Пример #4
0
def render_drugbankcadrugs_pane(request):

    user = request.user
    if request.method == "GET":
        app_wrapper = []
        context = RequestContext(request, {"user": user})
        try:
            pane_template = Template(open("registry/drug_db/drugbankca/dijit_widgets/pane.yaml", "r").read())
        except (IOError):
            raise Http404("No template file to render the pane ! ")
        rendered_pane = pane_template.render(context)
        pane_yaml = yaml.load(rendered_pane)
        app_object = {}
        app_object["app"] = "Drug_Bank_Ca"
        app_object["ui_sections"] = {
            "app_type": "sub_module",
            "load_after": "patient",
            "load_first": False,
            "layout": ["trailing", "top", "center"],
            "widgets": {"tree": None, "summary": None, "grid": None, "search": None},
        }
        app_object["url"] = ""
        app_wrapper.append(app_object)
        success = True
        error_message = "Returning Drug Bank Ca app pane variables"
        data = {"success": success, "error_message": error_message, "app": app_wrapper, "pane": pane_yaml}
        jsondata = json.dumps(data)
        return HttpResponse(jsondata, content_type="application/json")
    else:
        raise Http404("Bad Request Method")
Пример #5
0
 def test_result_list_empty_changelist_value(self):
     """
     Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored
     for relationship fields
     """
     new_child = Child.objects.create(name="name", parent=None)
     request = self.factory.get("/child/")
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(
         request,
         Child,
         list_display,
         list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_max_show_all,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     row_html = (
         '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">(None)</td></tr></tbody>'
         % new_child.id
     )
     self.assertFalse(table_output.find(row_html) == -1, "Failed to find expected row element: %s" % table_output)
Пример #6
0
 def test_kwargs(self):
     tpl = Template(
         """{% load i18n %}
         {% language 'nl'  %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
         {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}"""
     )
     self.assertEqual(tpl.render(Context({})).strip().split(), ["/vertaald/apo/", "/traduzidos/apo/"])
Пример #7
0
def session_view(request):
    "A view that modifies the session"
    request.session["tobacconist"] = "hovercraft"

    t = Template("This is a view that modifies the session.", name="Session Modifying View Template")
    c = Context()
    return HttpResponse(t.render(c))
Пример #8
0
    def test_with_custom_objects(self):
        condition_set = "gargoyle.builtins.UserConditionSet(auth.user)"

        switch = Switch.objects.create(key="test", status=SELECTIVE)
        switch = self.gargoyle["test"]

        switch.add_condition(condition_set=condition_set, field_name="percent", condition="0-50")

        request = HttpRequest()
        request.user = self.user

        # Pass in request.user explicitly.
        template = Template(
            """
            {% load gargoyle_tags %}
            {% ifswitch test request.user %}
            hello world!
            {% else %}
            foo bar baz
            {% endifswitch %}
        """
        )
        rendered = template.render(Context({"request": request}))

        self.assertFalse("foo bar baz" in rendered)
        self.assertTrue("hello world!" in rendered)
Пример #9
0
    def handle(self, *args, **options):

        tpl = Template(
            """
title:{{object.title}} 
subtitle:{{object.sub_title}}
slug:{{object.slug}}
featured:{{object.featured}}
status:{{object.status}}
add_date:{{object.add_date}}
pub_date:{{object.pub_date}}
mod_date:{{object.mod_date}}
project_date:{{object.project_date}}


#{{object.title}}
##{{object.sub_title}}
{{object.body}}

todo
images = models.ManyToManyField(Image, blank=True, through=ArticleImage)
files = models.ManyToManyField(File, blank=True)
vimeo = models.URLField(max_length=100, blank=True, null=True)
tags = TaggableManager(blank=True, through=TaggedArticle)


            """
        )
        for article in Article.objects.all():
            c = Context({"object": article})
            print tpl.render(c)
Пример #10
0
def parse_blocks(value):
    """ use the django template loader and response object to spit 
    out rendered content
    """
    t = Template(value)
    c = Context({"MEDIA_URL": settings.MEDIA_URL})
    return t.render(c)
Пример #11
0
def home(request):
    print "start process"

    last_comment_list = Comments.objects.all().order_by("-timestamp")
    page_size = 10
    paginator = Paginator(last_comment_list, page_size)
    print paginator.num_pages
    try:
        page = int(request.REQUEST.get("page", 1))
    # 如果没有对应的page键,就返回默认1
    except ValueError:

        page = 1
        print page
    try:
        posts = paginator.page(page)
        print page
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    print "succcs"
    json_data = serializers.serialize("json", posts)
    contexts = {"commentList": posts}
    if page == 1:
        return render(request, "comments/loadmore.html", contexts)
    else:
        t = Template("comments/ajax.html")
        html = t.render(Context(contexts))
        return HttpResponse(html)
Пример #12
0
    def test_title_h_only_number_bigger_than_6(self):
        template = Template("{% load drc %} {% drc_title 9 %}")
        rendered = template.render(Context({}))
        soup = BeautifulSoup(rendered, "html.parser")
        h6_tag = soup.find("h6")

        self.assertTrue(h6_tag, "title tag missing")
Пример #13
0
    def test_title_empty_param(self):
        template = Template('{% load drc %} {% drc_title "" %}')
        rendered = template.render(Context({}))
        soup = BeautifulSoup(rendered, "html.parser")
        h1_tag = soup.find("h1")

        self.assertTrue(h1_tag, "title tag missing")
Пример #14
0
    def test_title_multiple_words_in_param(self):
        template = Template('{% load drc %} {% drc_title "h3 data-arg" %}')
        rendered = template.render(Context({}))
        soup = BeautifulSoup(rendered, "html.parser")
        h3_tag = soup.find("h3")

        self.assertFalse(h3_tag.has_attr("data-arg"))
Пример #15
0
    def check_template(self, template):
        """
        Tries to compile and render our template to make sure it passes.
        """
        try:
            t = Template("{% load messages %}" + template)

            # we build a context that has dummy values for all required fields
            context = {}
            context["confirmation_id"] = 1
            for field in self.fields.all():
                required = field.constraints.all().filter(type="req_val")

                # we are at a field that isn't required?  pop out, these will be dealt with
                # in the next block
                if not required:
                    continue

                if field.field_type == XFormField.TYPE_INT or field.field_type == XFormField.TYPE_FLOAT:
                    context[field.command] = "1"
                else:
                    context[field.command] = "test"

            t.render(Context(context))
        except Exception as e:
            raise ValidationError(str(e))
Пример #16
0
    def json(self):
        """
        generate JSON for the post/comment object, intended to be returned via AJAX
        """

        # Use the implicit template formatting rather than the __str__
        # formatting, which is default if we were to return a formatted string.
        json_template = Template(
            """
            {
                "author":
                {
                    "email": "{{ email }}",
                    "first_name": "{{ first_name }}",
                    "last_name": "{{ last_name }}"
                },
                "date_posted": "{{ date_posted }}",
                "time_stamp": "{{ time_stamp }}",
                "message": "{{ message }}"
            }"""
        )
        ctx = Context(
            {
                "email": self.author.user.email,
                "first_name": self.author.user.first_name,
                "last_name": self.author.user.last_name,
                "date_posted": self.date_posted,
                "time_stamp": self.time_stamp(),
                "message": self.message,
            }
        )
        return json_template.render(ctx)
Пример #17
0
 def render(self, record, table, **kwargs):
     t = Template(self.template_code)
     if hasattr(table, "request"):
         context = RequestContext(table.request, {"record": record})
     else:
         context = Context({"record": record})
     return t.render(context)
Пример #18
0
    def render(self, withheader=True):
        if len(self.rows):
            try:
                styles = self.styles
            except AttributeError:
                styles = "table-striped table-bordered"

            t = Template(
                """
<table id="{{ tableid }}" class="table {{ styles }}">
  {% if withheader %}{% include "common/table_head.html" %}{% endif %}
  {% include "common/table_body.html" %}
</table>
"""
            )
            return t.render(
                RequestContext(
                    self.request, {"table": self, "tableid": self.tableid, "styles": styles, "withheader": withheader}
                )
            )

        t = Template(
            """
<div class="alert alert-info">%s</div>
"""
            % _("No entries to display")
        )
        return t.render(Context())
Пример #19
0
 def login_protected_view(self, request):
     t = Template(
         "This is a login protected test using a method. " "Username is {{ user.username }}.",
         name="Login Method Template",
     )
     c = Context({"user": request.user})
     return HttpResponse(t.render(c))
Пример #20
0
def render_template(template_path, context={}):
    """
    Evaluate a template by resource path, applying the provided context
    """
    template_str = load_resource(template_path)
    template = Template(template_str)
    return template.render(Context(context))
Пример #21
0
 def test_strings_only(self):
     t = Template(
         """{% load i18n %}
         {% language 'nl' %}{% url 'no-prefix-translated' %}{% endlanguage %}
         {% language 'pt-br' %}{% url 'no-prefix-translated' %}{% endlanguage %}"""
     )
     self.assertEqual(t.render(Context({})).strip().split(), ["/vertaald/", "/traduzidos/"])
Пример #22
0
def es_get_sid_by_hosts(request, sid, count=20, from_date=0):
    templ = Template(SID_BY_HOST_QUERY)
    context = Context({"rule_sid": sid, "alerts_number": count, "from_date": from_date})
    data = templ.render(context)
    es_url = get_es_url(from_date)
    req = urllib2.Request(es_url, data)
    try:
        out = urllib2.urlopen(req)
    except:
        return None
    data = out.read()
    # returned data is JSON
    data = json.loads(data)
    # total number of results
    try:
        data = data["facets"]["terms"]["terms"]
    except:
        return None
    stats = []
    if data != None:
        for elt in data:
            hstat = {"host": elt["term"], "count": elt["count"]}
            stats.append(hstat)
        stats = RuleStatsTable(stats)
        tables.RequestConfig(request).configure(stats)
    else:
        return None
    return stats
Пример #23
0
 def test_result_list_html(self):
     """
     Verifies that inclusion tag result_list generates a table when with
     default ModelAdmin settings.
     """
     new_parent = Parent.objects.create(name="parent")
     new_child = Child.objects.create(name="name", parent=new_parent)
     request = self.factory.get("/child/")
     m = ChildAdmin(Child, admin.site)
     list_display = m.get_list_display(request)
     list_display_links = m.get_list_display_links(request, list_display)
     cl = ChangeList(
         request,
         Child,
         list_display,
         list_display_links,
         m.list_filter,
         m.date_hierarchy,
         m.search_fields,
         m.list_select_related,
         m.list_per_page,
         m.list_max_show_all,
         m.list_editable,
         m,
     )
     cl.formset = None
     template = Template("{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}")
     context = Context({"cl": cl})
     table_output = template.render(context)
     row_html = (
         '<tbody><tr class="row1"><th><a href="%d/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>'
         % new_child.id
     )
     self.assertFalse(table_output.find(row_html) == -1, "Failed to find expected row element: %s" % table_output)
Пример #24
0
def es_get_timeline(from_date=0, interval=None, hosts=None, qfilter=None):
    templ = Template(TIMELINE_QUERY)
    # 100 points on graph per default
    if interval == None:
        interval = int((time() - (int(from_date) / 1000)) / 100)
    context = Context({"from_date": from_date, "interval": str(interval) + "s", "hosts": hosts})
    if qfilter != None:
        query_filter = " AND " + qfilter
        context["query_filter"] = re.sub('"', '\\"', query_filter)
    data = templ.render(context)
    es_url = get_es_url(from_date)
    req = urllib2.Request(es_url, data)
    try:
        out = urllib2.urlopen(req)
    except:
        return None
    data = out.read()
    # returned data is JSON
    data = json.loads(data)
    # total number of results
    try:
        data = data["facets"]
    except:
        return {}
    data["from_date"] = from_date
    data["interval"] = int(interval) * 1000
    return data
Пример #25
0
    def test_if_relationship_tag(self):
        t = Template(
            '{% load relationship_tags %}{% if_relationship john paul "following" %}y{% else %}n{% endif_relationship %}'
        )
        c = Context({"john": self.john, "paul": self.paul})
        rendered = t.render(c)
        self.assertEqual(rendered, "y")

        t = Template(
            '{% load relationship_tags %}{% if_relationship paul john "following" %}y{% else %}n{% endif_relationship %}'
        )
        c = Context({"john": self.john, "paul": self.paul})
        rendered = t.render(c)
        self.assertEqual(rendered, "n")

        t = Template(
            '{% load relationship_tags %}{% if_relationship paul john "followers" %}y{% else %}n{% endif_relationship %}'
        )
        c = Context({"john": self.john, "paul": self.paul})
        rendered = t.render(c)
        self.assertEqual(rendered, "y")

        t = Template(
            '{% load relationship_tags %}{% if_relationship paul john "friends" %}y{% else %}n{% endif_relationship %}'
        )
        c = Context({"john": self.john, "paul": self.paul})
        rendered = t.render(c)
        self.assertEqual(rendered, "n")

        t = Template(
            '{% load relationship_tags %}{% if_relationship john yoko "friends" %}y{% else %}n{% endif_relationship %}'
        )
        c = Context({"john": self.john, "yoko": self.yoko})
        rendered = t.render(c)
        self.assertEqual(rendered, "y")
Пример #26
0
def es_get_rules_per_category(from_date=0, hosts=None, qfilter=None):
    templ = Template(RULES_PER_CATEGORY)
    context = Context({"from_date": from_date, "hosts": hosts[0]})
    if qfilter != None:
        query_filter = " AND " + qfilter
        context["query_filter"] = query_filter
    data = templ.render(context)
    es_url = get_es_url(from_date)
    req = urllib2.Request(es_url, data)
    try:
        out = urllib2.urlopen(req)
    except:
        return None
    data = out.read()
    # returned data is JSON
    data = json.loads(data)
    # clean the data: we need to compact the leaf and previous data
    if data["hits"]["total"] > 0:
        cdata = compact_tree(data["aggregations"]["category"]["buckets"])
    else:
        return None
    rdata = {}
    rdata["key"] = "categories"
    rdata["children"] = cdata
    return rdata
Пример #27
0
    def _test_dropdown_action_hook(self, template_tag_name, hook_cls):
        action = {
            "id": "test-menu",
            "label": "Test Menu",
            "items": [
                {
                    "id": "test-action",
                    "label": "Test Action",
                    "url": "foo-url",
                    "image": "test-image",
                    "image_width": 42,
                    "image_height": 42,
                }
            ],
        }

        hook = hook_cls(extension=self.extension, actions=[action])

        context = Context({})
        entries = hook.get_actions(context)
        self.assertEqual(len(entries), 1)
        self.assertEqual(entries[0], action)

        t = Template("{% load rb_extensions %}" "{% " + template_tag_name + " %}")

        content = t.render(context).strip()

        self.assertTrue(('id="%s"' % action["id"]) in content)
        self.assertTrue((">%s &#9662;" % action["label"]) in content)
        self.assertTrue(self._build_action_template(action["items"][0]) in content)
Пример #28
0
    def send(self, subject="Confirm", message="Code", expire=72, tplparams=None):
        """
        Envoie (ou réenvoie) le code de confirmation.
        Le titre et le message sont pris comme des templates, les variables disponibles sont {{code}}, {{expire}},
         {{dest}}, et tout ce qui est contenu dans tplparams.

        Args:
          subject(str): Sujet du mail
          message(str): Message du mail
          expire(int): Nombre d'heures pour l'expiration du mail
          tplparams(dict): Eléments de contexte pour le titre et le message email


        """
        if tplparams is None:
            tplparams = {}
        if not self.code:
            self.generate()
        self.expire = datetime.datetime.now() + datetime.timedelta(hours=expire)
        subject = Template(subject)
        message = Template(message)
        tplparams.update({"code": self.code, "expire": self.expire, "dest": self.dest})
        ctx = Context(tplparams)
        send_mail(subject.render(ctx), message.render(ctx), "noreply@localhost", (self.dest, "jmbarbier@localhost"))
        self.status = "S"
        self.save()
Пример #29
0
    def test_docutils(self):
        try:
            import docutils
        except ImportError:
            docutils = None

        rest_content = """Paragraph 1

Paragraph 2 with a link_

.. _link: http://www.example.com/"""

        t = Template("{{ rest_content|restructuredtext }}")
        rendered = t.render(Context(locals())).strip()
        if docutils:
            # Different versions of docutils return slightly different HTML
            try:
                # Docutils v0.4 and earlier
                self.assertEqual(
                    rendered,
                    """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""",
                )
            except AssertionError, e:
                # Docutils from SVN (which will become 0.5)
                self.assertEqual(
                    rendered,
                    """<p>Paragraph 1</p>
<p>Paragraph 2 with a <a class="reference external" href="http://www.example.com/">link</a></p>""",
                )
Пример #30
0
 def test_social_share(self):
     """
     Test social share tags with unicode input
     """
     t = Template(
         "{% load spirit_tags %}"
         '{% get_facebook_share_url url="/á/foo bar/" title="á" %}'
         '{% get_twitter_share_url url="/á/foo bar/" title="á" %}'
         '{% get_gplus_share_url url="/á/foo bar/" %}'
         '{% get_email_share_url url="/á/foo bar/" title="á" %}'
         '{% get_share_url url="/á/foo bar/" %}'
     )
     res = t.render(Context({"request": RequestFactory().get("/")}))
     self.assertEqual(
         res.strip(),
         "http://www.facebook.com/sharer.php?s=100&p%5Burl%5D=http%3A%2F%2Ftestserver"
         "%2F%25C3%25A1%2Ffoo%2520bar%2F&p%5Btitle%5D=%C3%A1"
         "https://twitter.com/share?url=http%3A%2F%2Ftestserver%2F%25C3%25A1%2F"
         "foo%2520bar%2F&text=%C3%A1"
         "https://plus.google.com/share?url=http%3A%2F%2Ftestserver%2F%25C3%25A1%2F"
         "foo%2520bar%2F"
         "mailto:?body=http%3A%2F%2Ftestserver%2F%25C3%25A1%2Ffoo%2520bar%2F"
         "&subject=%C3%A1&to="
         "http://testserver/%C3%A1/foo%20bar/",
     )