29👍
This should works:
from django.http import HttpResponse
import requests
requests_response = requests.get('/some-url/')
django_response = HttpResponse(
content=requests_response.content,
status=requests_response.status_code,
content_type=requests_response.headers['Content-Type']
)
return django_response
1👍
To add to Brian Loughnane’s answer: when I tried the solution:
for k, v in requests_response.headers.items():
django_response[k] = v
I got an error from django: AssertionError: Hop-by-hop headers not allowed
I don’t know if it’s the best solution but I "fixed" it by removing the offending headers.
from wsgiref.util import is_hop_by_hop
for k, v in requests_response.headers.items():
if not is_hop_by_hop(k):
django_response[k] = v
- Create a Session in Django
- GeoDjango, difference between dwithin and distance_lt?
- How to send success message if we use django generic views
0👍
This may help you :
requests.models.Response
class which,has json() method (according to the documentation) that deserializes the JSON response into a Python object using json.loads(). Try to print following and you can access whatever you are looking for.
print yourResponse.json()
- Setting up proper testing for Django for TDD
- How do you create a Django HttpRequest object with the META fields populated?
- Graphene-python performance issues for large data sets
- Django url patterns with 2 parameters
0👍
To add to paivatulio’s answer, you can forward the headers like so:
for k, v in requests_response.headers.items():
django_response[k] = v
- Django – http code 304, how to workaround in the testserver?
- Save the related objects before the actual object being edited on django admin
- How to download a filefield file in django view
- Multiple USERNAME_FIELD in django user model
- Django default cache
0👍
I don’t know if this should be a comment but I don’t have enough reputation to post comments, but this might help:
If you came searching for Django Rest Framework way of doing this, we can modify @paivatulio’s answer like this:
import requests
from rest_framework.response import Response
requests_response = requests.get('/some-url/')
def covert_to_drf_response(response):
drf_response = Response(
data=requests_response.json(),
status=requests_response.status_code),
)
return drf_response
drf_response = convert_to_drf_response(requests_response)
This might also be helpful if you prefer to use DRF’s Response over HttpResponse for the reasons stated here
You can also set your content_type as @paivatulio did.
- Django 'TestForm' object has no attribute 'fields'
- Psycopg2 OperationalError: cursor does not exist
- Can not use celery delay for saved form: object is not JSON serializable
- Using Pre_delete Signal in django
- Django session expiry?