Пример #1
0
    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ""
        description = ""
        frames = []
        classes = ["traceback"]
        if not self.frames:
            classes.append("noframe-traceback")

        if include_title:
            if self.is_syntax_error:
                title = u"Syntax Error"
            else:
                title = u"Traceback <em>(most recent call last)</em>:"

        for frame in self.frames:
            frames.append(u"<li%s>%s" % (frame.info and u' title="%s"' % escape(frame.info) or u"", frame.render()))

        if self.is_syntax_error:
            description_wrapper = u"<pre class=syntaxerror>%s</pre>"
        else:
            description_wrapper = u"<blockquote>%s</blockquote>"

        return SUMMARY_HTML % {
            "classes": u" ".join(classes),
            "title": title and u"<h3>%s</h3>" % title or u"",
            "frames": u"\n".join(frames),
            "description": description_wrapper % escape(self.exception),
        }
Пример #2
0
def redirect(location, code=302):
    """Return a response object (a WSGI application) that, if called,
    redirects the client to the target location.  Supported codes are 301,
    302, 303, 305, and 307.  300 is not supported because it's not a real
    redirect and 304 because it's the answer for a request with a request
    with defined If-Modified-Since headers.

    .. versionadded:: 0.6
       The location can now be a unicode string that is encoded using
       the :func:`iri_to_uri` function.

    :param location: the location the response should redirect to.
    :param code: the redirect status code. defaults to 302.
    """
    display_location = escape(location)
    if isinstance(location, str):
        location = iri_to_uri(location)
    response = Response(
        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
        '<title>Redirecting...</title>\n'
        '<h1>Redirecting...</h1>\n'
        '<p>You should be redirected automatically to target URL: '
        '<a href="%s">%s</a>.  If not click the link.' %
        (escape(location), display_location), code, mimetype="text/html")
    response.headers["Location"] = location
    return response
Пример #3
0
def _make_text_block(name, content, content_type=None):
    """Helper function for the builder that creates an XML text block."""
    if content_type == "xhtml":
        return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % (name, XHTML_NAMESPACE, content, name)
    if not content_type:
        return u"<%s>%s</%s>\n" % (name, escape(content), name)
    return u'<%s type="%s">%s</%s>\n' % (name, content_type, escape(content), name)
Пример #4
0
    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ''
        frames = []
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')

        if include_title:
            if self.is_syntax_error:
                title = u'Syntax Error'
            else:
                title = u'Traceback <em>(most recent call last)</em>:'

        for frame in self.frames:
            frames.append(u'<li%s>%s' % (
                frame.info and u' title="%s"' % escape(frame.info) or u'',
                frame.render()
            ))

        if self.is_syntax_error:
            description_wrapper = u'<pre class=syntaxerror>%s</pre>'
        else:
            description_wrapper = u'<blockquote>%s</blockquote>'

        return SUMMARY_HTML % {
            'classes':      u' '.join(classes),
            'title':        title and u'<h3>%s</h3>' % title or u'',
            'frames':       u'\n'.join(frames),
            'description':  description_wrapper % escape(self.exception)
        }
Пример #5
0
    def xml_add_links(cls, data):
        """ Returns as many <link> nodes as there are in the datastream. The
        links are then removed from the datastream to allow for further
        processing.

        :param data: the data stream to be rendered as xml.

        .. versionchanged:: 0.5
           Always return ordered items (#441).

        .. versionchanged:: 0.0.6
           Links are now properly escaped.

        .. versionadded:: 0.0.3
        """
        xml = ''
        chunk = '<link rel="%s" href="%s" title="%s" />'
        links = data.pop(config.LINKS, {})
        ordered_links = OrderedDict(sorted(links.items()))
        for rel, link in ordered_links.items():
            if isinstance(link, list):
                xml += ''.join([chunk % (rel, utils.escape(d['href']),
                                         utils.escape(d['title']))
                                for d in link])
            else:
                xml += ''.join(chunk % (rel, utils.escape(link['href']),
                                        link['title']))
        return xml
Пример #6
0
 def render(self):
     """Render a single frame in a traceback."""
     return FRAME_HTML % {
         "id": self.id,
         "filename": escape(self.filename),
         "lineno": self.lineno,
         "function_name": escape(self.function_name),
         "current_line": highlight_or_escape(self.current_line.strip()),
     }
Пример #7
0
 def test_escape(self):
     class Foo(str):
         def __html__(self):
             return text_type(self)
     self.assert_equal(utils.escape(None), '')
     self.assert_equal(utils.escape(42), '42')
     self.assert_equal(utils.escape('<>'), '&lt;&gt;')
     self.assert_equal(utils.escape('"foo"'), '&quot;foo&quot;')
     self.assert_equal(utils.escape(Foo('<foo>')), '<foo>')
Пример #8
0
def test_escape():
    class Foo(str):
        def __html__(self):
            return text_type(self)
    assert utils.escape(None) == ''
    assert utils.escape(42) == '42'
    assert utils.escape('<>') == '&lt;&gt;'
    assert utils.escape('"foo"') == '&quot;foo&quot;'
    assert utils.escape(Foo('<foo>')) == '<foo>'
Пример #9
0
 def render(self):
     """Render a single frame in a traceback."""
     return FRAME_HTML % {
         'id':               self.id,
         'filename':         escape(self.filename),
         'lineno':           self.lineno,
         'function_name':    escape(self.function_name),
         'lines':            self.render_line_context(),
     }
Пример #10
0
 def render(self):
     """Render a single frame in a traceback."""
     return FRAME_HTML % {
         'id':               self.id,
         'filename':         escape(self.filename),
         'lineno':           self.lineno,
         'function_name':    escape(self.function_name),
         'current_line':     escape(self.current_line.strip())
     }
