How are HTTP requests and responses handled in Django?

In Django, handling HTTP requests and responses is primarily done through view functions. View functions are Python functions that receive an HTTP request as input and return an HTTP response as output.

Handling HTTP requests.

  1. Define a view function: Define a view function in the views.py file, which takes an HttpRequest object as a parameter, allowing access to information such as the request method, path, and parameters.
from django.http import HttpResponse

def my_view(request):
    # 获取请求参数
    param_value = request.GET.get('param_key', '')
    
    # 处理请求逻辑
    ...
    
    return HttpResponse('Response content')
  1. Configure URL routing: Set up URL routing in the urls.py file to map request paths to the corresponding view functions.
from django.urls import path
from .views import my_view

urlpatterns = [
    path('my_route/', my_view),
]

Handle HTTP responses:

  1. Constructing an HttpResponse object: In a view function, you can use the HttpResponse class to create a response object by passing in parameters such as response content and status code.
from django.http import HttpResponse

def my_view(request):
    # 处理请求逻辑
    ...
    
    # 构造响应对象
    response = HttpResponse('Response content', status=200)
    
    return response
  1. To return a JSON response, you can use the JsonResponse class.
from django.http import JsonResponse

def my_view(request):
    # 处理请求逻辑
    ...
    
    # 构造Json响应
    response_data = {'key': 'value'}
    response = JsonResponse(response_data)
    
    return response
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds