Iteration3 Update Setup.py and ps1 (#42)

* Update Setup file

* Add install method

* Update setup.py
This commit is contained in:
Sirin Puenggun 2023-09-17 00:14:54 +07:00 committed by GitHub
parent 216764d3aa
commit 3a5d8dacbf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 163 additions and 38 deletions

View File

@ -5,7 +5,7 @@ An application to conduct online polls and surveys based
on the [Django Tutorial project](https://docs.djangoproject.com/en/4.2/intro/tutorial01/), with additional features. on the [Django Tutorial project](https://docs.djangoproject.com/en/4.2/intro/tutorial01/), with additional features.
## Install and Run ## Install and Run
### Run Setup.py Method ### Run Setup.py (Recommended)
1. Install [Python 3.11 or later](https://www.python.org/downloads/) 1. Install [Python 3.11 or later](https://www.python.org/downloads/)
2. Clone this repository and Run `setup.py` to install and run the project 2. Clone this repository and Run `setup.py` to install and run the project
@ -15,12 +15,15 @@ git clone https://github.com/Sosokker/ku-polls
cd ku-polls cd ku-polls
python setup.py python setup.py
``` ```
If you want to customize the environment variables, name of environment folder then run this command
```bash
python setup.py -custom
```
or run `setup.ps1` (For Windows User) or run `setup.ps1` (For Windows User)
---- ----
### Manual ### Manual Installation (If the above method doesn't work)
1. Install [Python 3.11 or later](https://www.python.org/downloads/) 1. Install [Python 3.11 or later](https://www.python.org/downloads/)
2. Run these commands to clone and install requirements.txt 2. Run these commands to clone and install requirements.txt
```bash ```bash

View File

@ -18,6 +18,8 @@ if (-not (Test-Path .venv)) {
Write-Host "Using existing virtual environment." Write-Host "Using existing virtual environment."
} }
$python_in_venv = ".\.venv\Scripts\python"
if ($setup_venv -eq "yes") { if ($setup_venv -eq "yes") {
if (-not (Test-Path (Get-Command virtualenv -ErrorAction SilentlyContinue))) { if (-not (Test-Path (Get-Command virtualenv -ErrorAction SilentlyContinue))) {
Write-Host "Error: virtualenv is not installed. Please install it and rerun this script." Write-Host "Error: virtualenv is not installed. Please install it and rerun this script."
@ -28,7 +30,11 @@ if ($setup_venv -eq "yes") {
.\.venv\Scripts\Activate .\.venv\Scripts\Activate
} }
python -m pip install -r requirements.txt # Now, use the Python interpreter within the virtual environment for subsequent commands.
$python_in_venv = ".\.venv\Scripts\python"
# For example:
& $python_in_venv -m pip install -r requirements.txt
$secret_key = (python manage.py shell -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())') $secret_key = (python manage.py shell -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())')
@" @"

184
setup.py
View File

@ -1,10 +1,13 @@
import os import os
import subprocess import subprocess
import sys import sys
import argparse
is_windows = os.name == 'nt' is_windows = os.name == 'nt'
is_posix = os.name == 'posix' is_posix = os.name == 'posix'
def check_python_command(): def check_python_command():
python_commands = ["python", "py", "python3"] python_commands = ["python", "py", "python3"]
@ -17,46 +20,159 @@ def check_python_command():
return None return None
python_command = check_python_command() def create_virtual_environment(env_name, python_command):
subprocess.run([python_command, "-m", "venv", env_name], check=True)
if python_command is None: def customize_virtual_environment():
print("Error: Python interpreter not found. Please specify the Python command (e.g., python, py, python3).") env_name = input("Enter a custom virtual environment name (or press Enter for the default): ").strip()
sys.exit(1) if not env_name:
env_name = ".venv"
return env_name
setup_venv = input("Do you want to set up a virtual environment? (yes/no): ").lower() def setup_environment_variables(python_command_in_venv):
if setup_venv == "yes": print("Setting up Django environment variables:")
if not os.path.exists(".venv"):
print("Creating a new virtual environment...") # SECRET KEY
subprocess.run([python_command, "-m", "venv", ".venv"]) generate_secret_key = input("Generate a Django SECRET_KEY? (yes/no): ").strip().lower()
if generate_secret_key == "yes":
secret_key = subprocess.check_output([python_command_in_venv, "manage.py", "shell", "-c",
'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())']).decode().strip()
else: else:
print("Using an existing virtual environment.") secret_key = input("Enter Django SECRET_KEY: ").strip()
# DEBUG MODE
while True:
debug_mode = input("Enable DEBUG mode? (True/False): ").strip()
if debug_mode in ["True", "False"]:
break
else:
print("Please enter 'True' or 'False' for DEBUG mode. (Case Sensitive)")
if is_posix: # ALLOWED_HOSTS
activate_command = os.path.join(".venv", "bin", "activate") allowed_hosts = input("Enter ALLOWED_HOSTS (comma-separated, or press Enter for default): ").strip()
elif is_windows: if not allowed_hosts:
activate_command = os.path.join(".venv", "Scripts", "activate") allowed_hosts = "*.ku.th,localhost,127.0.0.1,::1"
subprocess.run([activate_command], shell=True)
# TZ
available_time_zones = ["Asia/Bangkok", "Japan", "UCT", "CST6CDT", "Custom"]
print("Available time zone options:")
for idx, tz in enumerate(available_time_zones, start=1):
print(f"{idx}. {tz}")
subprocess.run([python_command, "-m", "pip", "install", "-r", "requirements.txt"]) while True:
try:
selected_tz_index = int(input("Enter the number for TIME_ZONE: ")) - 1
if 0 <= selected_tz_index < len(available_time_zones):
time_zone = available_time_zones[selected_tz_index]
break
elif (selected_tz_index == len(available_time_zones)):
time_zone = input("Please enter you timezone: ")
break
else:
print("Invalid choice. Please enter a valid number.")
except ValueError:
print("Invalid input. Please enter a valid number.")
email_host_password = input("Enter EMAIL_HOST_PASSWORD: ").strip()
secret_key = subprocess.check_output([python_command, "manage.py", "shell", "-c", # SET
'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())']).decode().strip() with open(".env", "w") as env_file:
env_file.write(f"""SECRET_KEY={secret_key}
DEBUG={debug_mode}
ALLOWED_HOSTS={allowed_hosts}
TIME_ZONE={time_zone}
EMAIL_HOST_PASSWORD={email_host_password}
""")
with open(".env", "w") as env_file: def main():
env_file.write(f"""SECRET_KEY={secret_key} parser = argparse.ArgumentParser(description="Django Setup Script")
DEBUG=False parser.add_argument("-custom", action="store_true", help="Enter custom mode")
ALLOWED_HOSTS=*.ku.th,localhost,127.0.0.1,::1 args = parser.parse_args()
TIME_ZONE=Asia/Bangkok
EMAIL_HOST_PASSWORD=temppassword
""")
subprocess.run([python_command, "manage.py", "migrate"]) python_command = check_python_command()
subprocess.run([python_command, "manage.py", "loaddata", "data/users.json"])
subprocess.run([python_command, "manage.py", "loaddata", "data/polls.json"])
start_server = input("Do you want to start the Django server? (yes/no): ").lower() if python_command is None:
if start_server == "yes": print("Error: Python interpreter not found. Please specify the Python command (e.g., python, py, python3).")
print("=================================================") sys.exit(1)
print("Django run in --insecure mode to load Static File")
print("==================================================") if not args.custom:
subprocess.run([python_command, "manage.py", "runserver", "--insecure"]) if python_command is None:
print("Error: Python interpreter not found. Please specify the Python command (e.g., python, py, python3).")
sys.exit(1)
setup_venv = input("Do you want to set up a virtual environment? (yes/no): ").lower()
if setup_venv == "yes":
print("==========================Default Mode==========================")
if not os.path.exists(".venv"):
print("Creating a new virtual environment...")
subprocess.run([python_command, "-m", "venv", ".venv"])
else:
print("==========================Using an existing virtual environment.==========================")
if is_posix:
activate_command = os.path.join(".venv", "bin", "activate")
elif is_windows:
activate_command = os.path.join(".venv", "Scripts", "activate")
subprocess.run([activate_command], shell=True)
python_command = os.path.join(".venv", "bin", "python") if is_posix else os.path.join(".venv", "Scripts", "python")
else:
print("Not setting up a virtual environment. Using the global Python interpreter.")
subprocess.run([python_command, "-m", "pip", "install", "-r", "requirements.txt"])
secret_key = subprocess.check_output([python_command, "manage.py", "shell", "-c",
'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())']).decode().strip()
with open(".env", "w") as env_file:
env_file.write(f"""SECRET_KEY={secret_key}
DEBUG=False
ALLOWED_HOSTS=*.ku.th,localhost,127.0.0.1,::1
TIME_ZONE=Asia/Bangkok
EMAIL_HOST_PASSWORD=temppassword
""")
subprocess.run([python_command, "manage.py", "migrate"])
subprocess.run([python_command, "manage.py", "loaddata", "data/users.json"])
subprocess.run([python_command, "manage.py", "loaddata", "data/polls.json"])
start_server = input("Do you want to start the Django server? (yes/no): ").lower()
if start_server == "yes":
print("=================================================")
print("Django run in --insecure mode to load Static File")
print("==================================================")
subprocess.run([python_command, "manage.py", "runserver", "--insecure"])
else:
try:
print("==========================Custom Mode==========================")
python_commands = check_python_command()
env_name = customize_virtual_environment()
create_virtual_environment(env_name, python_commands)
print(f"Finishing Create Virtual environment {env_name}")
python_command_in_venv = os.path.join(env_name, "bin", "python") if is_posix else os.path.join(env_name, "Scripts", "python")
print(f"==========================Install Requirement==========================")
subprocess.run([python_command_in_venv, "-m", "pip", "install", "-r", "requirements.txt"])
setup_environment_variables(python_command_in_venv)
subprocess.run([python_command_in_venv, "-m", "pip", "install", "-r", "requirements.txt"], check=True)
subprocess.run([python_command_in_venv, "manage.py", "migrate"], check=True)
subprocess.run([python_command_in_venv, "manage.py", "loaddata", "data/users.json"], check=True)
subprocess.run([python_command_in_venv, "manage.py", "loaddata", "data/polls.json"], check=True)
start_server = input("Do you want to start the Django server? (yes/no): ").strip().lower()
if start_server == "yes":
print("=================================================")
print("Django run in --insecure mode to load Static File")
print("==================================================")
subprocess.run([python_command_in_venv, "manage.py", "runserver", "--insecure"], check=True)
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
sys.exit(1)
except KeyboardInterrupt:
print("\nSetup process aborted.")
sys.exit(1)
if __name__ == "__main__":
main()