gpt4 book ai didi

python - Django Tastypie Postgres 服务器响应缓慢

转载 作者:行者123 更新时间:2023-11-28 19:15:44 25 4
gpt4 key购买 nike

问题:

  • 服务器对调用的响应(通过 opbeat、DHC chrome 客户端测量)是大约 500 毫秒到 5000 毫秒。 Postgres 查询(总计,每次调用)比相应的响应时间快 20 到 50 倍。为什么这么慢?!?

上下文:

  • 我在 webfaction 上运行一个实时的 tastypie API(共享实例,1 gig ram :( ) 用于我们的移动应用程序。Django 1.8、Python 2.7、0.12.2.dev0 tastypie、PostgreSQL 9.4、CentOS7
  • 数据库有大约 40 个表,~2gigs,6k 用户(可能有 1/3 是“活跃的”),数据库在数据库的单独共享 webfaction 框上。
  • 虽然我们在 api 中确实有一些程序代码,但许多缓慢的调用只是对用户资源的 GET - 最大/最慢的是 ~50kb 的记录,JSON 响应中的 ~350 个对象。此调用的 postgres 时间约为 20-50 毫秒,DHC 上最快的时间在快速专用开发服务器上约为 2 秒——2gig ram,2 个进程——实时约为 4 秒,最慢的时间约为 10-16 秒箱子。
  • 在 Apache/mod_wsgi、HTTPS 上运行(apache 的基准速度很快),没有 gzip。 httpd.conf 设置似乎没问题。

简而言之:

  • 99% 的时间花在 tastypie.resources.wrapper 上——我没有弄乱这段代码。这些调用只是返回资源的调用。
  • 数据库查询速度很快
  • 网络服务器看起来很快。

诊断:

Django 调试工具栏(用于开发专用框上最慢操作的最快调用)

用户 CPU 时间 1926.979 毫秒

系统 CPU 时间 27.074 毫秒

总 CPU 时间 1954.053 毫秒

耗时 1980.884 毫秒

上下文切换 71 次自愿,44 次非自愿

httpd.conf

LoadModule authz_core_module modules/mod_authz_core.so

LoadModule dir_module modules/mod_dir.so

LoadModule env_module modules/mod_env.so

LoadModule log_config_module modules/mod_log_config.so

LoadModule mime_module modules/mod_mime.so

LoadModule rewrite_module modules/mod_rewrite.so

LoadModule setenvif_module modules/mod_setenvif.so

LoadModule wsgi_module modules/mod_wsgi.so

LoadModule unixd_module modules/mod_unixd.so

...

KeepAlive Off

SetEnvIf X-Forwarded-SSL on HTTPS=1

ServerLimit 1

StartServers 1

MaxRequestWorkers 5

MinSpareThreads 1

MaxSpareThreads 3

ThreadsPerChild 5

...

WSGIApplicationGroup %{GLOBAL}

WSGIDaemonProcess djangoapp processes=2 threads=8 python-path=...

WSGIProcessGroup djangoapp

WSGIRestrictEmbedded On

WSGILazyInitialization On

实时服务器上的 Opbeat(此抓取有更多/更长的数据库查询,因为我正在测试删除 selecte_related()/prefetch_related() - 它们有助于缩短数据库查询时间,但不会减少太多总时间):

Wtf,发布图片需要 10 个声望?

opbeat performance breakdown chart/graph posted by a n00b

最后的想法:

  • tastypie 就这么慢吗?当然不是。虽然更好的盒子运行它~更快,但用 python 2 秒来抛出 db 20ms 的东西是否现实?
  • 是的,当我把它放在一个更快的专用开发箱上时,时间会稍微缩短一些,但它们仍然是执行 SQL 调用所需时间的 10-50 倍,例如对于使用 db < 50ms 的资源 GET,它们仍然是最快的 2 秒。所以,据我所知,这似乎不仅仅是一个资源问题。
  • 我尝试链接到 amazon RDS postgres 数据库,但它的数据库调用时间(微/免费层)慢了大约 20 倍,总往返时间也慢了。
  • 感谢您的帮助和兴趣-

最佳答案

在我的调查中,Tastypie 很慢,因为函数 django.core.urlresolvers.reverse 很慢。

我从 resource_uri 中辞职并以这种方式修补 Tastypie:

django_app/monkey/tastypie.py
from __future__ import absolute_import

from django.core.exceptions import ObjectDoesNotExist
from tastypie.bundle import Bundle
from tastypie.exceptions import ApiFieldError


def dehydrate(self, bundle, for_list=True):
if not bundle.obj or not bundle.obj.pk:
if not self.null:
raise ApiFieldError(
"The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)

return []

the_m2ms = None
previous_obj = bundle.obj
attr = self.attribute

if isinstance(self.attribute, basestring):
attrs = self.attribute.split('__')
the_m2ms = bundle.obj

for attr in attrs:
previous_obj = the_m2ms
try:
the_m2ms = getattr(the_m2ms, attr, None)
except ObjectDoesNotExist:
the_m2ms = None

if not the_m2ms:
break

elif callable(self.attribute):
the_m2ms = self.attribute(bundle)

if not the_m2ms:
if not self.null:
raise ApiFieldError(
"The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))

return []

self.m2m_resources = []
m2m_dehydrated = []

# TODO: Also model-specific and leaky. Relies on there being a
# ``Manager`` there.
m2ms = the_m2ms.all() if for_list else the_m2ms.get_query_set().all()
for m2m in m2ms:
m2m_resource = self.get_related_resource(m2m)
m2m_bundle = Bundle(obj=m2m, request=bundle.request)
self.m2m_resources.append(m2m_resource)
m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource, for_list=for_list))

return m2m_dehydrated


def _build_reverse_url(self, name, args=None, kwargs=None):
return kwargs.get('pk')


def get_via_uri(self, uri, request=None):
bundle = self.build_bundle(request=request)
return self.obj_get(bundle=bundle, pk=uri)


def build_related_resource(self, value, request=None, related_obj=None, related_name=None):
"""
Returns a bundle of data built by the related resource, usually via
``hydrate`` with the data provided.

Accepts either a URI, a data dictionary (or dictionary-like structure)
or an object with a ``pk``.
"""
self.fk_resource = self.to_class()
kwargs = {
'request': request,
'related_obj': related_obj,
'related_name': related_name,
}

if isinstance(value, Bundle):
# Already hydrated, probably nested bundles. Just return.
return value
elif isinstance(value, (basestring, int)):
# We got a URI. Load the object and assign it.
return self.resource_from_uri(self.fk_resource, value, **kwargs)
elif isinstance(value, Bundle):
# We got a valid bundle object, the RelatedField had full=True
return value
elif hasattr(value, 'items'):
# We've got a data dictionary.
# Since this leads to creation, this is the only one of these
# methods that might care about "parent" data.
return self.resource_from_data(self.fk_resource, value, **kwargs)
elif hasattr(value, 'pk'):
# We've got an object with a primary key.
return self.resource_from_pk(self.fk_resource, value, **kwargs)
else:
raise ApiFieldError("The '%s' field was given data that was not a URI, not a dictionary-alike and does not have a 'pk' attribute: %s." % (self.instance_name, value))

django_app/monkey/init.py
def patch_tastypie():
from tastypie.fields import ToManyField, RelatedField
from tastypie.resources import Resource, ResourceOptions
from monkey.tastypie import dehydrate, _build_reverse_url, get_via_uri, build_related_resource

setattr(ToManyField, 'dehydrate', dehydrate)
setattr(Resource, '_build_reverse_url', _build_reverse_url)
setattr(Resource, 'get_via_uri', get_via_uri)
setattr(ResourceOptions, 'include_resource_uri', False)
setattr(RelatedField, 'build_related_resource', build_related_resource)

django_app/init.py
from __future__ import absolute_import

from .monkey import patch_tastypie


patch_tastypie()

它并不完美,但加速了 Tastypie 10-20%

关于python - Django Tastypie Postgres 服务器响应缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33745457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com