python类escape()的实例源码

ui_form.py 文件源码 项目:easydo-ui 作者: easydo-cn 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def html(self):
        value = cgi.escape(self.value, True)
        if self.readonly: return value

        self.klass.extend(['text-line', 'controls'])
        self.attr['type'] = self._type
        self.attr['placeholder'] = self.placeholder
        self.attr['value'] = value

        attr = self._get_attr()
        data = self._get_data()

        result = '<input style="100%%" %s %s />' % (attr, data)
        if self._icon:
            return '<div class="input-prepend"><span class="add-on"><i class="fa fa-%s"></i></span> %s </div>' % (self._icon, result)
        else:
            return result
ecdsa.py 文件源码 项目:abe-bootstrap 作者: TryCoin-Team 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def handle_qr(abe,page):
        address = wsgiref.util.shift_path_info(page['env'])
        if address in (None, '') or page['env']['PATH_INFO'] != '':
            raise PageNotFound()

        body = page['body']
        page['title'] = 'Address ' + escape(address)
        version, binaddr = decode_check_address(address)
        if binaddr is None:
            body += ['<p>Not a valid address.</p>']
            return

        ret = """<html><body>
               <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
               <script type="text/javascript" src="http://ecdsa.org/jquery.qrcode.min.js"></script>
               <div id="qrcode"></div>
               <script>jQuery('#qrcode').qrcode("bitcoin:%s");</script>  
               </body></html>"""%address

        abe.do_raw(page, ret)
        page['content_type']='text/html'
abe.py 文件源码 项目:abe-bootstrap 作者: TryCoin-Team 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def show_search_results(abe, page, found):
        if not found:
            page['body'] = [
                '<p>No results found.</p>\n', abe.search_form(page)]
            return

        if len(found) == 1:
            # Undo shift_path_info.
            sn = posixpath.dirname(page['env']['SCRIPT_NAME'])
            if sn == '/': sn = ''
            page['env']['SCRIPT_NAME'] = sn
            page['env']['PATH_INFO'] = '/' + page['dotdot'] + found[0]['uri']
            del(page['env']['QUERY_STRING'])
            raise Redirect()

        body = page['body']
        body += ['<h3>Search Results</h3>\n<ul>\n']
        for result in found:
            body += [
                '<li><a href="', page['dotdot'], escape(result['uri']), '">',
                escape(result['name']), '</a></li>\n']
        body += ['</ul>\n']
abe.py 文件源码 项目:abe-bootstrap 作者: TryCoin-Team 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def show_search_results(abe, page, found):
        if not found:
            page['body'] = [
                '<p>No results found.</p>\n', abe.search_form(page)]
            return

        if len(found) == 1:
            # Undo shift_path_info.
            sn = posixpath.dirname(page['env']['SCRIPT_NAME'])
            if sn == '/': sn = ''
            page['env']['SCRIPT_NAME'] = sn
            page['env']['PATH_INFO'] = '/' + page['dotdot'] + found[0]['uri']
            del(page['env']['QUERY_STRING'])
            raise Redirect()

        body = page['body']
        body += ['<h3>Search Results</h3>\n<ul>\n']
        for result in found:
            body += [
                '<li><a href="', page['dotdot'], escape(result['uri']), '">',
                escape(result['name']), '</a></li>\n']
        body += ['</ul>\n']
abe.py 文件源码 项目:abe-bootstrap 作者: TryCoin-Team 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def handle_b(abe, page):
        if page.get('chain') is not None:
            chain = page['chain']
            height = wsgiref.util.shift_path_info(page['env'])
            try:
                height = int(height)
            except Exception:
                raise PageNotFound()
            if height < 0 or page['env']['PATH_INFO'] != '':
                raise PageNotFound()

            cmd = wsgiref.util.shift_path_info(page['env'])
            if cmd is not None:
                raise PageNotFound()  # XXX want to support /a/...

            page['title'] = [escape(chain.name), ' ', height]
            abe._show_block(page, page['dotdot'] + 'block/', chain, block_number=height)
            return

        abe.show_search_results(
            page,
            abe.search_hash_prefix(
                shortlink_block(wsgiref.util.shift_path_info(page['env'])),
                ('block',)))
