本文整理汇总了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
示例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
示例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
示例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
示例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')))
示例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')))
示例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')))
示例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')))
示例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')))
示例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"})
示例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))
示例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))
示例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
示例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
示例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