当前位置: 首页>>代码示例>>Python>>正文


Python connection.queries方法代码示例

本文整理汇总了Python中django.db.connection.queries方法的典型用法代码示例。如果您正苦于以下问题:Python connection.queries方法的具体用法?Python connection.queries怎么用?Python connection.queries使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.db.connection的用法示例。


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

示例1: command

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def command(request):
    data = json.loads(request.POST.get('data', '{}'))
    func = getattr(commands, data['command'], None)
    if func:
        if request.user.has_perm(func.permission):
            output, status = func(data)
            output = serializers.serialize('json', output, ensure_ascii=False)
        else:
            output = json.dumps({'error': 'permission denied'})
            status = 403
    else:
        output = json.dumps({'error': 'unrecognized command'})
        status = 400
    resp = HttpResponse(output, content_type='application/json;charset=utf-8')
    if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
        return HttpResponse(
            json.dumps(connection.queries, ensure_ascii=False, indent=1),
            status=status,
            content_type='application/json;charset=utf-8',
        )
    return resp 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:23,代码来源:api.py

示例2: me

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def me(request):
    if request.user.is_anonymous or not request.user.is_active:
        raise PermissionDenied
    output = {'username': request.user.username}
    if request.user.is_superuser:
        output['superuser'] = True
    else:
        permissions = request.user.get_all_permissions()
        if permissions:
            output['permissions'] = list(permissions)
    if request.user.is_staff:
        output['staff'] = True
    resp = HttpResponse(
        json.dumps(output), content_type='application/json;charset=utf-8'
    )
    if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
        return HttpResponse(
            json.dumps(connection.queries, ensure_ascii=False, indent=1),
            status=200,
            content_type='application/json;charset=utf-8',
        )
    return resp 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:24,代码来源:api.py

示例3: __call__

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def __call__(self, request):
        response = self.get_response(request)

        if (len(connection.queries) == 0 or
                request.path_info.startswith('/favicon.ico') or
                request.path_info.startswith(settings.STATIC_URL) or
                request.path_info.startswith(settings.MEDIA_URL)):
            return response

        indentation = 2
        print(("\n\n%s\033[1;35m[SQL Queries for]\033[1;34m %s\033[0m\n" % (" " * indentation, request.path_info)))
        total_time = 0.0
        for query in connection.queries:
            if query['sql']:
                nice_sql = query['sql'].replace('"', '').replace(',', ', ')
                sql = "\033[1;31m[%s]\033[0m %s" % (query['time'], nice_sql)
                total_time = total_time + float(query['time'])
                print(("%s%s\n" % (" " * indentation, sql)))
        replace_tuple = (" " * indentation, str(total_time), str(len(connection.queries)))
        print(("%s\033[1;32m[TOTAL TIME: %s seconds (%s queries)]\033[0m" % replace_tuple))
        return response 
开发者ID:SubstraFoundation,项目名称:substra-backend,代码行数:23,代码来源:sql_printing_middleware.py