Пример #11
0
def test_escape():
    class Foo(str):
        def __html__(self):
            return text_type(self)

    assert utils.escape(None) == ""
    assert utils.escape(42) == "42"
    assert utils.escape("<>") == "&lt;&gt;"
    assert utils.escape('"foo"') == "&quot;foo&quot;"
    assert utils.escape(Foo("<foo>")) == "<foo>"
Пример #12
0
 def render(self, mark_lib=True):
     """Render a single frame in a traceback."""
     return FRAME_HTML % {
         'id':               self.id,
         'filename':         escape(self.filename),
         'lineno':           self.lineno,
         'function_name':    escape(self.function_name),
         'lines':            self.render_line_context(),
         "library": "library" if mark_lib and self.is_library else "",
     }
Пример #13
0
 def generate(self):
     """Yields pieces of ATOM XML."""
     base = ""
     if self.xml_base:
         base = ' xml:base="%s"' % escape(self.xml_base, True)
     yield u"<entry%s>\n" % base
     yield u"  " + _make_text_block("title", self.title, self.title_type)
     yield u"  <id>%s</id>\n" % escape(self.id)
     yield u"  <updated>%s</updated>\n" % format_iso8601(self.updated)
     if self.published:
         yield u"  <published>%s</published>\n" % format_iso8601(self.published)
     if self.url:
         yield u'  <link href="%s" />\n' % escape(self.url)
     for author in self.author:
         yield u"  <author>\n"
         yield u"    <name>%s</name>\n" % escape(author["name"])
         if "uri" in author:
             yield u"    <uri>%s</uri>\n" % escape(author["uri"])
         if "email" in author:
             yield u"    <email>%s</email>\n" % escape(author["email"])
         yield u"  </author>\n"
     for link in self.links:
         yield u"  <link %s/>\n" % "".join('%s="%s" ' % (k, escape(link[k], True)) for k in link)
     for category in self.categories:
         yield u"  <category %s/>\n" % "".join('%s="%s" ' % (k, escape(category[k], True)) for k in category)
     if self.summary:
         yield u"  " + _make_text_block("summary", self.summary, self.summary_type)
     if self.content:
         yield u"  " + _make_text_block("content", self.content, self.content_type)
     if self.lat_lon:
         yield u"  <georss:point>%s</georss:point>\n" % escape(" ".join(self.lat_lon))
     yield u"</entry>\n"
Пример #14
0
 def render_object_dump(self, items, title, repr=None):
     html_items = []
     for key, value in items:
         html_items.append('<tr><th>%s<td><pre class=repr>%s</pre>' %
                           (escape(key), value))
     if not html_items:
         html_items.append('<tr><td><em>Nothing</em>')
     return OBJECT_DUMP_HTML % {
         'title':    escape(title),
         'repr':     repr and '<pre class=repr>%s</pre>' % repr or '',
         'items':    '\n'.join(html_items)
     }
Пример #15
0
def _make_text_block(name, content, content_type = None):
    if content_type == 'xhtml':
        return u'<%s type="xhtml"><div xmlns="%s">%s</div></%s>\n' % (name,
         XHTML_NAMESPACE,
         content,
         name)
    if not content_type:
        return u'<%s>%s</%s>\n' % (name, escape(content), name)
    return u'<%s type="%s">%s</%s>\n' % (name,
     content_type,
     escape(content),
     name)
Пример #16
0
def make_report():
    lat = escape(request.get_json()['lat'])
    lng = escape(request.get_json()['lng'])
    description = escape(request.get_json()['description'])
    category_id = escape(request.get_json()['category_id'])
    user_id = session[SESSION_ID_KEY]
    category = category_service.get_by_id(category_id)
    user = user_service.get_by_id(user_id)
    if user is not None and category is not None:
        report = report_service.make_report(lat, lng, description, round(time.time()*1000), user, category)
        return dumps(report_service.report_to_dict(report))
    else:
        return redirect(url_for('not_found'))
Пример #17
0
 def generate(self):
     """Yields pieces of ATOM XML."""
     base = ''
     if self.xml_base:
         base = ' xml:base="%s"' % escape(self.xml_base, True)
     yield u'<entry%s>\n' % base
     yield u'  ' + _make_text_block('title', self.title, self.title_type)
     yield u'  <id>%s</id>\n' % escape(self.id)
     yield u'  <updated>%s</updated>\n' % format_iso8601(self.updated)
     if self.published:
         yield u'  <published>%s</published>\n' % \
               format_iso8601(self.published)
     if self.url:
         yield u'  <link href="%s" />\n' % escape(self.url)
     for author in self.author:
         yield u'  <author>\n'
         yield u'    <name>%s</name>\n' % escape(author['name'])
         if 'uri' in author:
             yield u'    <uri>%s</uri>\n' % escape(author['uri'])
         if 'email' in author:
             yield u'    <email>%s</email>\n' % escape(author['email'])
         yield u'  </author>\n'
     for link in self.links:
         yield u'  <link %s/>\n' % ''.join('%s="%s" ' % \
             (k, escape(link[k], True)) for k in link)
     for category in self.categories:
         yield u'  <category %s/>\n' % ''.join('%s="%s" ' % \
             (k, escape(category[k], True)) for k in category)
     if self.summary:
         yield u'  ' + _make_text_block('summary', self.summary,
                                        self.summary_type)
     if self.content:
         yield u'  ' + _make_text_block('content', self.content,
                                        self.content_type)
     yield u'</entry>\n'
Пример #18
0
 def string_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     a = repr(obj[:limit])
     b = repr(obj[limit:])
     if isinstance(obj, text_type) and PY2:
         buf.append('u')
         a = a[1:]
         b = b[1:]
     if b != "''":
         buf.extend((escape(a[:-1]), '<span class="extended">', escape(b[1:]), '</span>'))
     else:
         buf.append(escape(a))
     buf.append('</span>')
     return _add_subclass_info(u''.join(buf), obj, (bytes, text_type))
