Example #1
0
def sync_detailed(
    *,
    client: Client,
    not_null_required: datetime.datetime,
    null_required: Union[Unset, None, datetime.datetime] = UNSET,
    null_not_required: Union[Unset, None, datetime.datetime] = UNSET,
    not_null_not_required: Union[Unset, None, datetime.datetime] = UNSET,
) -> Response[Any]:
    """
    Args:
        not_null_required (datetime.datetime):
        null_required (Union[Unset, None, datetime.datetime]):
        null_not_required (Union[Unset, None, datetime.datetime]):
        not_null_not_required (Union[Unset, None, datetime.datetime]):

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        client=client,
        not_null_required=not_null_required,
        null_required=null_required,
        null_not_required=null_not_required,
        not_null_not_required=not_null_not_required,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #2
0
 def __make_request(
     self,
     method: HttpMethod,
     url: str,
     payload: Dict[str, Any] = None,
     headers: Dict[str, str] = None,
     timeout: int = 5,
 ) -> Result[JsonResponse, DataProviderFailureDetails]:
     _data = orjson.dumps(payload) if payload else None
     try:
         response = httpx.request(
             method=method.value,
             url=url,
             data=_data,
             headers=headers,
             timeout=timeout,
         )
         return self.__validate_response(response)
     except HTTPError as ex:
         return Failure(
             DataProviderFailureDetails(
                 dataprovider_type="REST",
                 reason=ex.__class__.__name__,
                 attributes={"origin": "EXCEPTION", "url": ex.request.url},
             )
         )
Example #3
0
def sync_detailed(
    *,
    client: Client,
    boolean_header: bool,
    string_header: str,
    number_header: float,
    integer_header: int,
) -> Response[Union[PostParametersHeaderResponse200, PublicError]]:
    """
    Args:
        boolean_header (bool):
        string_header (str):
        number_header (float):
        integer_header (int):

    Returns:
        Response[Union[PostParametersHeaderResponse200, PublicError]]
    """

    kwargs = _get_kwargs(
        client=client,
        boolean_header=boolean_header,
        string_header=string_header,
        number_header=number_header,
        integer_header=integer_header,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #4
0
def run(*, port: int):
    port = _find_free_port()
    sentinel = tempfile.mktemp()

    cmd = [
        sys.executable,
        "-m",
        "uvicorn",
        "x00hello:app",
        "--port",
        str(port),
        "--no-use-colors",
    ]
    server_process = subprocess.Popen(cmd, env={"SENTINEL": sentinel})

    # TODO:
    # - headers
    # - cookies
    # - queries
    # - trace (logging)
    # - retry
    # - auth
    # - post JSON
    # - post formData
    with connect_server(server_process, sentinel=sentinel):
        print("----------------------------------------")
        url = f"http://localhost:{port}/"
        res = httpx.request("GET", url, params={"pretty": True})
        print(res, res.text)
        print(res.json())
        print("----------------------------------------")
Example #5
0
def execute(base_url: str, request: Request) -> httpx.Response:
    """Executes a request with the base URL."""
    url = f"{base_url.rstrip('/')}{request.route}"
    return httpx.request(request.method,
                         url,
                         headers=request.headers,
                         json=request.body)
def sync_detailed(
    param_path: str,
    *,
    client: Client,
    param_query: str = "overridden_in_GET",
) -> Response[Any]:
    """Test that if you have an overriding property from `PathItem` in `Operation`, it produces valid code

    Args:
        param_path (str):
        param_query (str): A parameter with the same name as another. Default:
            'overridden_in_GET'. Example: an example string.

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        param_path=param_path,
        client=client,
        param_query=param_query,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #7
