|
| 1 | +from rest_framework.exceptions import ParseError |
| 2 | + |
| 3 | +def get_request_data(request, key, default_value=None): |
| 4 | + """ |
| 5 | + Extracts data from request.data, request.FILES, and request.query_params based on the request method and content type. |
| 6 | +
|
| 7 | + :param request: DRF request object |
| 8 | + :param key: The key to look for in the request data |
| 9 | + :param default_value: The default value to return if the key is not found |
| 10 | + :return: The value associated with the key, or the default value if not found |
| 11 | + """ |
| 12 | + try: |
| 13 | + if request.method in ['POST', 'PUT', 'PATCH']: |
| 14 | + if request.content_type.startswith('multipart/form-data'): |
| 15 | + # For file uploads |
| 16 | + if key in request.FILES: |
| 17 | + return request.FILES.get(key) |
| 18 | + elif key in request.data: |
| 19 | + return request.data.get(key) |
| 20 | + elif request.content_type in ['application/json', 'application/x-www-form-urlencoded']: |
| 21 | + # For JSON or form-encoded data |
| 22 | + if key in request.data: |
| 23 | + return request.data.get(key) |
| 24 | + elif request.method == 'GET': |
| 25 | + if key in request.query_params: |
| 26 | + return request.query_params.get(key) |
| 27 | + else: |
| 28 | + if key in request.query_params: |
| 29 | + return request.query_params.get(key) |
| 30 | + |
| 31 | + return default_value |
| 32 | + except Exception as e: |
| 33 | + raise ParseError(f"Error extracting request data for key '{key}': {str(e)}") |
0 commit comments