1. example: to create a simple url with a BASE_URL veriable
# settings.py
BASE_URL = 'http://127.0.0.1:8000'
# views.py
from django.conf import settings
class CommentViewSet(SerializerClassMixin, ModelViewSet):
def perform_create(self, serializer):
project_pk = self.kwargs["project_pk"]
issue_pk = self.kwargs["issue_pk"]
issue_url = f"{settings.BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
2. example: create BASE_URL in your operating system
Define the base URL as an environment variable in your operating system. The process for this varies depending on your operating system. For example, in a Unix-based system like Linux or MacOS, you can add the following line to your shell profile file (like ~/.bashrc
or ~/.bash_profile
for Bash shell, ~/.zshrc
for Zsh shell).
export BASE_URL="http://127.0.0.1:8000"
Then, source the profile file or restart your terminal to apply the changes:
source ~/.bashrc
In your Python script, use the os module to access the environment variable.
# views.py
import os
class CommentViewSet(SerializerClassMixin, ModelViewSet):
BASE_URL = os.getenv("BASE_URL")
def perform_create(self, serializer):
project_pk = self.kwargs["project_pk"]
issue_pk = self.kwargs["issue_pk"]
issue_url = f"{BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
3. example: save the BASE_URL in an .env
file
First, you need to install the python-dotenv
module. You can do this using pip, which is a package manager for Python. Run the following command in your terminal.
pip install python-dotenv
This command installs the python-dotenv
module, which allows you to specify environment variables in a .env
file in your project directory.
Next, create a .env
file in the root directory of your project. This file will contain your environment variables. Each variable should be defined on a new line in the format KEY=VALUE
. In your case, you would add the following line to your .env
file.
# .env
BASE_URL=http://127.0.0.1:8000
n your Python script, you can now use the load_dotenv
function from the dotenv
module to load the environment variables from the .env
file. Then, you can use the os.getenv
function to retrieve the value of the BASE_URL environment variable.
# views.py
import os
from dotenv import load_dotenv
class CommentViewSet(SerializerClassMixin, ModelViewSet):
BASE_URL = os.getenv("BASE_URL")
def perform_create(self, serializer):
project_pk = self.kwargs["project_pk"]
issue_pk = self.kwargs["issue_pk"]
issue_url = f"{BASE_URL}/api/projects/{project_pk}/issues/{issue_pk}/"
Top comments (1)
🌴💛