0

I wrote a command to be called by cron in django project. we need to print the full url to my django project. But the dev url is different from prod url.

For example, my dev url is: https://<dev machine ip>/myproject/dashboard/data

My prod url may be https://companyname.com/myproject/dashboard/data

Expected:

for dev: https://<dev machine ip>/myproject

for prod: https://companyname.com/myproject

I would not like to hard code the url. How to get the full url or root url inside command file below?

class Command(BaseCommand):
        def handle(self, *args, **options):
                url = "url" # need to get url here
BAE
  • 8,550
  • 22
  • 88
  • 171
  • Does cron run on the respective server for both of them, or only one cron runs? In the first case you can use `localhost`. In the second, you can consider running a second cron. – Wtower Apr 08 '16 at 17:13
  • https://docs.djangoproject.com/en/dev/ref/contrib/sites/#getting-the-current-domain-for-full-urls – DevLounge Apr 08 '16 at 20:21
  • look at the answer from shacker – DevLounge Apr 08 '16 at 20:23

1 Answers1

0

I would set this as a variable in settings.py. You will have to create a token file or an environment variable on your production server, then make the variable depend on its existence.

settings.py:

import os

# Either use a token file
PRODUCTION = os.path.exists('/somewhere/convienent/.DJANGO_PRODUCTION_TOKEN')
# Or use an environment variable
PRODUCTION = 'DJANGO_PRODUCTION_SERVER' in os.environ

if PRODUCTION:
    BASE_URL = "<dev machine ip>" # This could be computed if you want.
else:
    BASE_URL = "companyname.com"

Your command:

from django.conf import settings

class Command(BaseCommand):
    def handle(self, *args, **options):
        url = settings.BASE_URL
Travis
  • 1,998
  • 1
  • 21
  • 36