示例4: debugger_queries

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def debugger_queries(func):
    """Basic function to debug queries."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("func: ", func.__name__)
        reset_queries()

        start = time.time()
        start_queries = len(connection.queries)

        result = func(*args, **kwargs)

        end = time.time()
        end_queries = len(connection.queries)

        print("queries:", end_queries - start_queries)
        print("took: %.2fs" % (end - start))
        return result

    return wrapper 
开发者ID:LucasMagnum,项目名称:django-tip-02,代码行数:22,代码来源:decorators.py

示例5: test_get_with_exclude

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_get_with_exclude(self):
        with self.assertNumQueries(1):
            response = self.client.get('/users/?exclude[]=name')
        query = connection.queries[-1]['sql']
        self.assertFalse('name' in query, query)
        self.assertFalse('*' in query, query)

        self.assertEquals(200, response.status_code)
        self.assertEquals({
            'users': [{
                'id': 1,
                'location': 1
            }, {
                'id': 2,
                'location': 1
            }, {
                'id': 3,
                'location': 2
            }, {
                'id': 4,
                'location': 3
            }]
        }, json.loads(response.content.decode('utf-8'))) 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:25,代码来源:test_api.py

示例6: test_get_with_nested_has_many

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_get_with_nested_has_many(self):
        with self.assertNumQueries(2):
            # 2 queries: 1 for User, 1 for Group
            response = self.client.get('/users/?include[]=groups.')
        self.assertEquals(200, response.status_code)
        self.assertEquals(
            {'groups': [{'id': 1, 'name': '0'}, {'id': 2, 'name': '1'}],
             'users': [{
                 'groups': [1, 2], 'id': 1, 'location': 1, 'name': '0'
             }, {
                 'groups': [1, 2], 'id': 2, 'location': 1, 'name': '1'
             }, {
                 'groups': [1, 2], 'id': 3, 'location': 2, 'name': '2'
             }, {
                 'groups': [1, 2], 'id': 4, 'location': 3, 'name': '3'
             }]},
            json.loads(response.content.decode('utf-8'))) 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:19,代码来源:test_api.py

示例7: test_get_with_nested_include

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_get_with_nested_include(self):
        with self.assertNumQueries(3):
            # 3 queries: 1 for User, 1 for Group, 1 for Permissions
            response = self.client.get('/users/?include[]=groups.permissions')
        self.assertEquals(200, response.status_code)
        self.assertEquals(
            {'groups': [{'id': 1, 'name': '0', 'permissions': [1]},
                        {'id': 2, 'name': '1', 'permissions': [2]}],
             'users': [{
                 'groups': [1, 2], 'id': 1, 'location': 1, 'name': '0'
             }, {
                 'groups': [1, 2], 'id': 2, 'location': 1, 'name': '1'
             }, {
                 'groups': [1, 2], 'id': 3, 'location': 2, 'name': '2'
             }, {
                 'groups': [1, 2], 'id': 4, 'location': 3, 'name': '3'
             }
            ]},
            json.loads(response.content.decode('utf-8'))) 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:21,代码来源:test_api.py

示例8: test_get_with_nested_exclude

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_get_with_nested_exclude(self):
        with self.assertNumQueries(2):
            # 2 queries: 1 for User, 1 for Group
            response = self.client.get('/users/?exclude[]=groups.name')
        self.assertEquals(200, response.status_code)
        self.assertEquals(
            {'groups': [{'id': 1}, {'id': 2}],
             'users': [{
                 'groups': [1, 2], 'id': 1, 'location': 1, 'name': '0'
             }, {
                 'groups': [1, 2], 'id': 2, 'location': 1, 'name': '1'
             }, {
                 'groups': [1, 2], 'id': 3, 'location': 2, 'name': '2'
             }, {
                 'groups': [1, 2], 'id': 4, 'location': 3, 'name': '3'
             }]},
            json.loads(response.content.decode('utf-8'))) 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:19,代码来源:test_api.py

示例9: test_get_with_filter_and_include_relationship

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_get_with_filter_and_include_relationship(self):
        url = '/users/?include[]=groups.&filter{groups|name}=1'
        with self.assertNumQueries(2):
            # 2 queries: 1 for User, 1 for Group
            response = self.client.get(url)
        self.assertEquals(200, response.status_code)
        self.assertEquals(
            {
                'groups': [{'id': 2, 'name': '1'}],
                'users': [
                    {'groups': [2], 'id': 1, 'location': 1, 'name': '0'},
                    {'groups': [2], 'id': 2, 'location': 1, 'name': '1'},
                    {'groups': [2], 'id': 3, 'location': 2, 'name': '2'},
                    {'groups': [2], 'id': 4, 'location': 3, 'name': '3'}
                ]
            },
            json.loads(response.content.decode('utf-8'))) 
开发者ID:AltSchool,项目名称:dynamic-rest,代码行数:19,代码来源:test_api.py

示例10: test_traverse_GFK

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_traverse_GFK(self):
        """
        A 'content_object' can be traversed with prefetch_related() and
        get to related objects on the other side (assuming it is suitably
        filtered)
        """
        TaggedItem.objects.create(tag="awesome", content_object=self.book1)
        TaggedItem.objects.create(tag="awesome", content_object=self.book2)
        TaggedItem.objects.create(tag="awesome", content_object=self.book3)
        TaggedItem.objects.create(tag="awesome", content_object=self.reader1)
        TaggedItem.objects.create(tag="awesome", content_object=self.reader2)

        ct = ContentType.objects.get_for_model(Book)

        # We get 3 queries - 1 for main query, 1 for content_objects since they
        # all use the same table, and 1 for the 'read_by' relation.
        with self.assertNumQueries(3):
            # If we limit to books, we know that they will have 'read_by'
            # attributes, so the following makes sense:
            qs = TaggedItem.objects.filter(content_type=ct, tag='awesome').prefetch_related('content_object__read_by')
            readers_of_awesome_books = {r.name for tag in qs
                                        for r in tag.content_object.read_by.all()}
            self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"}) 
开发者ID:nesdis,项目名称:djongo,代码行数:25,代码来源:tests.py

示例11: test_simple_tree_cache

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_simple_tree_cache(self):
        queries = connection.queries
        cache_holder = NodeCacheHolder()
        node = symmetric_tree()
        not_cached_children = node.get_children().all()
        cached_children = cache_holder.get_children(node)
        self.assertTrue(isinstance(cache_holder._node_cache, NodeCache))
        for i, child in enumerate(not_cached_children):
            self.assertEqual(child.id, cached_children[i].id)
        max_num_queries = len(queries)
        self.assertEqual(max_num_queries, len(queries))
        content_object = node.content_object
        self.assertEqual(max_num_queries, len(queries))
        content_object = cached_children[0].content_object
        self.assertEqual(max_num_queries, len(queries))
        content_object = cached_children[1].content_object
        self.assertEqual(max_num_queries, len(queries)) 
开发者ID:dgk,项目名称:django-business-logic,代码行数:19,代码来源:test_node.py

示例12: test_medium_tree_cache

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_medium_tree_cache(self):
        queries = connection.queries
        cache_holder = NodeCacheHolder()
        node = symmetric_tree(count=4)
        lft_mul_node, rgh_mul_node = node.get_children().all()
        lft_lft_child, rgh_lft_child = lft_mul_node.get_children().all()
        lft_rgh_child, rgh_rgh_child = rgh_mul_node.get_children().all()
        cached_lft_mul_node, cached_rgh_mul_node = cache_holder.get_children(node)

        max_num_queries = len(queries)
        cached_lft_lft_child, cached_rgh_lft_child = cache_holder.get_children(cached_lft_mul_node)
        cached_lft_rgh_child, cached_rgh_rgh_child = cache_holder.get_children(cached_rgh_mul_node)
        self.assertEqual(max_num_queries, len(queries))
        cached_lft_rgh_child, cached_rgh_rgh_child = cache_holder.get_children(rgh_mul_node)
        content_object = cached_rgh_mul_node.content_object
        content_object = cached_lft_rgh_child.content_object
        content_object = cached_rgh_rgh_child.content_object
        self.assertEqual(max_num_queries, len(queries)) 
开发者ID:dgk,项目名称:django-business-logic,代码行数:20,代码来源:test_node.py

示例13: tracker_response

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def tracker_response(
    request, template='tracker/index.html', qdict=None, status=200, delegate=None
):
    qdict = tracker_context(request, qdict)
    try:
        starttime = time.time()
        if delegate:
            resp = delegate(request, template, context=qdict, status=status)
        else:
            resp = render(request, template, context=qdict, status=status)
        render_time = time.time() - starttime
        if 'queries' in request.GET and request.user.has_perm('tracker.view_queries'):
            resp = HttpResponse(
                json.dumps(connection.queries, ensure_ascii=False, indent=1),
                content_type='application/json;charset=utf-8',
            )
        cache_control = {}
        if request.user.is_anonymous:
            cache_control['public'] = True
        else:
            resp['X-Render-Time'] = render_time
            cache_control['private'] = True
            cache_control['max-age'] = 0
        patch_cache_control(resp, **cache_control)
        return resp
    except Exception as e:
        if request.user.is_staff and not settings.DEBUG:
            return HttpResponse(
                str(type(e)) + '\n\n' + str(e), content_type='text/plain', status=500
            )
        raise 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:33,代码来源:common.py

示例14: process_response

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def process_response(self, request, response):
        # see if things took too long, and log if they did
        if hasattr(request, 'monitoring_starttime'):
            duration = time.time() - request.monitoring_starttime
            if duration > getattr(settings, 'SLOW_THRESHOLD', 5):
                if not (request.path.startswith('/login/?next=')): # ignore requests we can't do anything about
                    logger.info('%0.1fs to return %s %s?%s' % (duration, request.method, request.path, request.META['QUERY_STRING']))
                    for q in connection.queries:
                        logger.debug('%s\t%s' % (q['sql'], q['time']))

        return response 
开发者ID:sfu-fas,项目名称:coursys,代码行数:13,代码来源:middleware.py

示例15: test_query_optimization

# 需要导入模块: from django.db import connection [as 别名]
# 或者: from django.db.connection import queries [as 别名]
def test_query_optimization(self):
        url = reverse("pet-list")
        url = url + "?expand=owner&fields=name,owner"

        response = self.client.get(url, format="json")
        self.assertEqual(response.status_code, HTTPStatus.OK)

        self.assertEqual(len(connection.queries), 1)
        self.assertEqual(
            connection.queries[0]["sql"],
            (
                "SELECT "
                '"testapp_pet"."id", '
                '"testapp_pet"."name", '
                '"testapp_pet"."owner_id", '
                '"testapp_person"."id", '
                '"testapp_person"."name", '
                '"testapp_person"."hobbies", '
                '"testapp_person"."employer_id" '
                'FROM "testapp_pet" '
                'INNER JOIN "testapp_person" ON ("testapp_pet"."owner_id" = "testapp_person"."id")'
            ),
        )

    # todo: test many to one
    # todo: test many to many
    # todo: test view options for SelectFieldsFilterBackend 
开发者ID:rsinger86,项目名称:drf-flex-fields,代码行数:29,代码来源:test_views.py


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