Пример #19
0
 def render_full(self, evalex=False, secret=None):
     """Render the Full HTML page with the traceback info."""
     exc = escape(self.exception)
     return PAGE_HTML % {
         "evalex": evalex and "true" or "false",
         "console": "false",
         "title": exc,
         "exception": exc,
         "exception_type": escape(self.exception_type),
         "summary": self.render_summary(include_title=False),
         "plaintext": self.plaintext,
         "plaintext_cs": re.sub("-{2,}", "-", self.plaintext),
         "traceback_id": self.id,
         "secret": secret,
     }
Пример #20
0
 def get_body(self, environ=None):
     """Get the XML body."""
     return text_type((
         u'<?xml version="1.0" encoding="UTF-8"?>\n'
         u'<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 ../../../ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">'
         u'<ows:Exception exceptionCode="%(name)s" locator="%(locator)s" >'
         u'%(description)s'
         u'</ows:Exception>'
         u'</ows:ExceptionReport>'
     ) % {
         'code':         self.code,
         'locator':         escape(self.locator),
         'name':         escape(self.name),
         'description':  self.get_description(environ)
     })
Пример #21
0
 def render_full(self, evalex=False, lodgeit_url=None):
     """Render the Full HTML page with the traceback info."""
     exc = escape(self.exception)
     return PAGE_HTML % {
         'evalex':           evalex and 'true' or 'false',
         'console':          'false',
         'lodgeit_url':      escape(lodgeit_url),
         'title':            exc,
         'exception':        exc,
         'exception_type':   escape(self.exception_type),
         'summary':          self.render_summary(include_title=False),
         'plaintext':        self.plaintext,
         'plaintext_cs':     re.sub('-{2,}', '-', self.plaintext),
         'traceback_id':     self.id
     }
Пример #22
0
    def render_summary(self, include_title=True):
        """Render the traceback for the interactive console."""
        title = ''
        classes = ['traceback']
        if not self.frames:
            classes.append('noframe-traceback')
            frames = []
        else:
            library_frames = sum(frame.is_library for frame in self.frames)
            mark_lib = 0 < library_frames < len(self.frames)
            frames = [group.render(mark_lib=mark_lib) for group in self.groups]

        if include_title:
            if self.is_syntax_error:
                title = u'Syntax Error'
            else:
                title = u'Traceback <em>(most recent call last)</em>:'

        if self.is_syntax_error:
            description_wrapper = u'<pre class=syntaxerror>%s</pre>'
        else:
            description_wrapper = u'<blockquote>%s</blockquote>'

        return SUMMARY_HTML % {
            'classes':      u' '.join(classes),
            'title':        u'<h3>%s</h3>' % title if title else u'',
            'frames':       u'\n'.join(frames),
            'description':  description_wrapper % escape(self.exception)
        }
Пример #23
0
 def render_line(line, cls):
     line = line.expandtabs().rstrip()
     stripped_line = line.strip()
     prefix = len(line) - len(stripped_line)
     rv.append(
         '<pre class="line %s"><span class="ws">%s</span>%s</pre>' % (
             cls, ' ' * prefix, escape(stripped_line) or ' '))
Пример #24
0
    def cmd_upgrade(self, repo_id=None, version=None, **opts):
        """Upgrade a database to a later version.

        This runs the upgrade() function defined in your change scripts.

        By default, the database is updated to the latest available
        version. You may specify a version instead, if you wish.

        You may preview the Python or SQL code to be executed, rather than
        actually executing it, using the appropriate 'preview' option.
        """
        from zine.models import SchemaVersion

        if repo_id is None:
            # get all repos, sort those with id "Zine*" first
            available_svs = sorted(
                SchemaVersion.query.order_by(SchemaVersion.repository_id.asc()),
                key=lambda sv: not sv.repository_id.startswith("Zine"),
            )
        else:
            available_svs = [SchemaVersion.query.get(repo_id)]
        # Now, run the available schema version upgrades
        for sv in available_svs:
            try:
                repository = api.Repository(sv.repository_path, sv.repository_id)
                for message in self._migrate(repository, version, upgrade=True, **opts):
                    yield message
            except Exception, msg:
                yield "<p>error upgrading %s: " % sv.repository_id
                yield escape(str(msg).decode("utf-8", "ignore"))
                yield "</p>\n"
Пример #25
0
    def put(self, book_id):
        form = BookForm()
        if form.validate_on_submit():
            book = Book.query.get(book_id)
            book.title = escape(form.data['title'])

            # escape() is overkill here
            authors = [Author.query.filter_by(name=escape(submitted_artist_name)).first()
                       for submitted_artist_name in request.json["authors"]
            ]
            # remove all nonexistent objects (they are not in DB)
            authors = list(filter(None, authors))
            # FIXME: Old M2M relations is not removed. Refactoring needed
            book.authors = authors

            db.session.commit()
Пример #26
0
 def edit_template(self, tid):
     def generate_global_vars(var_tree):
         for name, value in var_tree.items():
             if type(value) == dict:
                 for name2, value2 in value.items():
                     yield {'name': '%s.%s' % (name, name2), 'value': str(value2)}
             elif type(value) == list:
                 yield {'name': '{%% for item in %s %%}' % name}
                 for i, item in enumerate(value):
                     if type(item) == dict:
                         yield {'name': 'item %d' % i, 'indent': 20}
                         for k, v in item.items():
                             yield {'name': '{{ item.%s }}' % k, 'value': str(v), 'indent': 40}
                     else:
                         yield {'name': '{{ item }}', 'value': str(item), 'indent': 20}
                 yield {}
             else:
                 yield {'name': '{{ %s }}' % name, 'value': str(value)}
             
     self.context['help_statement'] = """
         <p>Template names should contain <span class="code">.template.</span> in their name, eg. <span class="code">my_template.template.html</span>.</p>
         <p>Templates are rendered using <a href="http://jinja.pocoo.org/docs/">Jinja2</a> which is a "Django like" template engine. See their site for Documentation.</p>
     """
     if tid is not None:
         t = ds.con.Templates()
         cfile, template_text = t.get_file_content(fid=tid)
         self.context['file_name'] = cfile.name
         self.context['active_repo'] = cfile.repo
         self.context['file_text'] = escape(template_text)
     self.context['global_variables'] = generate_global_vars(ds.SiteGenerator().global_context())
     self.context['show_file_text'] = True
     self.context['function'] = 'edit-template'
     self.context['save_gen_func'] = 'edit-template-gen'
     self.context['delete_action'] = 'delete-template'
     self._template = self._env.get_template('edit_file.html')