scgi_fork.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
ajp_fork.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
fcgi_single.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
fcgi_fork.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
scgi.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
ajp.py 文件源码 项目:Flask_Blog 作者: sugarguo 项目源码 文件源码 阅读 67 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
renderer.py 文件源码 项目:PhaserSublimePackage 作者: PhaserEditor2D 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_description_message(useHTML, type, doc=None, url=None):
  """Get the message to display for Describe commands.

  If useHTML is True, the message will be formatted with HTML tags.
  """

  message = type
  if useHTML:
    message = "<strong>{type}</strong>".format(type=message)
  if doc is not None:
    if useHTML:
      message += " — " + cgi.escape(doc)
    else:
      message += "\n\n" + format_doc(doc)
  if url is not None:
    message += " "
    if useHTML:
      message += '<a href="{url}">[docs]</a>'.format(url=url)
    else:
      message += "\n\n" + url
  return message
tree.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def addHTMLListings(document, dir):
    """
    Insert HTML source listings into the given document from files in the given
    directory based on C{html-listing} nodes.

    Any node in C{document} with a C{class} attribute set to C{html-listing}
    will have source lines taken from the file named in that node's C{href}
    attribute (searched for in C{dir}) inserted in place of that node.

    @type document: A DOM Node or Document
    @param document: The document within which to make listing replacements.

    @type dir: C{str}
    @param dir: The directory in which to find source files containing the
    referenced HTML listings.

    @return: C{None}
    """
    for node in domhelpers.findElementsWithAttribute(document, "class",
                                                     "html-listing"):
        filename = node.getAttribute("href")
        val = ('<pre class="htmlsource">\n%s</pre>' %
               cgi.escape(open(os.path.join(dir, filename)).read()))
        _replaceWithListing(node, val, filename, "html-listing")
tree.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def addPlainListings(document, dir):
    """
    Insert text listings into the given document from files in the given
    directory based on C{listing} nodes.

    Any node in C{document} with a C{class} attribute set to C{listing} will
    have source lines taken from the file named in that node's C{href}
    attribute (searched for in C{dir}) inserted in place of that node.

    @type document: A DOM Node or Document
    @param document: The document within which to make listing replacements.

    @type dir: C{str}
    @param dir: The directory in which to find source files containing the
    referenced text listings.

    @return: C{None}
    """
    for node in domhelpers.findElementsWithAttribute(document, "class",
                                                     "listing"):
        filename = node.getAttribute("href")
        val = ('<pre>\n%s</pre>' %
               cgi.escape(open(os.path.join(dir, filename)).read()))
        _replaceWithListing(node, val, filename, "listing")
SidebarPlugin.py 文件源码 项目:zeronet-debian 作者: bashrc 项目源码 文件源码 阅读 97 收藏 0 点赞 0 评论 0
def sidebarRenderOwnSettings(self, body, site):
        title = cgi.escape(site.content_manager.contents["content.json"]["title"], True)
        description = cgi.escape(site.content_manager.contents["content.json"]["description"], True)
        privatekey = cgi.escape(self.user.getSiteData(site.address, create=False).get("privatekey", ""))

        body.append(u"""
            <li>
             <label for='settings-title'>Site title</label>
             <input type='text' class='text' value="{title}" id='settings-title'/>
            </li>

            <li>
             <label for='settings-description'>Site description</label>
             <input type='text' class='text' value="{description}" id='settings-description'/>
            </li>

            <li style='display: none'>
             <label>Private key</label>
             <input type='text' class='text long' value="{privatekey}" placeholder='[Ask on signing]'/>
            </li>

            <li>
             <a href='#Save' class='button' id='button-settings'>Save site settings</a>
            </li>
        """.format(**locals()))
