Пример #1
0
    def test_error_line_number_module(self):
        loader = None

        def load_generate(path, **kwargs):
            return loader.load(path).generate(**kwargs)

        loader = DictLoader(
            {
                "base.html": "{% module Template('sub.html') %}",
                "sub.html": "{{1/0}}",
            },
            namespace={"_tt_modules": ObjectDict(Template=load_generate)})
        try:
            loader.load("base.html").generate()
            self.fail("did not get expected exception")
        except ZeroDivisionError:
            exc_stack = traceback.format_exc()
            self.assertTrue('# base.html:1' in exc_stack)
            self.assertTrue('# sub.html:1' in exc_stack)
Пример #2
0
 def test_error_line_number_module(self):
     loader = DictLoader(
         {
             "base.html": "{% module Template('sub.html') %}",
             "sub.html": "{{1/0}}",
         },
         namespace={
             "_modules":
             ObjectDict({
                 "Template":
                 lambda path, **kwargs: loader.load(path).generate(**kwargs)
             })
         })
     try:
         loader.load("base.html").generate()
     except ZeroDivisionError:
         exc_stack = traceback.format_exc()
         self.assertTrue('# base.html:1' in exc_stack)
         self.assertTrue('# sub.html:1' in exc_stack)
Пример #3
0
    def get_app_kwargs(self):
        loader = DictLoader({
            "linkify.html":
            "{% module linkify(message) %}",
            "page.html":
            """\
<html><head></head><body>
{% for e in entries %}
{% module Template("entry.html", entry=e) %}
{% end %}
</body></html>""",
            "entry.html":
            """\
{{ set_resources(embedded_css=".entry { margin-bottom: 1em; }", embedded_javascript="js_embed()", css_files=["/base.css", "/foo.css"], javascript_files="/common.js", html_head="<meta>", html_body='<script src="/analytics.js"/>') }}
<div class="entry">...</div>""",
        })
        return dict(template_loader=loader,
                    autoescape="xhtml_escape",
                    cookie_secret=self.COOKIE_SECRET)
Пример #4
0
    def test_default_on(self):
        loader = DictLoader(self.templates, autoescape="xhtml_escape")
        name = "Bobby <table>s"
        self.assertEqual(
            loader.load("escaped.html").generate(name=name), b"Bobby &lt;table&gt;s"
        )
        self.assertEqual(
            loader.load("unescaped.html").generate(name=name), b"Bobby <table>s"
        )
        self.assertEqual(
            loader.load("default.html").generate(name=name), b"Bobby &lt;table&gt;s"
        )

        self.assertEqual(
            loader.load("include.html").generate(name=name),
            b"escaped: Bobby &lt;table&gt;s\n"
            b"unescaped: Bobby <table>s\n"
            b"default: Bobby &lt;table&gt;s\n",
        )
Пример #5
0
    def test_whitespace_by_filename(self):
        # Default whitespace handling depends on the template filename.
        loader = DictLoader({
            "foo.html": "   \n\t\n asdf\t   ",
            "bar.js": " \n\n\n\t qwer     ",
            "baz.txt": "\t    zxcv\n\n",
            "include.html": "  {% include baz.txt %} \n ",
            "include.txt": "\t\t{% include foo.html %}    ",
        })

        # HTML and JS files have whitespace compressed by default.
        self.assertEqual(loader.load("foo.html").generate(), b"\nasdf ")
        self.assertEqual(loader.load("bar.js").generate(), b"\nqwer ")
        # TXT files do not.
        self.assertEqual(loader.load("baz.txt").generate(), b"\t    zxcv\n\n")

        # Each file maintains its own status even when included in
        # a file of the other type.
        self.assertEqual(
            loader.load("include.html").generate(), b" \t    zxcv\n\n\n")
        self.assertEqual(
            loader.load("include.txt").generate(), b"\t\t\nasdf     ")
Пример #6
0
    def get_app(self):
        loader = DictLoader({
                "linkify.html": "{% module linkify(message) %}",
                "page.html": """\
<html><head></head><body>
{% for e in entries %}
{% module Template("entry.html", entry=e) %}
{% end %}
</body></html>""",
                "entry.html": """\
{{ set_resources(embedded_css=".entry { margin-bottom: 1em; }", embedded_javascript="js_embed()", css_files=["/base.css", "/foo.css"], javascript_files="/common.js", html_head="<meta>", html_body='<script src="/analytics.js"/>') }}
<div class="entry">...</div>""",
                })
        urls = [
            url("/typecheck/(.*)", TypeCheckHandler, name='typecheck'),
            url("/decode_arg/(.*)", DecodeArgHandler),
            url("/decode_arg_kw/(?P<arg>.*)", DecodeArgHandler),
            url("/linkify", LinkifyHandler),
            url("/uimodule_resources", UIModuleResourceHandler),
            url("/optional_path/(.+)?", OptionalPathHandler),
            ]
        return Application(urls,
                           template_loader=loader,
                           autoescape="xhtml_escape")
Пример #7
0
 def test_custom_namespace(self):
     loader = DictLoader({"test.html": "{{ inc(5) }}"},
                         namespace={"inc": lambda x: x + 1})
     self.assertEqual(loader.load("test.html").generate(), b("6"))
Пример #8
0
 def test_non_ascii_name(self):
     loader = DictLoader({u"t\u00e9st.html": "hello"})
     self.assertEqual(loader.load(u"t\u00e9st.html").generate(), b"hello")
Пример #9
0
    def __init__(
            self, app: micro.Application, handlers: Sequence[Handler], *, port: int = 8080,
            url: str = None, debug: bool = False, client_config: ClientConfigArg = {}) -> None:
        url = url or 'http://*****:*****@noyainrain/micro/service.js'),
            'map_service_key': None,
            'description': 'Social micro web app',
            'color': '#08f',
            'share_target': False,
            'share_target_accept': [],
            **client_config, # type: ignore
            'shell': list(client_config.get('shell') or [])
        } # type: Server.ClientConfig

        self.app.email = 'bot@' + urlparts.hostname
        self.app.render_email_auth_message = self._render_email_auth_message

        def get_activity(*args: str) -> Activity:
            # pylint: disable=unused-argument; part of API
            return self.app.activity
        self.handlers = [
            # API
            (r'/api/users/([^/]+)$', _UserEndpoint),
            (r'/api/users/([^/]+)/set-email$', _UserSetEmailEndpoint),
            (r'/api/users/([^/]+)/finish-set-email$', _UserFinishSetEmailEndpoint),
            (r'/api/users/([^/]+)/remove-email$', _UserRemoveEmailEndpoint),
            (r'/api/users/([^/]+)/devices$', CollectionEndpoint,
             {'get_collection': lambda id: self.app.users[id].devices}), # type: ignore[misc]
            (r'/api/devices$', _DevicesEndpoint),
            (r'/api/devices/([^/]+)$', _DeviceEndpoint),
            (r'/api/settings$', _SettingsEndpoint),
            *make_activity_endpoints(r'/api/activity', get_activity),
            # Provide alias because /api/analytics triggers popular ad blocking filters
            (r'/api/(?:analytics|stats)/statistics/([^/]+)$', _StatisticEndpoint),
            (r'/api/(?:analytics|stats)/referrals$', _ReferralsEndpoint),
            (r'/api/(?:analytics|stats)/referrals/summary$', _ReferralSummaryEndpoint),
            (r'/api/previews/([^/]+)$', _PreviewEndpoint),
            (r'/files$', _FilesEndpoint), # type: ignore[misc]
            (r'/files/([^/]+)$', _FileEndpoint), # type: ignore[misc]
            *handlers,
            # UI
            (r'/log-client-error$', _LogClientErrorEndpoint),
            (r'/index.html$', _Index),
            (r'/manifest.webmanifest$', _WebManifest), # type: ignore
            (r'/manifest.js$', _BuildManifest), # type: ignore
            (fr"/static/{self.client_config['service_path']}$", _Service), # type: ignore
            (r'/static/(.*)$', _Static, {'path': self.client_config['path']}), # type: ignore
            (r'/.*$', UI), # type: ignore
        ] # type: List[Handler]

        application = Application(
            self.handlers, compress_response=True, # type: ignore[arg-type]
            template_path=self.client_config['path'], debug=self.debug, server=self)
        # Install static file handler manually to allow pre-processing
        cast(_ApplicationSettings, application.settings).update(
            {'static_path': self.client_config['path']})
        self._server = HTTPServer(application, xheaders=True)

        self._garbage_collect_files_task = None # type: Optional[Task[None]]
        self._empty_trash_task = None # type: Optional[Task[None]]
        self._collect_statistics_task = None # type: Optional[Task[None]]
        self._message_templates = DictLoader(templates.MESSAGE_TEMPLATES, autoescape=None)
        self._micro_templates = Loader(
            os.path.join(self.client_config['path'], self.client_config['modules_path'],
                         '@noyainrain/micro'))
Пример #10
0
    <div>Path to extract in: <input type="text" id="path" name="path" value="{{ path }}" required></div>
    <div>File: <input type="file" id="file" name="file"></div>
    <div><input type="submit" value="Upload"></div>
</form>
{% if error or success %}
<div class="msg_box">
  {% if error %}<span class="error">{{ error }}</span>{% end %}
  {% if success %}Success!{% end %}
</div>
{% end %}
</body>
</html>
"""

templates = DictLoader({
    'upload': upload_template,
})


class UploadAPIHandler(BaseHandler):
    def initialize(self, **kwargs):
        super().initialize(**kwargs)
        self.path = ''

    def check_xsrf_cookie(self):
        pass

    def write_error(self, status_code: 500, **kwargs):
        error = 'unknown error'
        if 'reason' in kwargs:
            error = kwargs['reason']
Пример #11
0
    v = Column(String)


DCLR_BASE.metadata.create_all(SQLITE_ENGINE)
MAKE_SESSION = sessionmaker(bind=SQLITE_ENGINE)

TEMP_LOADER = DictLoader({
    'rss.xml':
    '''<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
 <title>{{ site }}</title>
 <link>http://wils519.herokuapp.com/rss/{{ site }}</link>
 <description>https://github.com/wanghan519/heroku_tornado</description>
 {% for i in soup %}
 <item>
  <title>{{ i[0] }}</title>
  <link>{{ i[1] }}</link>
  <pubDate>{{ i[2] }}</pubDate>
  <description>{{ i[3] }}</description>
 </item>
 {% end %}
</channel>
</rss>
'''
})


class MyHandler(RequestHandler):
    def initialize(self):
        self.db = MAKE_SESSION()
Пример #12
0
def test_include():
    loader = DictLoader({
        "index.html": '{% include "header.html" %}\nbody text',
        "header.html": "header text",
    })
    print loader.load("index.html").generate()