Пример #27
0
def index(request):
    return Response('''
        <title>Logged in</title>
        <h1>Logged in</h1>
        <p>Logged in as %s
        <p><a href="/?do=logout">Logout</a>
    ''' % escape(request.user), mimetype='text/html')
Пример #28
0
 def fallback_repr(self):
     try:
         info = ''.join(format_exception_only(*sys.exc_info()[:2]))
     except Exception: # pragma: no cover
         info = '?'
     return u'<span class="brokenrepr">&lt;broken repr (%s)&gt;' \
            u'</span>' % escape(info.decode('utf-8', 'ignore').strip())
Пример #29
0
def on_index(request):
    if request.method == 'POST':
        letters = escape(request.form['letters'])
        if len(letters) != 25:
            return {'error': 'There has to be 25 letters'}
        return inner_redirect('game', {'letters': letters})
    return {}
Пример #30
0
    def xml_dict(cls, data):
        """ Renders a dict as XML.

        :param data: the data stream to be rendered as xml.

        .. versionchanged:: 0.5
           Always return ordered items (#441).

        .. versionchanged:: 0.2
           Leaf values are now properly escaped.

        .. versionadded:: 0.0.3
        """
        xml = ''
        ordered_items = OrderedDict(sorted(data.items()))
        for k, v in ordered_items.items():
            if isinstance(v, datetime.datetime):
                v = date_to_str(v)
            elif isinstance(v, (datetime.time, datetime.date)):
                v = v.isoformat()
            if not isinstance(v, list):
                v = [v]
            for value in v:
                if isinstance(value, dict):
                    links = cls.xml_add_links(value)
                    xml += "<%s>" % k
                    xml += cls.xml_dict(value)
                    xml += links
                    xml += "</%s>" % k
                else:
                    xml += "<%s>%s</%s>" % (k, utils.escape(value), k)
        return xml
Пример #31
0
def demo2(environ, start_response):
    result = ['<title>Greeter</title>']
    if environ['REQUEST_METHOD'] == 'POST':
        form = parse_form_data(environ)[1]
        result.append('<h1>what %s!</h1>' % escape(form['name']))
    result.append('''
        <form action="" method="post">
            <p>Name: <input type="text" name="name" size="20">
            <input type="submit" value="Greet me">
        </form>
    ''')
    start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
    return [''.join(result)]
Пример #32
0
 def get_body(self, environ=None):
     """Get the XML body."""
     args = {
         'name': escape(self.name),
         'description': self.get_description(environ)
     }
     return str((
         '<?xml version="1.0" encoding="UTF-8"?>\n'
         '<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 ../../../ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">'  # noqa
         '<ows:Exception exceptionCode="{name}">'
         '{description}'
         '</ows:Exception>'
         '</ows:ExceptionReport>').format(**args))
Пример #33
0
def xml_add_links(data):
    """ Returns as many <link> nodes as there are in the datastream. The links
    are then removed from the datastream to allow for further processing.

    :param data: the data stream to be rendered as xml.

    .. versionchanged:: 0.0.6
       Links are now properly escaped.

    .. versionadded:: 0.0.3
    """
    xml = ''
    chunk = '<link rel="%s" href="%s" title="%s" />'
    links = data.pop(config.LINKS, {})
    for rel, link in links.items():
        if isinstance(link, list):
            xml += ''.join([chunk % (rel, utils.escape(d['href']), d['title'])
                            for d in link])
        else:
            xml += ''.join(chunk % (rel, utils.escape(link['href']),
                                    link['title']))
    return xml
Пример #34
0
def redirect(location, code=302, Response=None):
    """Returns a response object (a ASGI application) that, if called,
    redirects the client to the target location.  Supported codes are 301,
    302, 303, 305, and 307.  300 is not supported because it's not a real
    redirect and 304 because it's the answer for a request with a request
    with defined If-Modified-Since headers.

    .. versionadded:: 0.6
       The location can now be a unicode string that is encoded using
       the :func:`iri_to_uri` function.

    .. versionadded:: 0.10
        The class used for the Response object can now be passed in.

    :param location: the location the response should redirect to.
    :param code: the redirect status code. defaults to 302.
    :param class Response: a Response class to use when instantiating a
        response. The default is :class:`werkzeug.wrappers.Response` if
        unspecified.
    """
    if Response is None:
        from apistar.http import HTMLResponse as Response

    display_location = escape(location)
    if isinstance(location, text_type):
        # Safe conversion is necessary here as we might redirect
        # to a broken URI scheme (for instance itms-services).
        from werkzeug.urls import iri_to_uri
        location = iri_to_uri(location, safe_conversion=True)
    response = Response(
        '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
        '<title>Redirecting...</title>\n'
        '<h1>Redirecting...</h1>\n'
        '<p>You should be redirected automatically to target URL: '
        '<a href="%s">%s</a>.  If not click the link.' %
        (escape(location), display_location),
        headers={"Location": location},
        status_code=code)
    return response
