tags:

views:

28

answers:

2

During the processing of a request in Django, I need to perform a nested request to the same application. Consider this example, where while processing the sendmail request, I attempt to make another request to the same server to obtain the content of an attachment (the body of the mail and a list of urls whose content to attach are provided to the sendmail view function through POST parameters):

def sendmail(request):
    mail = #... create a mail object
    for url in urls: # iterate over desired attachments urls
        data = urllib.urlopen('http://127.0.0.1:8000' + url).read()
        mail.attach(data)

There are several issues with this approach. First, it doesn't work with the development server because it can only process one request at a time: as it is already processing the sendmail request, attempting to read from the given url will block forever. Second, I have to specify the server's ip and port, which is not very nice.

I would like to do something like that instead:

data = django_get(url).read()

where the hypothetical django_get method would not really make an http request, but instead directly call the django component that takes an url and returns an HttpResponse. That would solve both problems, as there would not be any actual socket connection, and it would not be necessary to include the server/port in the url. How could that be achieved?

+1  A: 

The opposite of reverse() is resolve().

Also, this.

Ignacio Vazquez-Abrams
Exactly what I needed, many thanks.
gpothier
A: 

Put the desired functionality in a separate function that both your sendmail function and the original page's function can call.

That would mean I have to parse the url in my sendmail function to determine which function to call, which is the job django already does when parsing urls... I think Ignacio's answer is what I was looking for.
gpothier
@gpothier The dynamic part of the URL is not an argument to the function?