SidebarPlugin.py 文件源码 项目:zeronet-debian 作者: bashrc 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def sidebarRenderContents(self, body, site):
        body.append("""
            <li>
             <label>Content publishing</label>
             <select id='select-contents'>
        """)

        for inner_path in sorted(site.content_manager.contents.keys()):
            body.append(u"<option>%s</option>" % cgi.escape(inner_path, True))

        body.append("""
             </select>
             <span class='select-down'>&rsaquo;</span>
             <a href='#Sign' class='button' id='button-sign'>Sign</a>
             <a href='#Publish' class='button' id='button-publish'>Publish</a>
            </li>
        """)
report.py 文件源码 项目:caterpillar 作者: chromium 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def process_usage(apis, usage):
  """Populates usage element of an API dictionary with the usages of that API.

  Args:
    apis: Dictionary mapping Chrome Apps API name to polyfill manifest
      dictionaries. This will be modified.
    usage: Usage dictionary mapping API names to
      (filepath, linenum, context, context_linenum) tuples.
  """

  for api_name, api_info in apis.iteritems():
    api_info['usage'] = []
    for uses in usage[api_name].values():
      for filepath, line_num, context, start in uses:
        context = cgi.escape(context)
        context = highlight_relevant_line(context, line_num - start, apis)
        api_info['usage'].append((filepath, line_num, context, start))

    # Sort first by file, then by line number.
    api_info['usage'].sort()
fcgi.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_app(environ, start_response):
        """Probably not the most efficient example."""
        import cgi
        start_response('200 OK', [('Content-Type', 'text/html')])
        yield '<html><head><title>Hello World!</title></head>\n' \
              '<body>\n' \
              '<p>Hello World!</p>\n' \
              '<table border="1">'
        names = environ.keys()
        names.sort()
        for name in names:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                name, cgi.escape(`environ[name]`))

        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
                                keep_blank_values=1)
        if form.list:
            yield '<tr><th colspan="2">Form data</th></tr>'

        for field in form.list:
            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
                field.name, field.value)

        yield '</table>\n' \
              '</body></html>\n'
markmin2html.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def local_html_escape(data, quote=False):
    """
    Works with bytes.
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true (the default), the quotation mark
    characters, both double quote (") and single quote (') characters are also
    translated.
    """
    if PY2:
        import cgi
        data = cgi.escape(data, quote)
        return data.replace("'", "&#x27;") if quote else data
    else:
        import html
        if isinstance(data, str):
            return html.escape(data, quote=quote)
        data = data.replace(b"&", b"&amp;")  # Must be done first!                                                                                           
        data = data.replace(b"<", b"&lt;")
        data = data.replace(b">", b"&gt;")
        if quote:
            data = data.replace(b'"', b"&quot;")
            data = data.replace(b'\'', b"&#x27;")
        return data
utils.py 文件源码 项目:touch-pay-client 作者: HackPucBemobi 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def local_html_escape(data, quote=False):
    """
    Works with bytes.
    Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true (the default), the quotation mark
    characters, both double quote (") and single quote (') characters are also
    translated.
    """
    if PY2:
        import cgi
        data = cgi.escape(data, quote)
        return data.replace("'", "&#x27;") if quote else data
    else:
        import html
        if isinstance(data, str):
            return html.escape(data, quote=quote)
        data = data.replace(b"&", b"&amp;")  # Must be done first!
        data = data.replace(b"<", b"&lt;")
        data = data.replace(b">", b"&gt;")
        if quote:
            data = data.replace(b'"', b"&quot;")
            data = data.replace(b'\'', b"&#x27;")
        return data
upnpCommand.py 文件源码 项目:pyfeld 作者: scjurgen 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def set_transport_uri(self, data):
        print("CurrentURI:\n" + data['CurrentURI'])
        print("CurrentURIMetaData:\n" + data['CurrentURIMetaData'])
        send_data = '<InstanceID>0</InstanceID>'
        add_uri = data['CurrentURI']
        if 'raumfeldname' in data:
            if data['raumfeldname'] == 'Station':
                if 'TrackURI' in data:
                    add_uri = data['TrackURI']

        send_data += "<CurrentURI><![CDATA[" + add_uri + "]]></CurrentURI>"
        send_data += "<CurrentURIMetaData>" + cgi.escape(data['CurrentURIMetaData']) + "</CurrentURIMetaData>"
        # + cgi.escape(data['CurrentURIMetaData']) +
        print(send_data)
        xml_root = self.host_send_transport("SetAVTransportURI", send_data)
        return XmlHelper.xml_extract_dict(xml_root, ['SetAVTransportURI'])