0
def sync_detailed(
    *,
    client: Client,
    multipart_data: List[File],
) -> Response[Union[Any, HTTPValidationError]]:
    """Upload multiple files

     Upload several files in the same request

    Args:
        multipart_data (List[File]):

    Returns:
        Response[Union[Any, HTTPValidationError]]
    """

    kwargs = _get_kwargs(
        client=client,
        multipart_data=multipart_data,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #8
0
def sync_detailed(
    *,
    client: Client,
    json_body: str,
) -> Response[Union[HTTPValidationError, str]]:
    """Json Body Which is String

    Args:
        json_body (str):

    Returns:
        Response[Union[HTTPValidationError, str]]
    """

    kwargs = _get_kwargs(
        client=client,
        json_body=json_body,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
def sync_detailed(
    param4: str,
    param2: int,
    param1: str,
    param3: int,
    *,
    client: Client,
) -> Response[Any]:
    """
    Args:
        param4 (str):
        param2 (int):
        param1 (str):
        param3 (int):

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        param4=param4,
        param2=param2,
        param1=param1,
        param3=param3,
        client=client,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #10
0
 def fetch_url(self,
               url,
               params=None,
               headers=None,
               data=None,
               method='GET'):
     """
     公共抓取函数
     :param client:
     :param url:
     :param params:
     :return:
     """
     try:
         response = httpx.request(method=method,
                                  url=url,
                                  params=params,
                                  data=data,
                                  headers=headers,
                                  timeout=60,
                                  allow_redirects=True)
         assert response.status_code == 200
         content = response.content
         charset = cchardet.detect(content)
         html_doc = content.decode(charset['encoding'])
         return html_doc
     except Exception as e:
         return None
Example #11
0
def sync_detailed(
    *,
    client: Client,
    json_body: TestInlineObjectsJsonBody,
) -> Response[TestInlineObjectsResponse200]:
    """Test Inline Objects

    Args:
        json_body (TestInlineObjectsJsonBody):

    Returns:
        Response[TestInlineObjectsResponse200]
    """

    kwargs = _get_kwargs(
        client=client,
        json_body=json_body,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
def sync_detailed(
    param_path: str,
    *,
    client: Client,
    param_query: Union[Unset, None, str] = UNSET,
) -> Response[Any]:
    """
    Args:
        param_path (str):
        param_query (Union[Unset, None, str]):

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        param_path=param_path,
        client=client,
        param_query=param_query,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #13
0
def get_artifact(*,
                 client: Client,
                 project_key: str,
                 artifact_name: str,
                 artifact_version: Optional[int],
                 model_stage: str = None) -> ArtifactDto:
    version = artifact_version if artifact_version is not None else "latest"

    url = "{}/projects/{projectKey}/artifacts/{artifactName}/{artifactVersion}" \
        .format(client.base_url, projectKey=project_key, artifactName=artifact_name, artifactVersion=version)

    query_params = None if model_stage is None else {
        "model-stage": model_stage
    }

    headers: Dict[str, Any] = client.get_headers()

    response = httpx.request(method="GET",
                             url=url,
                             headers=headers,
                             params=query_params)

    assert_response_status(response)

    return ArtifactDto.from_dict(cast(Dict[str, Any], response.json()))
def sync_detailed(
    *,
    client: Client,
    boolean_header: Union[Unset, bool] = UNSET,
    string_header: Union[Unset, str] = UNSET,
    number_header: Union[Unset, float] = UNSET,
    integer_header: Union[Unset, int] = UNSET,
) -> Response[Any]:
    """
    Args:
        boolean_header (Union[Unset, bool]):
        string_header (Union[Unset, str]):
        number_header (Union[Unset, float]):
        integer_header (Union[Unset, int]):

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        client=client,
        boolean_header=boolean_header,
        string_header=string_header,
        number_header=number_header,
        integer_header=integer_header,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
def sync_detailed(
    *,
    client: Client,
    int_enum: AnIntEnum,
) -> Response[Union[Any, HTTPValidationError]]:
    """Int Enum

    Args:
        int_enum (AnIntEnum): An enumeration.

    Returns:
        Response[Union[Any, HTTPValidationError]]
    """

    kwargs = _get_kwargs(
        client=client,
        int_enum=int_enum,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #16
0
def _at_api_request(url, method='GET', headers=HEADERS, **kwargs):
    response = httpx.request(method,
                             AT_API_URL + url,
                             headers=HEADERS,
                             **kwargs)
    response.raise_for_status()
    return response.json().get('response')
def sync_detailed(
    *,
    client: Client,
    json_body: AModel,
) -> Response[Union[Any, HTTPValidationError]]:
    """Json Body

     Try sending a JSON body

    Args:
        json_body (AModel): A Model for testing all the ways custom objects can be used

    Returns:
        Response[Union[Any, HTTPValidationError]]
    """

    kwargs = _get_kwargs(
        client=client,
        json_body=json_body,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #18
0
def sync_detailed(
    *,
    client: Client,
    multipart_data: BodyUploadFileTestsUploadPost,
) -> Response[Union[Any, HTTPValidationError]]:
    """Upload File

     Upload a file

    Args:
        multipart_data (BodyUploadFileTestsUploadPost):

    Returns:
        Response[Union[Any, HTTPValidationError]]
    """

    kwargs = _get_kwargs(
        client=client,
        multipart_data=multipart_data,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
def sync_detailed(
    *,
    client: Client,
    my_token: str,
) -> Response[Any]:
    """TOKEN_WITH_COOKIE

     Test optional cookie parameters

    Args:
        my_token (str):

    Returns:
        Response[Any]
    """

    kwargs = _get_kwargs(
        client=client,
        my_token=my_token,
    )

    response = httpx.request(
        verify=client.verify_ssl,
        **kwargs,
    )

    return _build_response(response=response)
Example #20
0
    def _request(self, method: str, url: str, json: dict = None) -> dict:
        url = url.strip('/')
        url = urljoin(self.host, url)

        params = {
            'method': method,
            'url': url,
            'headers': {
                **self.headers,
                'X-auth-TOKEN': self.token,
            },
            'timeout': self.timeout,
        }

        if json:
            params['json'] = json

        response = httpx.request(**params)

        if response.status_code != 200:
            raise HTTPException(
                f'Non-200 response when fetching url {url}: {response.status_code}'
            )

        return response.json()
Example #21
0
def basic_auth_request(method: str,
                       url: str,
                       token: str = None,
                       payload: Dict[str, Any] = None,
                       params: Dict[str, Any] = None) -> OneSignalResponse:
    """Make a request using basic authorization."""
    request_kwargs = _build_request_kwargs(token, payload, params)
    return _handle_response(httpx.request(method, url, **request_kwargs))
Example #22
0
def basic_auth_request(method: str,
                       url: str,
                       token: str = None,
                       platform: SubscriptionPlatform = None,
                       payload: Dict[str, Any] = None,
                       params: Dict[str, Any] = None) -> RevenueCatResponse:
    response = httpx.request(
        method, url, **_build_request(token, platform, payload, params))

    return _handle_response(response)
Example #23
0
 async def __on_room_change(self, command):
     group_list = api.group
     for group in group_list:
         r = httpx.request(
             'POST',
             api.url,
             json={
                 'key': api.key,
                 'message':
                 F"{BLive.runame}的直播间改标题啦:{command['data']['title']}",
                 'qid': group,
                 'message_type': 'group'
             })
Example #24
0
def create_model(*, client: Client, project_key: str, artifact_name: str,
                 artifact_version: int) -> None:
    url = "{}/projects/{projectKey}/artifacts/{artifactName}/{artifactVersion}/model"\
        .format(client.base_url, projectKey=project_key, artifactName=artifact_name, artifactVersion=artifact_version)

    headers: Dict[str, Any] = client.get_headers()

    response = httpx.request(
        method="PUT",
        url=url,
        headers=headers,
    )

    assert_response_status(response)
Example #25
0
def create_artifact(*, client: Client, project_key: str,
                    artifact: ArtifactDto) -> ArtifactDto:
    url = "{}/projects/{projectKey}/artifacts"\
        .format(client.base_url, projectKey=project_key)

    headers: Dict[str, Any] = client.get_headers()

    response = httpx.request(method="POST",
                             url=url,
                             headers=headers,
                             json=artifact.to_dict_without_none_values())

    assert_response_status(response)

    return ArtifactDto.from_dict(response.json())
Example #26
0
def upload_file(*, client: Client, project_key: str, artifact_name: str,
                artifact_version: int, filename: str, file: io.BytesIO):
    url = "{}/projects/{projectKey}/artifacts/{artifactName}/{artifactVersion}/files"\
        .format(client.base_url, projectKey=project_key, artifactName=artifact_name, artifactVersion=artifact_version)

    headers: Dict[str, Any] = client.get_headers()

    files = {'file': (filename, file)}

    response = httpx.request(method="POST",
                             url=url,
                             headers=headers,
                             files=files)

    assert_response_status(response)
Example #27
0
    def make_request(self,
                     method: str,
                     url: str,
                     headers: dict = None,
                     payload: dict = None) -> typing.Optional[dict]:
        if headers:
            self.headers.update(headers)

        try:
            response = httpx.request(method.lower(),
                                     url,
                                     headers=self.headers,
                                     data=payload)
            return response.json()
        except (httpx.RequestError, json.JSONDecodeError, AttributeError):
            raise HTTPRequestError
Example #28
0
def find_in_aur(pkg: str, qby: str = "name-desc") -> Dict:
    if qby not in [
        "name",
        "name-desc",
        "maintainer",
        "depends",
        "makedepends",
        "optdepends",
        "checkdepends",
    ]:
        raise Exception(
            "Unsupported keyword. See supported keywords at https://wiki.archlinux.org/index.php/Aurweb_RPC_interface#search "
        )
    querystring = {"v": "5", "type": "search", "by": qby, "arg": pkg}
    response = httpx.request(method="GET", url=AUR_URL, params=querystring)
    return response.json()
Example #29
0
def packagefiles(repo: str, arch: str, name: str) -> Dict:
    if repo not in [
            "Core",
            "Extra",
            "Testing",
            "Multilib",
            "Multilib-Testing",
            "Community",
            "Community-Testing",
    ]:
        raise Exception("Repository not available in Arch Linux!")
    if arch not in ["any", "i686", "x86_64"]:
        raise Exception("Architecture not available in Arch Linux!")
    url = f"https://www.archlinux.org/packages/{repo}/{arch}/{name}/files/json"
    response = httpx.request("GET", url)
    return response.json()
Example #30
0
def download_artifact(*, client: Client, project_key: str, artifact_name: str,
                      artifact_version: int) -> Tuple[io.BytesIO, str]:

    url = "{}/projects/{projectKey}/artifacts/{artifactName}/{artifactVersion}/files" \
        .format(client.base_url, projectKey=project_key, artifactName=artifact_name, artifactVersion=artifact_version)

    headers: Dict[str, Any] = client.get_headers()
    headers["Accepts"] = "application/zip"

    response = httpx.request(method="GET", url=url, headers=headers)

    assert_response_status(response)

    content_disposition = response.headers.get("Content-Disposition")
    value, params = cgi.parse_header(content_disposition)
    filename = params.get("filename")
    return io.BytesIO(response.content), filename