Пример #35
0
 def get_body(self, environ=None):
     """Get the XML body."""
     return text_type(
         (
             u'<?xml version="1.0" encoding="UTF-8"?>\n'
             u'<ows:ExceptionReport xmlns:ows="http://www.opengis.net/ows/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/ows/1.1 ../../../ows/1.1.0/owsExceptionReport.xsd" version="1.0.0">'  # noqa
             u'<ows:Exception exceptionCode="%(name)s">'
             u'%(description)s'
             u'</ows:Exception>'
             u'</ows:ExceptionReport>') % {
                 'name': escape(self.name),
                 'description': self.get_description(environ)
             })
Пример #36
0
    def wiki_link(self, addr, label=None, class_=None, image=None, lineno=0):
        """Create HTML for a wiki link."""

        addr = addr.strip()
        text = escape(label or addr)
        chunk = ''
        if class_ is not None:
            classes = [class_]
        else:
            classes = []
        if hatta.parser.external_link(addr):
            classes.append('external')
            if addr.startswith('mailto:'):
                # Obfuscate e-mails a little bit.
                classes.append('mail')
                text = text.replace('@', '&#64;').replace('.', '&#46;')
                href = escape(addr).replace('@', '%40').replace('.', '%2E')
            else:
                href = escape(url_fix(addr))
        else:
            if '#' in addr:
                addr, chunk = addr.split('#', 1)
                chunk = '#' + url_fix(chunk)
            if addr.startswith(':'):
                alias = self.link_alias(addr[1:])
                href = escape(url_fix(alias) + chunk)
                classes.append('external')
                classes.append('alias')
            elif addr.startswith('+'):
                href = '/'.join(
                    [self.request.script_root, '+' + escape(addr[1:])])
                classes.append('special')
            elif addr == '':
                href = escape(chunk)
                classes.append('anchor')
            else:
                classes.append('wiki')
                href = escape(self.get_url(addr) + chunk)
                if addr not in self.storage:
                    classes.append('nonexistent')
        class_ = escape(' '.join(classes) or '')
        # We need to output HTML on our own to prevent escaping of href
        return '<a href="%s" class="%s" title="%s">%s</a>' % (
            href, class_, escape(addr + chunk), image or text)
Пример #37
0
 def get_body(environ=None):
     res = {"code": exception.code, "name": escape(exception.name)}
     description = exception.get_description(environ)
     if config.get_misc("base_rest", "dev_mode"):
         # return exception info only if base_rest is in dev_mode
         res.update({
             "traceback": exception.traceback,
             "description": description
         })
     elif include_description:
         res["description"] = description
     res.update(extra_info or {})
     return JSONEncoder().encode(res)
Пример #38
0
def edit_item(item_id):
    conn = get_db()
    c = conn.cursor()
    item_from_db = c.execute("SELECT * FROM items WHERE id = ?", (item_id, ))
    row = c.fetchone()
    try:
        item = {
            "id": row[0],
            "title": row[1],
            "description": row[2],
            "price": row[3],
            "image": row[4]
        }
    except:
        item = {}
    if item:
        form = EditItemForm()
        if form.validate_on_submit():
            filename = item["image"]
            if form.image.data:
                filename = save_image_upload(form.image)
            c.execute(
                """UPDATE items SET title = ?, description = ?, price =?, image=? WHERE id=?""",
                (
                    escape(form.title.data),
                    escape(form.description.data),
                    float(form.price.data),
                    filename,
                    item_id,
                ))
            conn.commit()
            flash(f"Item {form.title.data} has been successfully updated",
                  "success")
            return redirect(url_for('item', item_id=item_id))
        form.title.data = item["title"]
        form.description.data = unescape(item["description"])
        form.price.data = item["price"]
        return render_template("edit_item.html", item=item, form=form)
    return redirect(url_for("home"))
Пример #39
0
 def mobile_send_letter(self, *params, **parameters):
     """
     Function called by the app upon clicking on send letter.
     We search for the s2b_generator that we used for the preview generation
     Once we have it, we proceed to sending it.
     This function is called two times by the app for unknown dark reasons.
     The second time the parameters contains the DbId of the letter we just
     sent. If the parameter is present, we already sent the letter and
     therefore return early.
     :param params: A dictionary containing:
                        - 'TemplateID': ID of the template
                        - 'Need': ID of the child the letter is sent to
                        - 'DbID': (optional) Indicator that the letter was
                                  already sent.
     :return: The ID of the sent letter, never used by the app.
     """
     params = params[0]
     params['Message'] = escape(params.get('Message', ''))
     template_id = self._get_required_param('TemplateID', params)
     if 'DbId' in params:
         # The letter was submitted on the last api call
         if template_id == "0":
             return "Letter Submitted "
         return "Card Submitted "
     # body = self._get_required_param('Message', params)
     # partner_id = self._get_required_param('SupporterId', params)
     # iOS and Android do not return the same format
     if template_id == '0' or template_id == 0:
         # write a card -> default template
         template_id = self.env['mobile.app.settings'].get_param(
             'default_s2b_template_id')
     child_id = self._get_required_param('Need', params)
     if isinstance(child_id, list):
         child_id = child_id[0]
     child = \
         self.env['compassion.child'].browse(int(child_id))
     gen = self.env['correspondence.s2b.generator'].sudo().search(
         [('name', '=', 'app-' + child.local_id),
          ('sponsorship_ids.child_id', '=', child.id),
          ('s2b_template_id', '=', int(template_id)),
          ('state', '=', 'preview')],
         limit=1,
         order='create_date DESC')
     gen.generate_letters_job()
     gen.write({
         'state': 'done',
         'date': fields.Datetime.now(),
     })
     return {
         'DbId': gen.letter_ids.mapped('id'),
     }
