在openshift上压力测试我的django的好方法

时间:2014-09-29 09:58:49

标签: python django stress-testing

我正在努力找到一个很好的方法来检查我的django应用程序如何响应来自许多用户的许多请求。我使用django的测试客户端

实现了这个脚本
from threading import Thread
from time import sleep
import logging
from django.conf import settings

logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
                   )
import os, sys
from datetime import datetime, timedelta

os.environ['DJANGO_SETTINGS_MODULE'] = 'app.settings'
script_path = os.path.dirname(__file__)
project_dir = os.path.abspath(os.path.join(script_path, '..'))

sys.path.insert(0, project_dir)


if __name__ == '__main__':
    from django.test.client import Client
    from django.core.urlresolvers import reverse
    from django.test.utils import setup_test_environment

    setup_test_environment()

    def stress_test(username, password, requests, wait):
        #create Client. Each Thread will have one
        client = Client()
        logging.debug('created client')

        #login user based on username and password provided
        client.login(username=username, password=password)
        logging.debug('User Logged in')

        #make a post request on /crm/customer/ causes django to execute search on customers.
        #needs ajax request
        #no of requests made by user
        for k in range(0, requests):
            logging.debug("Making search response with no args")
            response = client.post(reverse('customer'), {'doctor': client.session['_auth_user_id']},
                                   HTTP_X_REQUESTED_WITH="XMLHttpRequest",)

            #logging.debug("Wait..")
            sleep(wait)

        client.logout()

    thread_pool = []
    for i in range(0, 10):
        if settings.DEBUG:
            thread = Thread(name="Thread-%d" %i, target=stress_test, args=('doctor1', 'doctor1', 10, 5,))
        else:
            thread = Thread(name="Thread-%d" %i, target=stress_test, args=('avlahop', 'avlahop', 10, 5,))

        thread_pool.append(thread)
        thread.start()

    for thread in thread_pool:
        thread.join()

这是获得一些结果的好方法吗?帖子网址在我的数据库上执行搜索。执行的视图如下

def index(request):
    search = False
    filtered = []
    customer_form = CustomerSearchForm(request.POST or None)
    practice_data = request.user.practice
    doctors = get_user_model().objects.filter(practice=practice_data, groups__name='doctors')
    customer_form.fields['doctor'].queryset = doctors
    customers = Customer.objects.filter(practice=practice_data)
    customers_no = customers.count()
    if request.method == 'POST' and request.is_ajax():
        if customer_form.is_valid():
            post_data = customer_form.cleaned_data
            empty = True if post_data.values().count("") == len(post_data.values()) - 2 and post_data.values().count(None) == 2 else False
            if empty:
                print empty
                start = time.time()
                search_result = customers
                end = time.time()
                duration = end - start                   
            else:
                search_terms = {}
                for field in post_data.keys():
                    if post_data[field] is not None and post_data[field] != "":
                        search_terms.update({field: post_data[field]})
                if post_data['doctor']:
                    customers = customers.filter(doctor=post_data['doctor'])
                    del post_data['doctor']
                    print 'doctor' in post_data


                search_result = []
                start = time.time()
                search_result = filter(lambda customer: my_filter(customer, search_terms), list(customers)
                try:
                    import operator
                except:
                    cmpkey = lambda x: (x.last_name, x.first_name)

                else:
                    cmpkey = operator.attrgetter('last_name', 'first_name')
                search_result.sort(key=cmpkey, reverse=False)
                end = time.time()
                duration = end - start
            return render_to_response('customer/ajax/search_results.html', dict(customers=search_result, duration=duration))

    search = True

    return { 'customers': customers, 'search': search, "customers_no": customers_no,
         'customer_form': customer_form}

和my_filter函数

def my_filter(customer, search_terms):
    satisfies = True
    for field in search_terms.keys():
        if getattr(customer, field):
            if isinstance(search_terms[field], date) or isinstance(search_terms[field], get_user_model()):
                if getattr(customer, field) != search_terms[field]:
                    satisfies = False
                    break
            elif not getattr(customer, field).lower().startswith(search_terms[field].lower()):
                satisfies = False
                break
        else:
            satisfies = False
    return satisfies

我用于模型因为我在之前的问题中说客户模型字段是加密的。有什么方法可以优化搜索。我应该使用numpy数组而不是python列表吗?你能说出我的代码是否多次击中我的数据库?有没有更好的方法来检查我的django应用程序在现实世界的测试中(许多请求用户等)?

0 个答案:

没有答案