簡體   English   中英

如何計算 Django Python 中的響應時間

[英]How to calculate response time in Django Python

我是 Django Python 的新手。 請告知如何計算從用戶輸入搜索條件到相關信息加載/顯示到門戶的響應時間。 謝謝。

Django 是一個用於后端操作的 Python 框架。 它的目的是處理http請求,因此您的問題“從用戶輸入搜索條件到加載/顯示相關信息的那一刻”在這種情況下非常模糊。 您的問題表明您正在研究一些基於 Javascript/Ajax 的交互式前端?

如果您對單個 http 請求的渲染時間感到好奇,您可以使用自定義中間件來解決這個問題,大致如下:

class StatsMiddleware(object):
    def process_request(self, request):
        "Start time at request coming in"
        request.start_time = time.time()

    def process_response(self, request, response):
        "End of request, take time"
        total = time.time() - request.start_time

        # Add the header.
        response["X-total-time"] = int(total * 1000)
        return response

然后,在相應的 Django settings.py部分添加這個中間件:

MIDDLEWARE_CLASSES = (
  ...
  'app.stats.StatsMiddleware',
  ...
)

生成響應所花費的時間將添加到自定義 http 標頭“X-total-time”中。 請注意,這將涉及所有渲染、計算、第 3 方系統和數據庫操作。

從 Django 1.10 開始,現在的工作方式有所不同。

https://docs.djangoproject.com/en/3.0/topics/http/middleware/

新樣式如下:

import time


class StatsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()

        response = self.get_response(request)

        duration = time.time() - start_time

        # Add the header. Or do other things, my use case is to send a monitoring metric
        response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
        return response

無需在請求對象上存儲開始時間並進行檢索,因為這一切都發生在同一個方法中。

它也可以用簡單的函數樣式而不是類來完成:

import time


def stats_middleware(get_response):

    def middleware(request):
        start_time = time.time()

        response = get_response(request)

        duration = time.time() - start_time

        response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
        return response

    return middleware

這是完成整個事情的課程

import time


class StatsMiddleware(object):

    def process_request(self, request):
        "Store the start time when the request comes in."
        request.start_time = time.time()

    def process_response(self, request, response):
        "Calculate and output the page generation duration"
        # Get the start time from the request and calculate how long
        # the response took.
        duration = time.time() - request.start_time

        # Add the header.
        response["X-Page-Generation-Duration-ms"] = int(duration * 1000)
        return response

這就是全部。 只需存儲請求進來的時間,並在以后檢索它。

要安裝上面的中間件,只需將其添加到 settings.py 中:

MIDDLEWARE_CLASSES = (
    'project.stats_middleware.StatsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
)

您可以在 Internet 瀏覽器 (F12) 中看到它,或者如果您使用 POSTMAN,它會顯示時間。 您還可以使用標准 python 庫time來測量一段代碼的執行時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM