• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python compat.bytes_函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyramid_debugtoolbar.compat.bytes_函数的典型用法代码示例。如果您正苦于以下问题:Python bytes_函数的具体用法?Python bytes_怎么用?Python bytes_使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了bytes_函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: process_response

    def process_response(self, response):
        # If the body is HTML, then we add the toolbar to the response.
        request = self.request

        if isinstance(response, WSGIHTTPException):
            # the body of a WSGIHTTPException needs to be "prepared"
            response.prepare(request.environ)

        for panel in self.panels:
            panel.process_response(response)

        if response.content_type in self.html_types:
            static_path = request.static_url(STATIC_PATH)
            root_path = request.route_url(ROOT_ROUTE_NAME)
            button_style = get_setting(request.registry.settings,
                    'button_style', '')
            vars = {'panels': self.panels, 'static_path': static_path,
                    'root_path': root_path, 'button_style': button_style}
            toolbar_html = render(
                    'pyramid_debugtoolbar:templates/toolbar.dbtmako',
                    vars, request=request)
            response_html = response.body
            toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
            body = replace_insensitive(
                response_html, bytes_('</body>'),
                toolbar_html + bytes_('</body>')
                )
            response.app_iter = [body]
            response.content_length = len(body)
开发者ID:clintron,项目名称:pyramid_debugtoolbar,代码行数:29,代码来源:toolbar.py


示例2: process_response

    def process_response(self, response):
        data = []
        for query in self.queries:
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass # object not JSON serializable
            except UnicodeDecodeError:
                pass # parameters contain non-utf8 (probably binary) data

            need = self.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        self.data = {
            'queries':data,
            'text':text,
            }
开发者ID:kevinruizmayoral,项目名称:zodiac2,代码行数:33,代码来源:sqla.py


示例3: sql_select

    def sql_select(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']
        engine_id = self.request.params['engine_id']

        # Validate hash
        hash = hashlib.sha1(
            bytes_(self.request.exc_history.token + stmt + params)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')
 
        # Make sure it is a select statement
        if not stmt.lower().strip().startswith('select'):
            raise HTTPBadRequest('Not a SELECT SQL statement')

        if not engine_id:
            raise HTTPBadRequest('No valid database engine')

        engine = getattr(self.request.registry, 'pdtb_sqla_engines')\
                      [int(engine_id)]()
        params = json.loads(params)
        result = engine.execute(stmt, params)

        return {
            'result': result.fetchall(),
            'headers': result.keys(),
            'sql': format_sql(stmt),
            'duration': float(self.request.params['duration']),
        }
开发者ID:Cito,项目名称:pyramid_debugtoolbar,代码行数:29,代码来源:views.py


示例4: test_execute

 def test_execute(self):
     request = self._makeRequest()
     request.params['cmd'] = 'doit'
     view = self._makeOne(request)
     response = view.execute()
     self.assertEqual(response.body, bytes_('evaled'))
     self.assertEqual(response.content_type, 'text/html')
开发者ID:Pylons,项目名称:pyramid_debugtoolbar,代码行数:7,代码来源:test_views.py


示例5: test_source

 def test_source(self):
     request = self._makeRequest()
     request.params['frm'] = '0'
     view = self._makeOne(request)
     response = view.source()
     self.assertEqual(response.body, bytes_('source'))
     self.assertEqual(response.content_type, 'text/html')
开发者ID:Bedrock02,项目名称:Vigenere,代码行数:7,代码来源:test_views.py


示例6: sql_select

    def sql_select(self):
        stmt = self.request.params["sql"]
        params = self.request.params["params"]
        engine_id = self.request.params["engine_id"]

        # Validate hash
        hash = hashlib.sha1(bytes_(self.request.exc_history.token + stmt + params)).hexdigest()
        if hash != self.request.params["hash"]:
            raise HTTPBadRequest("Bad token in request")

        # Make sure it is a select statement
        if not stmt.lower().strip().startswith("select"):
            raise HTTPBadRequest("Not a SELECT SQL statement")

        if not engine_id:
            raise HTTPBadRequest("No valid database engine")

        engine = getattr(self.request.registry, "pdtb_sqla_engines")[int(engine_id)]()
        params = json.loads(params)
        result = engine.execute(stmt, params)

        return {
            "result": result.fetchall(),
            "headers": result.keys(),
            "sql": format_sql(stmt),
            "duration": float(self.request.params["duration"]),
        }
开发者ID:sundisee,项目名称:appsync-vendor,代码行数:27,代码来源:views.py


示例7: test_execute

 def test_execute(self):
     request = self._makeRequest()
     request.params["frm"] = "0"
     request.params["cmd"] = "doit"
     view = self._makeOne(request)
     response = view.execute()
     self.assertEqual(response.body, bytes_("evaled"))
     self.assertEqual(response.content_type, "text/html")
开发者ID:sundisee,项目名称:appsync-vendor,代码行数:8,代码来源:test_views.py


示例8: inject

 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings,
             'button_style', '')
     css_path = request.static_url(STATIC_PATH + 'css/toolbar_button.css')
     toolbar_html = toolbar_html_template % {
         'button_style': button_style,
         'css_path': css_path,
         'toolbar_url': toolbar_url}
     toolbar_html = toolbar_html.encode(response.charset or 'utf-8')
     response.body = replace_insensitive(
         response_html, bytes_('</body>'),
         toolbar_html + bytes_('</body>')
         )
开发者ID:Bedrock02,项目名称:Vigenere,代码行数:19,代码来源:toolbar.py


示例9: validate

    def validate(self):
        stmt = self.request.params["sql"]
        params = self.request.params["params"]

        # Validate hash
        need = self.request.exc_history.token + stmt + url_quote(params)

        hash = hashlib.sha1(bytes_(need)).hexdigest()
        if hash != self.request.params["hash"]:
            raise HTTPBadRequest("Bad token in request")
        return stmt, params
开发者ID:muellert,项目名称:pyramid_debugtoolbar,代码行数:11,代码来源:views.py


示例10: validate

    def validate(self):
        stmt = self.request.params['sql']
        params = self.request.params['params']

        # Validate hash
        need = self.token + stmt + url_quote(params)

        hash = hashlib.sha1(bytes_(need)).hexdigest()
        if hash != self.request.params['hash']:
            raise HTTPBadRequest('Bad token in request')
        return stmt, params
开发者ID:kevinruizmayoral,项目名称:zodiac2,代码行数:11,代码来源:views.py


示例11: test_inject_html

 def test_inject_html(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
     self.assertEqual(response.content_length, len(response.app_iter[0]))
开发者ID:kashifpk,项目名称:pyramid_debugtoolbar,代码行数:13,代码来源:test_toolbar.py


示例12: test_process_response_html

 def test_process_response_html(self):
     from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static',
                                 STATIC_PATH)
     self.config.add_route(ROOT_ROUTE_NAME, '/_debugtoolbar')
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
     self.assertTrue(bytes_('div id="pDebug"') in response.app_iter[0])
开发者ID:cguardia,项目名称:pyramid_debugtoolbar,代码行数:14,代码来源:test_toolbar.py


示例13: test_passing_of_button_style

 def test_passing_of_button_style(self):
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.add_static_view('_debugtoolbar/static', STATIC_PATH)
     self.config.add_route('debugtoolbar', '/_debugtoolbar/*subpath')
     self.config.registry.settings['debugtoolbar.button_style'] = \
         'top:120px;zoom:50%'
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.pdtb_id = 'abc'
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel], [DummyPanel], [])
     toolbar.inject(request, response)
     self.assertTrue(bytes_('top:120px;zoom:50%') in response.app_iter[0])
开发者ID:kashifpk,项目名称:pyramid_debugtoolbar,代码行数:14,代码来源:test_toolbar.py


示例14: inject

 def inject(self, request, response):
     """
     Inject the debug toolbar iframe into an HTML response.
     """
     # called in host app
     response_html = response.body
     toolbar_url = debug_toolbar_url(request, request.id)
     button_style = get_setting(request.registry.settings, "button_style", "")
     css_path = request.static_url(STATIC_PATH + "css/toolbar.css")
     toolbar_html = toolbar_html_template % {
         "button_style": button_style,
         "css_path": css_path,
         "toolbar_url": toolbar_url,
     }
     toolbar_html = toolbar_html.encode(response.charset or "utf-8")
     response.body = replace_insensitive(response_html, bytes_("</body>"), toolbar_html + bytes_("</body>"))
