Hello everyone,
I'm working on a Django application which needs to communicate with a 3rd-party REST API. In production the flow would be like this;
- end-user browser sends a request to my django server
- my server makes a remote REST call to 3rd party server
- 3rd party server responds
- my server sends back response to end-user's browser
I'm simulating the above flow during development by using the Httpretty mocking library. Here is how my view looks like;
import httpretty
THIRD_PARTY_SERVER = http://api.gitlab.com/
def my_view(request):
if settings.DEBUG:
httpretty.enable()
httpretty.register_uri(httpretty.GET, THIRD_PARTY_SERVER, body='{some_mock_response_here}')
partner_response = requests.get(THIRD_PARTY_SERVER)
if settings.DEBUG:
httpretty.disable()
httpretty.reset()
# Do some stuff here
# ...
return render(request, 'template.html', context)
For the most part, the above works. I can experiment around without hitting the 3rd-party API. But it doesn't feel good. My mocking code is now part of the view function - not what I consider a good design. Problem is, I'm not sure how else this can be done? Does anyone have any better ideas? Note - I'm not doing any testing here. Just need a way to mock 3rd-party REST responses during development when I run "python manage.py runserver" for debugging/experimentation.
Ideally, I'd like to move all the mocking code to it's own file and away from my views. This should somehow get activated when I start 'runserver' and work for all my views.
Puzzled,
Abraham V.