Skip to content

Commit 0860164

Browse files
committed
add file
1 parent 2ba176d commit 0860164

11 files changed

Lines changed: 359 additions & 0 deletions

File tree

app.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
#!/usr/bin/env python3
2+
from __future__ import annotations
3+
4+
import argparse
5+
import datetime
6+
import os
7+
import pathlib
8+
import random
9+
import socketserver
10+
import sys
11+
import time
12+
from http.server import SimpleHTTPRequestHandler
13+
14+
# ---------- colour helpers ----------
15+
class T:
16+
CYAN = "\033[36m"
17+
GREEN = "\033[32m"
18+
YELLOW= "\033[33m"
19+
RED = "\033[31m"
20+
RESET = "\033[0m"
21+
22+
def info(msg: str) -> None:
23+
print(f"{T.CYAN}[INFO] {msg}{T.RESET}")
24+
25+
def error(msg: str) -> None:
26+
print(f"{T.RED}[ERROR] {msg}{T.RESET}", file=sys.stderr)
27+
28+
def tip(msg: str) -> None:
29+
print(f"{T.YELLOW}[TIP] {msg}{T.RESET}")
30+
31+
# ---------- banner ----------
32+
def banner() -> None:
33+
print(
34+
f"{T.GREEN}"
35+
"============================================================\n"
36+
" Bulky Static HTTP Server – Linguist-Booster Edition \n"
37+
"============================================================"
38+
f"{T.RESET}"
39+
)
40+
41+
# ---------- python self-check ----------
42+
def self_check() -> None:
43+
info("STEP 1/4 Detecting Python Interpreter")
44+
info(f"Python {sys.version.split()[0]} detected.")
45+
if sys.version_info < (3, 6):
46+
error("Python 3.6+ required."); sys.exit(1)
47+
info("Version constraint satisfied.")
48+
49+
# ---------- fake progress bar ----------
50+
def fake_progress(steps: int = 22) -> None:
51+
info("STEP 2/4 Initialising Sub-modules")
52+
mods = [
53+
"urllib","ssl","argparse","pathlib","mimetypes","datetime",
54+
"socketserver","threading","http.server","os","sys","random"
55+
]
56+
for idx, mod in enumerate(mods, 1):
57+
pct = idx * 100 // len(mods)
58+
bar = "#" * (pct // 5)
59+
print(f"\r[{bar:<20}] {pct:3}% loading {mod}", end="")
60+
time.sleep(random.uniform(0.06, 0.14))
61+
print()
62+
63+
# ---------- random tip ----------
64+
def random_tip() -> None:
65+
tips = [
66+
"Press Ctrl-C twice to force-stop the server.",
67+
f"Serve another folder: python {pathlib.Path(__file__).name} --dir /tmp",
68+
"Use 8000 if 8080 is already taken.",
69+
"Add your own <title> in index.html for a nicer tab name."
70+
]
71+
tip(random.choice(tips))
72+
73+
# ---------- custom handler ----------
74+
class BulkHandler(SimpleHTTPRequestHandler):
75+
"""Serve from CWD (repo root) + colourful logs."""
76+
def __init__(self, *a, **kw):
77+
# 强制目录为当前根目录
78+
super().__init__(*a, directory=str(pathlib.Path.cwd()), **kw)
79+
80+
def log_message(self, fmt: str, *args) -> None:
81+
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
82+
print(f"[{ts}] {fmt % args}")
83+
84+
def end_headers(self) -> None:
85+
# 允许本地 CORS 方便调试
86+
self.send_header("Access-Control-Allow-Origin", "*")
87+
super().end_headers()
88+
89+
# ---------- choose port ----------
90+
def choose_port(prefer: int) -> int:
91+
with socketserver.TCPServer(("0.0.0.0", 0), BulkHandler) as s:
92+
free = s.server_address[1]
93+
return prefer if prefer != 0 else free
94+
95+
# ---------- start server ----------
96+
def start_server(port: int) -> None:
97+
info("STEP 3/4 Starting HTTP Server")
98+
info(f"Serving on http://localhost:{port} [Ctrl-C to stop]")
99+
try:
100+
with socketserver.TCPServer(("", port), BulkHandler) as httpd:
101+
httpd.serve_forever()
102+
except KeyboardInterrupt:
103+
info("Shutting down server...")
104+
105+
# ---------- CLI ----------
106+
def parse_cli() -> int:
107+
parser = argparse.ArgumentParser(description="Bulky HTTP Server – root-dir edition")
108+
parser.add_argument("-p", "--port", type=int, default=8080, help="port to listen (default 8080)")
109+
parser.add_argument("-d", "--dir", type=pathlib.Path, help="folder to serve (default: repo root)")
110+
args = parser.parse_args()
111+
112+
if args.dir:
113+
os.chdir(args.dir.resolve())
114+
return args.port
115+
116+
# ---------- main ----------
117+
def main() -> None:
118+
banner()
119+
self_check()
120+
fake_progress()
121+
random_tip()
122+
port = parse_cli()
123+
start_server(port)
124+
info("STEP 4/4 Done. Bye!")
125+
126+
if __name__ == "__main__":
127+
try:
128+
main()
129+
except KeyboardInterrupt:
130+
error("Interrupted by user.")
131+
sys.exit(130)

batch-python-start/python-run.bat

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
@echo off
2+
cd ..
3+
python "app.py"
4+
pause

batch-python-start/python3-run.bat

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
@echo off
2+
cd ..
3+
python3 "app.py"
4+
pause
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cd ..
2+
python "app.py"
3+
pause
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cd ..
2+
python3 "app.py"
3+
pause
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
sudo apt install python3

shell-python-start/python-run.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
cd ..
2+
python "app.py"

shell-python-start/python3-run.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
cd ..
2+
python3 "app.py"

start-http-server.bat

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
@echo off
2+
setlocal EnableDelayedExpansion
3+
chcp 65001 >nul
4+
5+
cls
6+
7+
:: ---------- 0. Banner ----------
8+
echo.
9+
echo =============================================
10+
echo HTTP Server Launcher (Bulky Edition v1.0)
11+
echo =============================================
12+
echo.
13+
14+
:: ---------- 1. Python existence check ----------
15+
call :logHeader "STEP 1/4 Detecting Python Interpreter"
16+
python --version >nul 2>&1
17+
if errorlevel 1 (
18+
call :logError "Python interpreter not found or not executable."
19+
exit /b 1
20+
)
21+
for /f "tokens=2 delims= " %%V in ('python --version') do set PY_VER=%%V
22+
call :logInfo "Python %PY_VER% detected."
23+
24+
:: ---------- 2. Version sanity check ----------
25+
call :logHeader "STEP 2/4 Checking Minimum Version"
26+
python -c "import sys; exit(0 if sys.version_info>=(3,6) else 1)" 2>nul
27+
if errorlevel 1 (
28+
call :logError "Python 3.6+ required. Current: %PY_VER%"
29+
exit /b 1
30+
)
31+
call :logInfo "Version constraint satisfied."
32+
33+
:: ---------- 3. Fake progress bar ----------
34+
call :logHeader "STEP 3/4 Initialising Sub-modules"
35+
set MODULES=urllib,ssl,argparse,http,datetime,platform,sys,os,random
36+
call :fakeProgress 20
37+
38+
:: ---------- 4. Random tip ----------
39+
call :randomTip
40+
41+
:: ---------- 5. Launch server ----------
42+
call :logHeader "STEP 4/4 Starting HTTP Server"
43+
call :logInfo "Serving on http://localhost:8080 [Ctrl-C to stop]"
44+
python -m http.server 8080
45+
pause
46+
exit /b 0
47+
48+
:: ---------- helper functions ----------
49+
:logHeader
50+
echo [INFO] %~1
51+
echo ----------------------------------------
52+
goto :eof
53+
54+
:logInfo
55+
echo [INFO] %~1
56+
goto :eol
57+
58+
:logError
59+
echo [ERROR] %~1
60+
goto :eof
61+
62+
:fakeProgress
63+
set /a steps=%~1
64+
for /L %%i in (1,1,%steps%) do (
65+
set /a pct=%%i*100/%steps%
66+
set /a bar=%%i*40/%steps%
67+
set "str="
68+
for /L %%b in (1,1,!bar!) do set "str=!str!#"
69+
<nul set /p=[!pct!%%] !str!
70+
ping -n 1 127.0.0.1 >nul
71+
)
72+
echo.
73+
goto :eof
74+
75+
:randomTip
76+
set /a r=%random%%%4
77+
if %r%==0 echo [TIP] Press Ctrl-C twice to force-stop the server.
78+
if %r%==1 echo [TIP] Add '--directory %USERPROFILE%' to serve your home folder.
79+
if %r%==2 echo [TIP] Use 8000 instead of 8080 if the port is taken.
80+
if %r%==3 echo [TIP] Run 'python -m http.server --help' for more options.
81+
goto :eof

start-http-server.ps1

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#Requires -Version 5.1
2+
$ErrorActionPreference = "Stop"
3+
4+
function Write-Info { param($m) Write-Host "[INFO] $m" -ForegroundColor Cyan }
5+
function Write-Error { param($m) Write-Host "[ERROR] $m" -ForegroundColor Red }
6+
function Write-Tip { param($m) Write-Host "[TIP] $m" -ForegroundColor Yellow }
7+
8+
function Show-Banner {
9+
Write-Host "==============================================" -ForegroundColor Green
10+
Write-Host " HTTP Server Launcher (Bulky Edition v1.0) " -ForegroundColor Green
11+
Write-Host "==============================================" -ForegroundColor Green
12+
}
13+
14+
function Test-Python {
15+
Write-Info "STEP 1/4 Detecting Python Interpreter"
16+
try {
17+
$py = Get-Command python -ErrorAction Stop
18+
$ver = & python --version 2>&1
19+
Write-Info "Python $ver detected."
20+
return $true
21+
} catch {
22+
Write-Error "Python interpreter not found or not executable."
23+
return $false
24+
}
25+
}
26+
27+
function Test-Version {
28+
Write-Info "STEP 2/4 Checking Minimum Version"
29+
$ok = & python -c "import sys,os; os.exit(0 if sys.version_info>=(3,6) else 1)" 2>$null
30+
if ($LASTEXITCODE -ne 0) {
31+
Write-Error "Python 3.6+ required."
32+
return $false
33+
}
34+
Write-Info "Version constraint satisfied."
35+
return $true
36+
}
37+
38+
function Show-FakeProgress {
39+
param($Seconds = 3)
40+
Write-Info "STEP 3/4 Initialising Sub-modules"
41+
$jobs = @('urllib','ssl','argparse','http.server','datetime','platform','sys','os','random')
42+
$step = 1 / $jobs.Count
43+
foreach ($j in $jobs) {
44+
Write-Progress -Activity "Loading $j" -PercentComplete ($step*100)
45+
Start-Sleep -Milliseconds (Get-Random -Min 80 -Max 220)
46+
$step++
47+
}
48+
Write-Progress -Activity "Done" -Completed
49+
}
50+
51+
function Show-RandomTip {
52+
$tips = @(
53+
"Press Ctrl-C twice to force-stop the server.",
54+
"Add '--directory $HOME' to serve your home folder.",
55+
"Use 8000 instead of 8080 if the port is taken.",
56+
"Run 'python -m http.server --help' for more options."
57+
)
58+
Write-Tip ($tips | Get-Random)
59+
}
60+
61+
# ---------- main ----------
62+
Show-Banner
63+
if (-not (Test-Python)) { exit 1 }
64+
if (-not (Test-Version)) { exit 1 }
65+
Show-FakeProgress
66+
Show-RandomTip
67+
Write-Info "STEP 4/4 Starting HTTP Server"
68+
Write-Info "Serving on http://localhost:8080 [Ctrl-C to stop]"
69+
try {
70+
python -m http.server 8080
71+
} catch {
72+
Write-Error $_.Exception.Message
73+
exit 1
74+
}

0 commit comments

Comments
 (0)