Пример #40
0
def index():
    animal.set_animal('wombat')  # modifies g in animal module

    html = '<html><head><title>Context Objects</title></head><body>\n'

    html += '<h1>Context Objects</h1>\n'

    html += '<h2>Request Object</h2>\n'
    html += '<table border="1">\n'
    html += '<tr><th>Attribute</th><th>Object Type</th><th>Value</th></tr>\n'
    for attribute_name in dir(request):
        if not attribute_name.startswith('_'):
            attribute = getattr(request, attribute_name)
            type_name = type(attribute).__name__
            type_name = type_name if type_name else '&nbsp'
            attribute_value = escape(str(attribute))
            html += '<tr><td>{}</td><td>{!s}</td><td>{!s}</td></tr>\n'.format(
                attribute_name, type_name, attribute_value)

    html += '</table>\n'

    html += '<h2>g (Global) Object</h2>\n'
    html += '<table border="1">\n'
    html += '<tr><th>Attribute</th><th>Object Type</th><th>Value</th></tr>\n'
    for attribute_name in dir(g):
        if not attribute_name.startswith('_'):
            attribute = getattr(g, attribute_name)
            type_name = type(attribute).__name__
            type_name = type_name if type_name else '&nbsp'
            attribute_value = escape(str(attribute))
            html += '<tr><td>{}</td><td>{!s}</td><td>{!s}</td></tr>\n'.format(
                attribute_name, type_name, attribute_value)

    html += '</table>\n'

    html += '</body></html>\n'

    return html
Пример #41
0
def render_testapp(req):
    try:
        import pkg_resources
    except ImportError:
        eggs = ()
    else:
        eggs = list(pkg_resources.working_set)
        eggs.sort(
            lambda a, b: cmp(a.project_name.lower(), b.project_name.lower()))
    python_eggs = []
    for egg in eggs:
        try:
            version = egg.version
        except (ValueError, AttributeError):
            version = 'unknown'
        python_eggs.append('<li>%s <small>[%s]</small>' %
                           (escape(egg.project_name), escape(version)))

    wsgi_env = []
    sorted_environ = req.environ.items()
    sorted_environ.sort(key=lambda x: repr(x[0]).lower())
    for key, value in sorted_environ:
        wsgi_env.append(
            '<tr><th>%s<td><code>%s</code>' %
            (escape(str(key)), ' '.join(wrap(escape(repr(value))))))

    sys_path = []
    for item, virtual, expanded in iter_sys_path():
        class_ = []
        if virtual:
            class_.append('virtual')
        if expanded:
            class_.append('exp')
        sys_path.append(
            '<li%s>%s' %
            (class_ and ' class="%s"' % ' '.join(class_) or '', escape(item)))

    return TEMPLATE % {
        'python_version': '<br>'.join(escape(sys.version).splitlines()),
        'platform': escape(sys.platform),
        'os': escape(os.name),
        'api_version': sys.api_version,
        'byteorder': sys.byteorder,
        'werkzeug_version': werkzeug.__version__,
        'python_eggs': '\n'.join(python_eggs),
        'wsgi_env': '\n'.join(wsgi_env),
        'sys_path': '\n'.join(sys_path)
    }
Пример #42
0
def comment():
    conn = get_db()
    c = conn.cursor()

    form = CommentForm()

    if form.validate_on_submit():
        c.execute(
            '''INSERT INTO comment (content, item_id)
         VALUES (?,?)
        ''', (escape(form.content.data), form.item_id.data))

        conn.commit()
    return redirect(url_for('item.item', item_id=form.item_id.data))
Пример #43
0
 def dispatch_request(self, req):
     adapter = self.url_map.bind_to_environ(req.environ)
     try:
         endpoint, _ = adapter.match()
         resp = getattr(self, 'on_' + endpoint)(req)
     except HTTPException as exc:
         resp = exc
     except Exception as exc:
         if self.logger:
             self.logger.exception('ERROR Unhandled exception in request')
         resp = InternalServerError('Unmanaged error: %s' % exc)
     if isinstance(resp, HTTPException) and not resp.response:
         resp.response = Response(escape(resp.description), resp.code)
     return resp
Пример #44
0
def new_item():
    conn = get_db()
    c = conn.cursor()
    form = NewItemForm()

    c.execute("SELECT id, name FROM categories")
    categories = c.fetchall()
    # [(1, 'Food'), (2, 'Technology'), (3, 'Books')]
    form.category.choices = categories

    c.execute("SELECT id, name FROM subcategories")
    subcategories = c.fetchall()
    form.subcategory.choices = subcategories

    # pdb.set_trace()
    # if request.method == 'POST':
    if form.validate_on_submit() and form.image.validate(
            form, extra_validators=(FileRequired(), )):
        filename = save_image_upload(form.image)

        # Process the form data
        c.execute(
            """INSERT INTO items
                    (title, description, price, image, category_id, subcategory_id)
                    VALUES(?,?,?,?,?,?)""",
            (escape(form.title.data), escape(
                form.description.data), float(form.price.data), filename,
             form.category.data, form.subcategory.data))
        conn.commit()
        # Redirect to some page
        flash(f"Item {request.form['title']} has been successfully submitted",
              "success")
        return redirect(url_for('home'))

    # if form.errors:
    #     flash(f"{form.errors}", "danger")
    return render_template("new_item.html", form=form)
Пример #45
0
    def xml_add_links(cls, data):
        """ Returns as many <link> nodes as there are in the datastream. The
        added links are then removed from the datastream to allow for further
        processing.

        :param data: the data stream to be rendered as xml.

        .. versionchanged:: 0.8.2
           Keep data relation links in the datastream as they will be
           processed as node attributes in xml_dict

        .. versionchanged:: 0.5
           Always return ordered items (#441).

        .. versionchanged:: 0.0.6
           Links are now properly escaped.

        .. versionadded:: 0.0.3
        """
        xml = ""
        chunk = '<link rel="%s" href="%s" title="%s" />'
        links = data.pop(config.LINKS, {})
        ordered_links = OrderedDict(sorted(links.items()))
        for rel, link in ordered_links.items():
            if rel == "related":
                # add data relation links back for
                # future processing of hateoas attributes
                data.update({config.LINKS: {rel: link}})

            elif isinstance(link, list):
                xml += "".join(                    
                    chunk % (rel, utils.escape(d["href"]), utils.escape(d["title"]))
                    for d in link                    
                )
            else:
                xml += "".join(chunk % (rel, utils.escape(link["href"]), link["title"]))
        return xml