开发者ID:nbasu02,项目名称:pyramid_debugtoolbar,代码行数:16,代码来源:toolbar.py


示例15: test_passing_of_button_style

 def test_passing_of_button_style(self):
     from pyramid_debugtoolbar.utils import ROOT_ROUTE_NAME
     from pyramid_debugtoolbar.utils import STATIC_PATH
     self.config.include('pyramid_jinja2')
     self.config.add_static_view('_debugtoolbar/static',
                                 STATIC_PATH)
     self.config.add_route(ROOT_ROUTE_NAME, '/_debugtoolbar')
     self.config.registry.settings['debugtoolbar.button_style'] = \
         'top:120px;zoom:50%'
     response = Response('<body></body>')
     response.content_type = 'text/html'
     request = Request.blank('/')
     request.registry = self.config.registry
     toolbar = self._makeOne(request, [DummyPanel])
     toolbar.process_response(response)
     self.assertTrue(response.processed)
     self.failUnless(bytes_('top:120px;zoom:50%') in response.app_iter[0])
开发者ID:mozilla,项目名称:appsync-vendor,代码行数:17,代码来源:test_toolbar.py


示例16: content

    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            stmt = query['statement']

            is_select = stmt.strip().lower().startswith('select')
            params = ''
            try:
                params = url_quote(json.dumps(query['parameters']))
            except TypeError:
                pass # object not JSON serializable
            except UnicodeDecodeError:
                pass # parameters contain non-utf8 (probably binary) data

            need = self.request.exc_history.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(stmt),
                'raw_sql': stmt,
                'hash': hash,
                'parameters': query['parameters'],
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries':data,
            'text':text,
            }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.dbtmako',
            vars, self.request)
开发者ID:ianjosephwilson,项目名称:pyramid_debugtoolbar,代码行数:44,代码来源:sqla.py


示例17: content

    def content(self):
        if not self.queries:
            return "No queries in executed in request."

        data = []
        for query in self.queries:
            stmt = query["statement"]

            is_select = stmt.strip().lower().startswith("select")
            params = ""
            try:
                params = url_quote(json.dumps(query["parameters"]))
            except TypeError:
                pass  # object not JSON serializable
            except UnicodeDecodeError:
                pass  # parameters contain non-utf8 (probably binary) data

            need = self.request.exc_history.token + stmt + params
            hash = hashlib.sha1(bytes_(need)).hexdigest()

            data.append(
                {
                    "engine_id": query["engine_id"],
                    "duration": query["duration"],
                    "sql": format_sql(stmt),
                    "raw_sql": stmt,
                    "hash": hash,
                    "parameters": query["parameters"],
                    "params": params,
                    "is_select": is_select,
                    "context": query["context"],
                }
            )

        vars = {
            "static_path": self.request.static_url(STATIC_PATH),
            "root_path": self.request.route_url(ROOT_ROUTE_NAME),
            "queries": data,
            "text": text,
        }

        delattr(self.request, "pdtb_sqla_queries")

        return self.render("pyramid_debugtoolbar.panels:templates/sqlalchemy.dbtmako", vars, self.request)
开发者ID:hanula,项目名称:pyramid_debugtoolbar,代码行数:44,代码来源:sqla.py


示例18: content

    def content(self):
        if not self.queries:
            return 'No queries in executed in request.'

        data = []
        for query in self.queries:
            is_select = query['statement'].strip().lower().startswith('select')
            params = ''
            try:
                params = json.dumps(query['parameters'])
            except TypeError:
                pass # object not JSON serializable

            hash = hashlib.sha1(
                bytes_(self.request.exc_history.token +
                       query['statement'] + params)).hexdigest()

            data.append({
                'engine_id': query['engine_id'],
                'duration': query['duration'],
                'sql': format_sql(query['statement']),
                'raw_sql': query['statement'],
                'hash': hash,
                'params': params,
                'is_select': is_select,
                'context': query['context'],
            })

        vars = {
            'static_path': self.request.static_url(STATIC_PATH),
            'root_path': self.request.route_url(ROOT_ROUTE_NAME),
            'queries':data,
            }

        delattr(self.request, 'pdtb_sqla_queries')

        return self.render(
            'pyramid_debugtoolbar.panels:templates/sqlalchemy.jinja2',
            vars, self.request)
