我在django项目中编写了一个由cron调用的命令。我们需要将完整的URL打印到我的django项目中。但是dev url与prod url不同。
例如,我的开发网址是:https://<dev machine ip>/myproject/dashboard/data
我的产品网址可能是https://companyname.com/myproject/dashboard/data
预期:
for dev:
https://<dev machine ip>/myproject
为刺激:
https://companyname.com/myproject
我不想对网址进行硬编码。如何获取下面命令文件中的完整URL或根URL?
class Command(BaseCommand):
def handle(self, *args, **options):
url = "url" # need to get url here
答案 0 :(得分:0)
我会将其设置为settings.py
中的变量。您必须在生产服务器上创建令牌文件或环境变量,然后使变量取决于其存在。
<强> 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"
您的命令:
from django.conf import settings
class Command(BaseCommand):
def handle(self, *args, **options):
url = settings.BASE_URL