_webapp25.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def handle_exception(self, exception, debug_mode):
    """Called if this handler throws an exception during execution.

    The default behavior is to call self.error(500) and print a stack trace
    if debug_mode is True.

    Args:
      exception: the exception that was thrown
      debug_mode: True if the web application is running in debug mode
    """
    self.error(500)
    logging.exception(exception)
    if debug_mode:
      lines = ''.join(traceback.format_exception(*sys.exc_info()))
      self.response.clear()
      self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True)))
util.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def write_error(sock, status_int, reason, mesg):
    html = textwrap.dedent("""\
    <html>
      <head>
        <title>%(reason)s</title>
      </head>
      <body>
        <h1><p>%(reason)s</p></h1>
        %(mesg)s
      </body>
    </html>
    """) % {"reason": reason, "mesg": cgi.escape(mesg)}

    http = textwrap.dedent("""\
    HTTP/1.1 %s %s\r
    Connection: close\r
    Content-Type: text/html\r
    Content-Length: %d\r
    \r
    %s""") % (str(status_int), reason, len(html), html)
    write_nonblock(sock, http.encode('latin1'))
core.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def html_params(**kwargs):
    """
    Generate HTML parameters from inputted keyword arguments.

    The output value is sorted by the passed keys, to provide consistent output
    each time this function is called with the same parameters.  Because of the
    frequent use of the normally reserved keywords `class` and `for`, suffixing
    these with an underscore will allow them to be used.

    >>> html_params(name='text1', id='f', class_='text') == 'class="text" id="f" name="text1"'
    True
    """
    params = []
    for k,v in sorted(iteritems(kwargs)):
        if k in ('class_', 'class__', 'for_'):
            k = k[:-1]
        if v is True:
            params.append(k)
        else:
            params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
    return ' '.join(params)
_webapp25.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def handle_exception(self, exception, debug_mode):
    """Called if this handler throws an exception during execution.

    The default behavior is to call self.error(500) and print a stack trace
    if debug_mode is True.

    Args:
      exception: the exception that was thrown
      debug_mode: True if the web application is running in debug mode
    """
    self.error(500)
    logging.exception(exception)
    if debug_mode:
      lines = ''.join(traceback.format_exception(*sys.exc_info()))
      self.response.clear()
      self.response.out.write('<pre>%s</pre>' % (cgi.escape(lines, quote=True)))
constituency.py 文件源码 项目:electioncharts 作者: mickeykedia 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_constituency_info(db,constituency_id):
    cursor = db.cursor()
    cursor.execute('''Select c.id, c.name, c.constituency_code, c.state_id, s.name, c.result_status 
        from constituency c inner join state s on s.id = c.state_id 
        where c.id = ''' + constituency_id + ''';''')
    row = cursor.fetchone()
    voting_status=cgi.escape(row[5])

    voting_status=voting_status.title() if (voting_status!="NOT_STARTED") else "Not Started"
    constituency = {"id": row[0], "name": row[1], \
                    "constituency_code": cgi.escape(row[2]), \
                    "state_id": row[3], "state_name": cgi.escape(row[4]),\
                    "voting_status":voting_status}
    result = get_constituency_result_1(db,constituency_id)
    for result_item in result.iterkeys():
        constituency[result_item]=result[result_item]
    return json.dumps(constituency)