开发者ID:mozilla,项目名称:appsync-vendor,代码行数:39,代码来源:sqla.py


示例19: hexlify

def hexlify(value):
    """Hexlify int, str then returns native str type."""
    # If integer
    str_ = str(value)
    hexified = text_(binascii.hexlify(bytes_(str_)))
    return hexified
开发者ID:chiho924,项目名称:session05,代码行数:6,代码来源:utils.py


示例20: test_debug_repr

    def test_debug_repr(self):
        assert debug_repr([]) == '[]'
        assert debug_repr([1, 2]) == \
            '[<span class="number">1</span>, <span class="number">2</span>]'
        assert debug_repr([1, 'test']) == \
            '[<span class="number">1</span>, <span class="string">\'test\'</span>]'
        assert debug_repr([None]) == \
            '[<span class="object">None</span>]'
        assert debug_repr(list(range(20))) == (
            '[<span class="number">0</span>, <span class="number">1</span>, '
            '<span class="number">2</span>, <span class="number">3</span>, '
            '<span class="number">4</span>, <span class="number">5</span>, '
            '<span class="number">6</span>, <span class="number">7</span>, '
            '<span class="number">8</span>, <span class="number">9</span>, '
            '<span class="number">10</span>, <span class="number">11</span>, '
            '<span class="number">12</span>, <span class="number">13</span>, '
            '<span class="number">14</span>, <span class="number">15</span>, '
            '<span class="number">16</span>, <span class="number">17</span>, '
            '<span class="number">18</span>, <span class="number">19</span>]'
        )
        assert debug_repr({}) == '{}'
        assert debug_repr({'foo': 42}) == \
            '{<span class="pair"><span class="key"><span class="string">\'foo\''\
            '</span></span>: <span class="value"><span class="number">42' \
            '</span></span></span>}'
        result = debug_repr((1, bytes_('zwei'), text_('drei')))
        if PY3: # pragma: no cover
            expected = (
                '(<span class="number">1</span>, <span class="string">b\''
                'zwei\'</span>, <span class="string">\'drei\'</span>)')
        else:
            expected = (
                '(<span class="number">1</span>, <span class="string">\''
                'zwei\'</span>, <span class="string">u\'drei\'</span>)')
        assert result == expected

        class Foo(object):
            def __repr__(self):
                return '<Foo 42>'
        assert debug_repr(Foo()) == '<span class="object">&lt;Foo 42&gt;</span>'

        class MyList(list):
            pass
        tmp = debug_repr(MyList([1, 2]))
        assert tmp == \
            '<span class="module">pyramid_debugtoolbar.tests.test_debug.</span>MyList([' \
            '<span class="number">1</span>, <span class="number">2</span>])'

        result = debug_repr(re.compile(r'foo\d'))
        assert result == \
            're.compile(<span class="string regex">r\'foo\\d\'</span>)'
        result = debug_repr(re.compile(text_(r'foo\d')))
        if PY3: # pragma: no cover
            assert result == \
                   're.compile(<span class="string regex">r\'foo\\d\'</span>)'
        else:
            assert result == \
                   're.compile(<span class="string regex">ur\'foo\\d\'</span>)'


        assert debug_repr(frozenset('x')) == \
            'frozenset([<span class="string">\'x\'</span>])'
        assert debug_repr(set('x')) == \
            'set([<span class="string">\'x\'</span>])'

        a = [1]
        a.append(a)
        assert debug_repr(a) == '[<span class="number">1</span>, [...]]'

        class Foo(object):
            def __repr__(self):
                1/0

        result = debug_repr(Foo())

        assert 'division' in result
开发者ID:ianmarcinkowski,项目名称:pyramid_debugtoolbar,代码行数:76,代码来源:test_debug.py



注:本文中的pyramid_debugtoolbar.compat.bytes_函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python compat.text_函数代码示例发布时间:2022-05-27
下一篇:
Python pyramid_beaker.set_cache_regions_from_settings函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap