0

I have a package:

urls/
    __init__.py
    dev_urls.py
    prod_urls.py

This urls package is in an app api and in my main urls.py:

...
url(r'^api/v1/', include('apps.api.urls')),
...

I know that if I add this to urls.__init__.py file:

# __init__.py
from dev_urls import *

Django will run including dev_urls.py as apps.api.urls.

But I'd like to make this dynamic by adding a variable in my settings module:

# settings
URLS_ENV = 'dev'  # This could be 'prod'

Then in my urls.__init__.py:

# __init__.py
from django.conf import settings
name = settings.URLS_ENV + '_urls'

Now, here is the question: How can I do somwthing like:

from <name> import *

Is this possible?

Gocht
  • 9,924
  • 3
  • 42
  • 81
  • 1
    Not exactly a duplicate but probably having enough information to answer: http://stackoverflow.com/q/301134/4996248 – John Coleman Jan 20 '17 at 16:44
  • @JohnColeman I've read that answer yet. Thank. Note that what I want is to get the functionality to import `apps.api.urls.dev_urls.py` as `apps.api.urls` using `__init__.py` – Gocht Jan 20 '17 at 16:47

2 Answers2

1

No, you can't change the name you import from without changing the filename, the __name__ property you're probably thinking of is set by how you import it. You would need to use a custom import as John suggested (see here to import *) or modify the included path as follows

...
url(r'^api/v1/', include('apps.api.urls.' + settings.URLS_ENV + '_urls')),
..
Community
  • 1
  • 1
yummies
  • 686
  • 6
  • 14
1

I found this answer https://stackoverflow.com/a/301139/3945375

This worked for me, this is running:

# urls.__init__.py

from django.conf import settings

mod = settings.URL_ENVIRONMENT + '_urls'
exec 'from %s import *' % mod
Community
  • 1
  • 1
Gocht
  • 9,924
  • 3
  • 42
  • 81