SPB Git

Repository Public

service-simule.py 6.9 KB 161 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project          : Vrai-Prix Android10# File             : tools/service-simule.py11# Module           : tools12# Repository       : https://git.spboucher.ai/vrai-prix-android13# Project Website  : https://www.vrai-prix.com14# Created          : 2026-11-2915# Last Modified    : 2026-11-2916#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author           : Simon-Pierre Boucher22# Position         : Professor of Finance23# Institution      : Université du Québec en Outaouais (UQO)24# Department       : Département des sciences administratives25# Organization     : SP Boucher26#27# Website          : https://spboucher.ai28# Git              : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General          : info@spboucher.ai35# Professional     : contact@spboucher.ai36# Direct           : simon@spboucher.ai37# Research         : research@spboucher.ai38# Development      : dev@spboucher.ai39# Support          : support@spboucher.ai40# Security/Admin   : admin@spboucher.ai41# Notifications    : notifications@spboucher.ai42#43# Preferred Contact: dev@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification   : Public68# Distribution     : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License          : None specified (no license file in this repository)82# Maintainer       : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889# Vrai-Prix Android90# File: tools/service-simule.py91# Description: service simulé pour les essais sur émulateur (version de développement, extra `base_url`92#              http://10.0.2.2:8791). Relaie les GET vers la production, en lecture seule ; ne relaie JAMAIS un POST :93#              la méthode du coût répond par les réponses enregistrées. Modes : `v3` (défaut), `v2` (la sonde94#              /api/v3/version rend la page HTML d'un site sans API v3 : repli sur l'API 2), `panne` (50395#              engine_unavailable sur /api/v3/proprietes).96#97# Author: Simon-Pierre Boucher98# Contact: contact@spboucher.ai99#100# Usage : python3 -I tools/service-simule.py [v3|v2|panne] [port]101102import json103import sys104import urllib.error105import urllib.request106from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer107from pathlib import Path108109MODE = sys.argv[1] if len(sys.argv) > 1 else "v3"110PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 8791111PROD = "https://www.vrai-prix.com"112FIXTURES = Path(__file__).resolve().parent.parent / "app/src/test/resources/fixtures"113114115class Handler(BaseHTTPRequestHandler):116    def reply(self, code, body, ctype="application/json", etag=None):117        data = body if isinstance(body, bytes) else body.encode()118        self.send_response(code)119        self.send_header("Content-Type", ctype)120        self.send_header("Content-Length", str(len(data)))121        if etag:122            self.send_header("ETag", etag)123        self.end_headers()124        self.wfile.write(data)125126    def do_GET(self):127        path = self.path128        if MODE == "v2" and path.startswith("/api/v3/"):129            return self.reply(404, "<!DOCTYPE html><html><body>Page introuvable</body></html>", "text/html")130        if MODE == "panne" and path.startswith("/api/v3/proprietes"):131            return self.reply(503, json.dumps({"error": {"code": "engine_unavailable", "message": "Le moteur de valeur est en cours de mise à jour."}}))132        if path.startswith("/api/cost/property"):133            return self.reply(200, (FIXTURES / "cost-prop.json").read_bytes())134        req = urllib.request.Request(PROD + path, headers={"Accept": self.headers.get("Accept", "*/*"), "User-Agent": "VraiPrix-Android-essais"})135        inm = self.headers.get("If-None-Match")136        if inm:137            req.add_header("If-None-Match", inm)138        try:139            with urllib.request.urlopen(req, timeout=30) as r:140                self.reply(r.status, r.read(), r.headers.get("Content-Type", "application/json"), r.headers.get("ETag"))141        except urllib.error.HTTPError as e:142            self.reply(e.code, e.read(), e.headers.get("Content-Type", "application/json"))143        except Exception as e:  # production injoignable144            self.reply(502, json.dumps({"error": str(e)}))145146    def do_POST(self):147        # jamais relayé : seule la méthode du coût (calcul sans enregistrement) est simulée148        length = int(self.headers.get("Content-Length", "0"))149        self.rfile.read(length)150        if self.path.startswith("/api/cost/estimate"):151            return self.reply(200, (FIXTURES / "cost-est.json").read_bytes())152        self.reply(405, json.dumps({"error": "POST non simulé"}))153154    def log_message(self, fmt, *args):155        sys.stderr.write("%s %s\n" % (self.command, self.path))156157158if __name__ == "__main__":159    print(f"service simulé ({MODE}) sur http://127.0.0.1:{PORT}  (émulateur : http://10.0.2.2:{PORT})")160    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()161
Files main
Menu

Theme