|
| 1 | +"""This module implements the generation of connector configuration files.""" |
| 2 | + |
| 3 | +from dataprep.connector.schema.base import BaseDef |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any, Dict, Optional, Union |
| 6 | +from urllib.parse import parse_qs, urlparse, urlunparse |
| 7 | + |
| 8 | +import requests |
| 9 | + |
| 10 | +from ..schema import ( |
| 11 | + AuthorizationDef, |
| 12 | + ConfigDef, |
| 13 | + PaginationDef, |
| 14 | +) |
| 15 | +from .state import ConfigState |
| 16 | +from .table import gen_schema_from_path, search_table_path |
| 17 | + |
| 18 | +# class Example(TypedDict): |
| 19 | +# url: str |
| 20 | +# method: str |
| 21 | +# params: Dict[str, str] |
| 22 | +# authorization: Tuple[Dict[str, Any], Dict[str, Any]] |
| 23 | +# pagination: Dict[str, Any] |
| 24 | + |
| 25 | + |
| 26 | +class ConfigGenerator: |
| 27 | + """Config Generator. |
| 28 | +
|
| 29 | + Parameters |
| 30 | + ---------- |
| 31 | + config |
| 32 | + Initialize the config generator with existing config file. |
| 33 | +
|
| 34 | + """ |
| 35 | + |
| 36 | + config: ConfigState |
| 37 | + storage: Dict[str, Any] # for auth usage |
| 38 | + |
| 39 | + def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: |
| 40 | + if config is None: |
| 41 | + self.config = ConfigState(None) |
| 42 | + else: |
| 43 | + self.config = ConfigState(ConfigDef(**config)) |
| 44 | + self.storage = {} |
| 45 | + |
| 46 | + def add_example( |
| 47 | + self, example: Dict[str, Any] |
| 48 | + ) -> None: # pylint: disable=too-many-locals |
| 49 | + """Add an example to the generator. The example |
| 50 | + should be in the dictionary format. |
| 51 | +
|
| 52 | + class Example(TypedDict): |
| 53 | + url: str |
| 54 | + method: str |
| 55 | + params: Dict[str, str] |
| 56 | + # 0 for def and 1 for params |
| 57 | + authorization: Optional[Tuple[Dict[str, Any], Dict[str, Any]]] |
| 58 | + pagination: Optional[Dict[str, Any]] |
| 59 | +
|
| 60 | + Parameters |
| 61 | + ---------- |
| 62 | + req_example |
| 63 | + The request example. |
| 64 | + """ |
| 65 | + url = example["url"] |
| 66 | + method = example["method"] |
| 67 | + if method not in {"POST", "GET", "PUT"}: |
| 68 | + raise ValueError(f"{method} not allowed.") |
| 69 | + if method != "GET": |
| 70 | + raise NotImplementedError(f"{method} not implemented.") |
| 71 | + |
| 72 | + params = example.get("params", {}) |
| 73 | + |
| 74 | + # Move url params to params |
| 75 | + parsed = urlparse(url) |
| 76 | + |
| 77 | + query_string = parse_qs(parsed.query) |
| 78 | + for key, (val, *_) in query_string.items(): |
| 79 | + if key in params and params[key] != val: |
| 80 | + raise ValueError( |
| 81 | + f"{key} appears in both url and params, but have different values." |
| 82 | + ) |
| 83 | + params[key] = val |
| 84 | + |
| 85 | + url = urlunparse((*parsed[:4], "", *parsed[5:])) |
| 86 | + req = { |
| 87 | + "method": method, |
| 88 | + "url": url, |
| 89 | + "headers": {}, |
| 90 | + "params": params, |
| 91 | + } |
| 92 | + |
| 93 | + # Parse authorization and build authorization into request |
| 94 | + authdef: Optional[AuthorizationDef] = None |
| 95 | + authparams: Optional[Dict[str, Any]] = None |
| 96 | + if example.get("authorization") is not None: |
| 97 | + authorization, authparams = example["authorization"] |
| 98 | + authdef = AuthUnion(val=authorization).val |
| 99 | + |
| 100 | + if authdef is not None and authparams is not None: |
| 101 | + authdef.build(req, authparams, self.storage) |
| 102 | + |
| 103 | + # Send out request and construct config |
| 104 | + config = _create_config(req) |
| 105 | + |
| 106 | + # Add pagination information into the config |
| 107 | + pagination = example.get("pagination") |
| 108 | + if pagination is not None: |
| 109 | + pagdef = PageUnion(val=pagination).val |
| 110 | + config.request.pagination = pagdef |
| 111 | + |
| 112 | + self.config += config |
| 113 | + |
| 114 | + def to_string(self) -> str: |
| 115 | + """Output the string format of the current config.""" |
| 116 | + return str(self.config) |
| 117 | + |
| 118 | + def save(self, path: Union[str, Path]) -> None: |
| 119 | + """Save the current config to a file. |
| 120 | +
|
| 121 | + Parameters |
| 122 | + ---------- |
| 123 | + path |
| 124 | + The path to the saved file, with the file extension. |
| 125 | + """ |
| 126 | + path = Path(path) |
| 127 | + |
| 128 | + with open(path, "w") as f: |
| 129 | + f.write(self.to_string()) |
| 130 | + |
| 131 | + |
| 132 | +def _create_config(req: Dict[str, Any]) -> ConfigDef: |
| 133 | + resp = requests.request( |
| 134 | + req["method"].lower(), req["url"], params=req["params"], headers=req["headers"], |
| 135 | + ) |
| 136 | + |
| 137 | + if resp.status_code != 200: |
| 138 | + raise RuntimeError( |
| 139 | + f"Request to HTTP endpoint not successful: {resp.status_code}: {resp.text}" |
| 140 | + ) |
| 141 | + payload = resp.json() |
| 142 | + |
| 143 | + table_path = search_table_path(payload) |
| 144 | + |
| 145 | + ret: Dict[str, Any] = { |
| 146 | + "version": 1, |
| 147 | + "request": { |
| 148 | + "url": req["url"], |
| 149 | + "method": req["method"], |
| 150 | + "params": {key: False for key in req["params"]}, |
| 151 | + }, |
| 152 | + "response": { |
| 153 | + "ctype": "application/json", |
| 154 | + "orient": "records", |
| 155 | + "tablePath": table_path, |
| 156 | + "schema": gen_schema_from_path(table_path, payload), |
| 157 | + }, |
| 158 | + } |
| 159 | + |
| 160 | + return ConfigDef(**ret) |
| 161 | + |
| 162 | + |
| 163 | +class AuthUnion(BaseDef): |
| 164 | + val: AuthorizationDef |
| 165 | + |
| 166 | + |
| 167 | +class PageUnion(BaseDef): |
| 168 | + val: PaginationDef |
0 commit comments