KindOfGuy
KindOfGuy

Reputation: 3211

Correct root url in Django views.py

I need to refer to the correct, environment-specific root url in views.py. Here's the situation. I am posting an event image to Facebook, grabbing the image with urllib2.

I need to make the url dynamically adjust to the current environment. My solution is to use a conditional based on environment-variables (as I do in settings.py for env-specific database config). So I have:

    # Get appropriate, environment-specific root url for urllib call below.
    try:
        if os.environ['ENV'] == 'staging':
            img_url = 'http://www.mysite.com/static/img/logo.png'
    except:
        img_url = 'http://localhost:8000/static/img/logo.png'

    graph.post(
        path = fb_event_path,
        source = urllib2.urlopen(img_url))

This works locally and in production (i.e. staging), but I find it a little hacky. There must be a slicker way to set a variable with root URL in views.py. What is it? Thanks.

Upvotes: 0

Views: 221

Answers (1)

xelblch
xelblch

Reputation: 697

Just hide your staging/dev logic into settings.py like this:

DOMAIN = 'www.mysite.com'  # Production DOMAIN    

if os.environ['ENV'] != 'staging':
    DOMAIN = 'localhost:8000'  # Dev DOMAIN

Or add this into the end of your settings.py

from settings_local import *

And define DOMAIN in your settings_local.py:

DOMAIN = 'localhost:8000'

And finally in your view:

from settings import DOMAIN, STATIC_URL

img_url = 'http://{domain}/{static}/img/logo.png'.format(
    domain=DOMAIN, 
    static=STATIC_URL
)

graph.post(
    path = fb_event_path,
    source = urllib2.urlopen(img_url)
)

Upvotes: 1

Related Questions