Пример #46
0
def render_testapp(req):
    try:
        import pkg_resources
    except ImportError:
        eggs = ()
    else:
        eggs = sorted(pkg_resources.working_set,
                      key=lambda x: x.project_name.lower())
    python_eggs = []
    for egg in eggs:
        try:
            version = egg.version
        except (ValueError, AttributeError):
            version = "unknown"
        python_eggs.append("<li>%s <small>[%s]</small>" %
                           (escape(egg.project_name), escape(version)))

    wsgi_env = []
    sorted_environ = sorted(req.environ.items(),
                            key=lambda x: repr(x[0]).lower())
    for key, value in sorted_environ:
        wsgi_env.append(
            "<tr><th>%s<td><code>%s</code>" %
            (escape(str(key)), " ".join(wrap(escape(repr(value))))))

    sys_path = []
    for item, virtual, expanded in iter_sys_path():
        class_ = []
        if virtual:
            class_.append("virtual")
        if expanded:
            class_.append("exp")
        sys_path.append(
            "<li%s>%s" %
            (class_ and ' class="%s"' % " ".join(class_) or "", escape(item)))

    return (TEMPLATE % {
        "python_version": "<br>".join(escape(sys.version).splitlines()),
        "platform": escape(sys.platform),
        "os": escape(os.name),
        "api_version": sys.api_version,
        "byteorder": sys.byteorder,
        "werkzeug_version": werkzeug.__version__,
        "python_eggs": "\n".join(python_eggs),
        "wsgi_env": "\n".join(wsgi_env),
        "sys_path": "\n".join(sys_path),
    }).encode("utf-8")
Пример #47
0
def post_register():
    logging.debug('post_register()')
    first_name = escape(request.form['first_name'])
    last_name = escape(request.form['last_name'])
    email = request.form['email']
    username = escape(request.form['username'])

    password = sha256_crypt.hash((str(request.form['password'])))

    user = User()
    user.email = email
    user.first_name = first_name
    user.last_name = last_name
    user.password = password
    user.username = username
    user.authenticated = True
    user.active = True

    db.session.add(user)
    db.session.commit()

    response = jsonify({'message': 'User added', 'result': user.to_json()})

    return response
Пример #48
0
    def _validate_music_title(music_title):
        """Validates music title.

        Max title length - 45 symbols.
        Title must be .mp3"""

        if len(music_title) <= 45:
            music_title = escape(music_title)

            if not music_title.endswith('.mp3'):
                music_title: str = f'{music_title}.mp3'

            return music_title
        else:
            raise ValueError('The title is too long')
Пример #49
0
    def string_repr(self, obj, limit=70):
        buf = ['<span class="string">']
        r = repr(obj)

        # shorten the repr when the hidden part would be at least 3 chars
        if len(r) - limit > 2:
            buf.extend((
                escape(r[:limit]),
                '<span class="extended">',
                escape(r[limit:]),
                '</span>',
            ))
        else:
            buf.append(escape(r))

        buf.append('</span>')
        out = u"".join(buf)

        # if the repr looks like a standard string, add subclass info if needed
        if r[0] in "'\"" or (r[0] in "ub" and r[1] in "'\""):
            return _add_subclass_info(out, obj, (bytes, text_type))

        # otherwise, assume the repr distinguishes the subclass already
        return out
Пример #50
0
    def xml_field_open(cls, field, idx, related_links):
        """ Returns opening tag for XML field element node.

        :param field: field name for the element node
        :param idx: the index in the data relation links if serializing a list of same field to XML
        :param related_links: a dictionary that stores all data relation links

        .. versionadded:: 0.8.2
        """
        if field in related_links:
            if isinstance(related_links[field], list):
                return '<%s href="%s" title="%s">' % (
                    field,
                    utils.escape(related_links[field][idx]["href"]),
                    related_links[field][idx]["title"],
                )
            else:
                return '<%s href="%s" title="%s">' % (
                    field,
                    utils.escape(related_links[field]["href"]),
                    related_links[field]["title"],
                )
        else:
            return "<%s>" % field
Пример #51
0
def add_comment():
    conn = get_db()
    c = conn.cursor()
    form = NewCommentForm()

    is_ajax = True

    if form.validate_on_submit():
        c.execute("""INSERT INTO comments (content, item_id) VALUES (?, ?)""",
                  (escape(form.content.data), form.item_id.data))
        conn.commit()

    if is_ajax:
        return render_template("/_comment.html", content=form.content.data)
    return redirect(url_for("items.get_item", item_id=form.item_id.data))
Пример #52
0
 def get_body(environ=None):
     res = {
         'code': exception.code,
         'name': escape(exception.name),
     }
     description = exception.get_description(environ)
     if config.get_misc('base_rest', 'dev_mode'):
         # return exception info only if base_rest is in dev_mode
         res.update({
             'traceback': exception.traceback,
             'description': description
         })
     elif include_description:
         res['description'] = description
     return JSONEncoder().encode(res)
Пример #53
0
 def string_repr(self, obj, limit=70):
     buf = ['<span class="string">']
     escaped = escape(obj)
     a = repr(escaped[:limit])
     b = repr(escaped[limit:])
     if isinstance(obj, text_type) and PY2:
         buf.append('u')
         a = a[1:]
         b = b[1:]
     if b != "''":
         buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
     else:
         buf.append(a)
     buf.append('</span>')
     return _add_subclass_info(u''.join(buf), obj, (bytes, text_type))
def low_hello_world(environ, start_response):
    result = ['<title>Greeter</title>']
    if environ['REQUEST_METHOD'] == 'POST':
        form = parse_form_data(environ)[1]
        result.append('<h1>Hello %s!' % escape(form['name']))
    result.append('''
        <form action="" method="post">
        Name: <input type="text" size="20" name="name">
        <input type="submit">
        </form>
        ''')
    start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
    return [
        ''.join([bytes(i) for i in result])
    ]  #TODO 中文提交 UnicodeEncodeError  原文[''.join(result)]  AssertionError: applications must write bytes
    def process_wp_confirmed_donation(self, donnation_infos):
        """
        Utility to process the donation done via wordpress.
        :return:
        """
        for key in donnation_infos:
            donnation_infos[key] = escape(donnation_infos[key])

        match_obj = self.env['res.partner.match.wp']

        # Extract the partner infos
        partner_fields = {  # wp_field : odoo_field
            'email': 'email',
            'first_name': 'firstname',
            'last_name': 'lastname',
            'street': 'street',
            'zipcode': 'zip',
            'city': 'city',
            'language': 'lang',
            'partner_ref': 'ref',
        }
        partner_infos = {
            'company_id': self.env.user.company_id.id
        }
        for wp_field, odoo_field in partner_fields.iteritems():
            partner_infos[odoo_field] = donnation_infos[wp_field]

        # Find the matching odoo country
        partner_infos['country_id'] = match_obj.match_country(
            donnation_infos['country'], partner_infos['lang']).id

        # Find matching partner
        partner = match_obj.match_partner_to_infos(partner_infos)

        # Insert the donation details to the database.
        pf_brand = donnation_infos['pf_brand']
        pf_pm = donnation_infos['pf_pm']
        if pf_brand != pf_pm:
            payment_mode = "{}_{}".format(pf_brand, pf_pm)
        else:
            payment_mode = pf_brand

        return self.create_from_wordpress(
            partner.id, donnation_infos['orderid'], donnation_infos['amount'],
            donnation_infos['fund'], donnation_infos['child_id'],
            donnation_infos['pf_payid'], payment_mode.strip(),
            donnation_infos['utm_source'], donnation_infos['utm_medium'],
            donnation_infos['utm_campaign'])
Пример #56
0
 def test_escape(self):
     class Foo(str):
         def __html__(self):
             return unicode(self)
     assert utils.escape(None) == ''
     assert utils.escape(42) == '42'
     assert utils.escape('<>') == '&lt;&gt;'
     assert utils.escape('"foo"') == '"foo"'
     assert utils.escape('"foo"', True) == '&quot;foo&quot;'
     assert utils.escape(Foo('<foo>')) == '<foo>'
Пример #57
0
 def runsource(self, source):
     source = source.rstrip() + "\n"
     ThreadedStream.push()
     prompt = self.more and "... " or ">>> "
     try:
         source_to_eval = "".join(self.buffer + [source])
         if code.InteractiveInterpreter.runsource(self, source_to_eval,
                                                  "<debugger>", "single"):
             self.more = True
             self.buffer.append(source)
         else:
             self.more = False
             del self.buffer[:]
     finally:
         output = ThreadedStream.fetch()
     return prompt + escape(source) + output
Пример #58
0
 def runsource(self, source):
     source = source.rstrip() + '\n'
     ThreadedStream.push()
     prompt = self.more and '... ' or '>>> '
     try:
         source_to_eval = ''.join(self.buffer + [source])
         if code.InteractiveInterpreter.runsource(self, source_to_eval,
                                                  '<debugger>', 'single'):
             self.more = True
             self.buffer.append(source)
         else:
             self.more = False
             del self.buffer[:]
     finally:
         output = ThreadedStream.fetch()
     return prompt + escape(source) + output
Пример #59
0
    def process_wp_confirmed_donation(self, donnation_infos):
        """
        Utility to process the donation done via wordpress.
        :return:
        """
        for key in donnation_infos:
            donnation_infos[key] = escape(donnation_infos[key])

        match_obj = self.env["res.partner.match.wp"]

        # Extract the partner infos
        partner_fields = {  # wp_field : odoo_field
            "email": "email",
            "name": "name",
            "street": "street",
            "zipcode": "zip",
            "city": "city",
            "language": "lang",
            "partner_ref": "ref",
        }
        partner_infos = {"company_id": self.env.user.company_id.id}
        for wp_field, odoo_field in list(partner_fields.items()):
            partner_infos[odoo_field] = donnation_infos[wp_field]

        # Find the matching odoo country
        partner_infos["country_id"] = match_obj.match_country(
            donnation_infos["country"], partner_infos["lang"]).id

        # Find matching partner
        partner = match_obj.match_partner_to_infos(partner_infos)

        # Insert the donation details to the database.
        pf_brand = donnation_infos["pf_brand"]
        pf_pm = donnation_infos["pf_pm"]
        if pf_brand != pf_pm:
            payment_mode = "{}_{}".format(pf_brand, pf_pm)
        else:
            payment_mode = pf_brand

        return self.create_from_wordpress(
            partner.id, donnation_infos["orderid"], donnation_infos["amount"],
            donnation_infos["fund"],
            donnation_infos["child_id"], donnation_infos["pf_payid"],
            payment_mode.strip(), donnation_infos["utm_source"],
            donnation_infos["utm_medium"], donnation_infos["utm_campaign"],
            donnation_infos["time"])
Пример #60
0
def feed():
    feed = AtomFeed('HoMaple的个人博客',
                    feed_url=request.url,
                    url=request.url_root,
                    subtitle='I like solitude, yearning for freedom')
    articles = Articles.query.limit(15).all()
    for article in articles:
        feed.add(article.title,
                 escape(safe_markdown(article.content)),
                 content_type='html',
                 author=article.author,
                 url=make_external(url_for('blog.view',
                                           id=article.id)),
                 updated=article.updated
                 if article.updated is not None else article.publish,
                 published=article.publish)
    return feed.get_response()