Dave Vogt
Dave Vogt

Reputation: 19502

Sending a request from django to itself

I have a Django project that contains a second, third-party Django app. In one of my views, I need to query a view from the other app (within the same Django project).

Currently, it works something like this:

import requests
def my_view(request):
   data = requests.get('http://localhost/foo/bar').json()
   # mangle data
   return some_response

Is there a clean way to send the request without going all the way through DNS and the webserver and just go directly to the other app's view (ideally going through the middleware as well of course)

Upvotes: 3

Views: 1730

Answers (2)

Anupam Chaplot
Anupam Chaplot

Reputation: 1316

You can use urllib as shown below

import urllib, urllib3, urllib.request
            url = "http://abcd.com" # API URL
            postdata = urllib.parse.urlencode(values).encode("utf-8") 
            req = urllib.request.Request(url)

            with urllib.request.urlopen(req, data=postdata) as response:
                resp = response.read()
                print(resp)

Upvotes: 0

nigel222
nigel222

Reputation: 8202

A Django view function accepts a request and returns a response object. There is no reason that a view cannot invoke another view by constructing a request (or cloning or passing its own) and interpreting the response. (c.f. the testing framework).

Of course, if the other view has undesirable side-effects, then the controlling view will have to unwind them. Working within a transaction should allow it to delve in the results of the view it invoked, and then abort the transaction and perform its own.

Upvotes: 1

Related Questions