Debian Codegraph @

wyoming/http/shared.py

raw ◀ ▶
1 Debian patch touch this file
1 """Shared code for HTTP servers."""
2
3 import argparse
4 from pathlib import Path
5 from typing import Union
6
7 from flask import Flask, jsonify, redirect, request
8
9 from wyoming.client import AsyncClient
10 from wyoming.info import Describe, Info
11
12
13 def get_argument_parser() -> argparse.ArgumentParser:
14 """Create argument parser with shared arguments."""
15 parser = argparse.ArgumentParser()
16 parser.add_argument("--host", default="0.0.0.0")
17 parser.add_argument("--port", type=int, default=5000)
18 parser.add_argument("--uri", help="URI of Wyoming service")
19 parser.add_argument(
20 "--debug", action="store_true", help="Print DEBUG logs to console"
21 )
22 return parser
23
24
25 def get_app(
26 name: str, openapi_config_path: Union[str, Path], args: argparse.Namespace
27 ) -> Flask:
28 """Create Flask app with default endpoints."""
29
30 app = Flask(name)
31
32 @app.route("/")
33 def redirect_to_api():
34 return redirect("/api")
35
36 @app.route("/api/info", methods=["GET"])
37 async def api_info():
38 uri = request.args.get("uri", args.uri)
39 if not uri:
40 raise ValueError("URI is required")
41
42 async with AsyncClient.from_uri(uri) as client:
43 await client.write_event(Describe().event())
44
45 while True:
46 event = await client.read_event()
47 if event is None:
48 raise RuntimeError("Client disconnected")
49
50 if Info.is_type(event.type):
51 info = Info.from_event(event)
52 return jsonify(info.to_dict())
53
54 @app.errorhandler(Exception)
55 async def handle_error(err):
56 """Return error as text."""
57 return (f"{err.__class__.__name__}: {err}", 500)
58
59 return app