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.
- 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')
- 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:
- 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
- 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