constituency.py 文件源码 项目:electioncharts 作者: mickeykedia 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_constituency_result_1(db,constituency_id):
    cursor = db.cursor()
    cursor.execute('''SELECT ca.id, ca.fullname, p.id, p.name, r.time_start, r.votes, p.symbol
      FROM results r, candidate_constituency c_c, candidate ca, constituency co, party p 
      where c_c.constituency_id=co.id and c_c.candidate_id=ca.id 
      and c_c.party_id=p.id and r.candidate_id=ca.id and r.constituency_id=co.id 
      and r.active=1  and c_c.election="2014" and r.constituency_id='''+ constituency_id +''' order 
      by r.votes desc;''')
    output={'total_votes':0}
    results=[]
    for row in cursor.fetchall():
        temp_map={}
        temp_map['candidate_id']=row[0]
        temp_map['candidate_name']=cgi.escape(row[1]).title()
        temp_map['party_id']=row[2]
        temp_map['party_name']=cgi.escape(row[3]).title()
        temp_map['votes']=row[5]
        temp_map['party_symbol']=row[6]
        output['total_votes']=output['total_votes']+row[5]
        results.append(temp_map)
    output['result_list']=results
    return output
constituency.py 文件源码 项目:electioncharts 作者: mickeykedia 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_constituency_result_2009(db,constituency_id):
    cursor = db.cursor()
    cursor.execute('''SELECT ca.id, ca.fullname, p.id, p.name, l.votes
      FROM last_time_results l, candidate ca, constituency co, party p 
      where l.constituency_id=co.id and l.candidate_id=ca.id 
      and l.party_id=p.id and l.candidate_id=ca.id and l.constituency_id=co.id 
      and l.constituency_id='''+ constituency_id +''' order 
      by l.votes desc;''')
    results=[]
    total_votes=0
    for row in cursor.fetchall():
        temp_map={}
        temp_map['candidate_id']=row[0]
        temp_map['candidate_name']=cgi.escape(row[1]).title()
        temp_map['party_id']=row[2]
        temp_map['party_name']=cgi.escape(row[3]).title()
        temp_map['votes']=row[4]
        total_votes=total_votes+row[4]
        results.append(temp_map)
    new_results = []
    for rec in results:
        rec['total_votes']=total_votes
        new_results.append(rec)

    return json.dumps(new_results)
candidate.py 文件源码 项目:electioncharts 作者: mickeykedia 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_candidate_list(db,param):
    cursor = db.cursor()
    cursor.execute('''SELECT ca.id, ca.fullname, co.id, co.name, p.id, p.name 
        from candidate ca, candidate_constituency c_c, constituency co, party p 
        where ca.id=c_c.candidate_id and c_c.constituency_id=co.id and c_c.party_id=p.id ''')
    output=[]
    for row in cursor.fetchall():
        temp={}
        temp['candidate_id']=row[0]
        temp['candidate_name']=cgi.escape(row[1])
        temp['constituency_id']=row[2]
        temp['constituency_name']=cgi.escape(row[3])
        temp['party_id']=row[4]
        temp['party_name']=cgi.escape(row[5])
        output.append(temp)

    return json.dumps(output);
error.py 文件源码 项目:dati-ckan-docker 作者: italia 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def document(self):
        """Render the error document"""
        original_request = request.environ.get('pylons.original_request')
        original_response = request.environ.get('pylons.original_response')
        # When a request (e.g. from a web-bot) is direct, not a redirect
        # from a page. #1176
        if not original_response:
            return 'There is no error.'
        # Bypass error template for API operations.
        if (original_request and
                (original_request.path.startswith('/api') or
                 original_request.path.startswith('/fanstatic'))):
            return original_response.body
        # If the charset has been lost on the middleware stack, use the
        # default one (utf-8)
        if not original_response.charset and original_response.default_charset:
            original_response.charset = original_response.default_charset
        # Otherwise, decorate original response with error template.
        c.content = literal(original_response.unicode_body) or \
            cgi.escape(request.GET.get('message', ''))
        c.prefix = request.environ.get('SCRIPT_NAME', ''),
        c.code = cgi.escape(request.GET.get('code',
                            str(original_response.status_int))),
        return render('error_document_template.html')


问题


面经


文章

微信
公众号

扫码关注公众号