簡體   English   中英

如何在django視圖中向另一台服務器發送請求?

[英]How to send a request to another server in a django view?

我想在我的django view向另一台服務器發送一個http請求,如下所示:

def django_view(request):
    response = send_request('http://example.com')
    result = do_something_with_response(response)
    return HttpResponse(result)

我怎樣才能做到這一點?

您可以使用python requests庫發送請求並獲取響應。 但是您需要根據需要格式化響應。

以下是GET請求的示例:

import requests

def django_view(request):
    # get the response from the URL
    response = requests.get('http://example.com')
    result = do_something_with_response(response)
    return HttpResponse(result)

唯一需要注意的是,如果你在這里做,它將不再是ajax (異步JavaScript和XML)。 另一種方法是您正常從django視圖加載網頁,然后在javascript中執行所有AJAX請求 - 進一步處理響應並在頁面中呈現它。

暫無
暫無

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

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