Ameliore portail de test: photos et interruptions

This commit is contained in:
Emmanuel Viennet 2021-09-03 09:00:43 +02:00
parent 0d2926d48e
commit 84e991cef0

View File

@ -9,18 +9,22 @@ from urllib.parse import urlparse
import http.server
import os
import random
import signal
import socketserver
import sys
import time
from gen_nomprenoms import nomprenom
cur_dir = Path(os.path.abspath(__file__)).parent
script_dir = Path(os.path.abspath(__file__)).parent
# Les "photos" des étudiants
FAKE_FACES_FILENAMES = list((script_dir / "faces").glob("*.jpg"))
# Etudiant avec tous les champs (USPN)
ETUD_TEMPLATE_FULL = open(cur_dir / "etud_template.xml").read()
ETUD_TEMPLATE_FULL = open(script_dir / "etud_template.xml").read()
# Etudiant avec seulement les champs requis
ETUD_TEMPLATE_MINI = open(cur_dir / "etud_minimal_template.xml").read()
ETUD_TEMPLATE_MINI = open(script_dir / "etud_minimal_template.xml").read()
ETUD_HEAD = """<?xml version="1.0" encoding="UTF-8"?>
<etudiants>"""
@ -70,13 +74,16 @@ def make_random_etape_etuds(etape, annee):
return "\n".join(L)
FAKE_FACES_FILENAME = list(Path("faces").glob("*.jpg"))
def get_photo_filename(nip):
"""get an existing filename for a fake photo, found in faces/"""
def get_photo_filename(nip: str) -> str:
"""get an existing filename for a fake photo, found in faces/
Returns a path relative to the current working dir
"""
#
return FAKE_FACES_FILENAME[hash(nip) % len(FAKE_FACES_FILENAME)]
nb_faces = len(FAKE_FACES_FILENAMES)
if nb_faces == 0:
print("WARNING: aucun fichier image disponible !")
return ""
return Path(FAKE_FACES_FILENAMES[hash(nip) % nb_faces]).relative_to(Path.cwd())
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
@ -122,8 +129,8 @@ class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
return
elif "getPhoto" in self.path or "scodocPhoto" in self.path:
nip = query_components["nip"][0]
print(f"photo for nip={nip}")
self.path = str(get_photo_filename(nip))
print(f"photo for nip={nip}: {self.path}")
else:
print(f"Error 404: path={self.path}")
self.send_response(404)
@ -137,9 +144,21 @@ class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
PORT = 8678
my_server = socketserver.TCPServer(("", PORT), MyHttpRequestHandler)
def signal_handler(sig, frame):
print("You pressed Ctrl+C!")
raise SystemExit()
signal.signal(signal.SIGINT, signal_handler)
if __name__ == "__main__":
# Start the server
print(f"Server listening on port {PORT}...")
my_server = socketserver.TCPServer(("", PORT), MyHttpRequestHandler)
try:
my_server.serve_forever()
finally:
print("shutting down...")
my_server.shutdown()