views:

119

answers:

2

I am trying to mock-up an API and am using separate apps within Django to represent different web services. I would like App A to take in a link that corresponds to App B and parse the response (json).

Is there a way to dynamically construct the url to App B so that I can test the code in development and not change to much before going into production? The problem is that I can't use localhost as part of a link.

I am currently using urllib, but eventually I would like to do something less hacky and better fitting with the web services (REST) paradigm.

+2  A: 

You could do something like

if settings.DEBUG:
  other = "localhost"
else:
  other = "somehost"

and use other to build the external URL. Generally you code in DEBUG mode and deploy in non-DEBUG mode. settings.DEBUG is a 'standard' Django thing.

J. Pablo Fernández
platform.node() is also really useful for this (the platform module is part of the standard library).
Justin Voss
+1  A: 

By "separate apps within Django" do you mean separate applications with a common settings? That is to say, two applications within the same Django site (or project)?

If so, the {% url %} tag will generate a proper absolute URL to any of the apps listed in the settings file.

If there are separate Django servers with separate settings, you have the standard internet problem of URI design. Your URI's can be consistent with only the hostname changing.

- http://localhost/some/path - development

- http://123.45.67.78/some/path - someone's laptop who's running a server for testing

- http://qa.mysite.com/some/path - QA

- http://www.mysite.com/some/path - production

You never need to provide the host information, so all of your links are <A HREF="/some/path/">.

This, generally, works out the best. You have can someone's random laptop being a test server; you can get the IP address using ifconfig.

S.Lott
How do I use the {% url %} functionality while in somewhere other than a template?
thaiyoshi
model.get_absolute_url()
S.Lott
You can also use django.core.urlresolvers.reverse (look in the docs) to get any URL, not just a model's absolute URL.
Justin Voss