Debian Codegraph @

wyoming/http/shared.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 from swagger_ui import flask_api_doc # pylint: disable=no-name-in-module
9
10 from wyoming.client import AsyncClient
11 from wyoming.info import Describe, Info
12
13
14 def get_argument_parser() -> argparse.ArgumentParser:
15 """Create argument parser with shared arguments."""
16 parser = argparse.ArgumentParser()
17 parser.add_argument("--host", default="0.0.0.0")
18 parser.add_argument("--port", type=int, default=5000)
19 parser.add_argument("--uri", help="URI of Wyoming service")
20 parser.add_argument(
21 "--debug", action="store_true", help="Print DEBUG logs to console"
22 )
23 return parser
24
25
26 def get_app(
27 name: str, openapi_config_path: Union[str, Path], args: argparse.Namespace
28 ) -> Flask:
29 """Create Flask app with default endpoints."""
30
31 app = Flask(name)
32
33 @app.route("/")
34 def redirect_to_api():
35 return redirect("/api")
36
37 @app.route("/api/info", methods=["GET"])
38 async def api_info():
39 uri = request.args.get("uri", args.uri)
40 if not uri:
41 raise ValueError("URI is required")
42
43 async with AsyncClient.from_uri(uri) as client:
44 await client.write_event(Describe().event())
45
46 while True:
47 event = await client.read_event()
48 if event is None:
49 raise RuntimeError("Client disconnected")
50
51 if Info.is_type(event.type):
52 info = Info.from_event(event)
53 return jsonify(info.to_dict())
54
55 @app.errorhandler(Exception)
56 async def handle_error(err):
57 """Return error as text."""
58 return (f"{err.__class__.__name__}: {err}", 500)
59
60 flask_api_doc(
61 app, config_path=str(openapi_config_path), url_prefix="/api", title="API doc"
62 )
63
64 return app