Python httpx.AsyncClient() Examples

The following are 30 code examples of httpx.AsyncClient(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module httpx , or try the search function .
Example #1
Source File: client.py    From Audible with GNU Affero General Public License v3.0 9 votes vote down vote up
def __init__(self, auth: Optional[Union[LoginAuthenticator, FileAuthenticator]] = None,
                 session=None, is_async=False, **options) -> None:
        self.auth = auth

        self.is_async = is_async
        self.session = (session or (httpx.AsyncClient() if is_async
                        else httpx.Client()))
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        self.session.headers.update(headers)

        locale = test_convert("locale", options.get("locale", auth.locale))
        domain = options.get("domain", locale.domain)
        self.api_root_url = options.get("url", f"https://api.audible.{domain}")

        self.timeout = options.get('timeout', 10) 
Example #2
Source File: test_profiles.py    From fastapi-realworld-example-app with MIT License 7 votes vote down vote up
def test_user_that_follows_another_will_receive_profile_with_follow(
    app: FastAPI, authorized_client: AsyncClient, pool: Pool, test_user: UserInDB
) -> None:
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        user = await users_repo.create_user(
            username="user_for_following",
            email="test-for-following@email.com",
            password="password",
        )

        profiles_repo = ProfilesRepository(conn)
        await profiles_repo.add_user_into_followers(
            target_user=user, requested_user=test_user
        )

    response = await authorized_client.get(
        app.url_path_for("profiles:get-profile", username=user.username)
    )
    profile = ProfileInResponse(**response.json())
    assert profile.profile.username == user.username
    assert profile.profile.following 
Example #3
Source File: abc.py    From aiochclient with MIT License 6 votes vote down vote up
def choose_http_client(session):
        try:
            import aiohttp

            if session is None or isinstance(session, aiohttp.ClientSession):
                from aiochclient.http_clients.aiohttp import AiohttpHttpClient

                return AiohttpHttpClient
        except ImportError:
            pass
        try:
            import httpx

            if session is None or isinstance(session, httpx.AsyncClient):
                from aiochclient.http_clients.httpx import HttpxHttpClient

                return HttpxHttpClient
        except ImportError:
            pass
        raise ChClientError('Async http client heeded. Please install aiohttp or httpx') 
Example #4
Source File: test_profiles.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_that_does_not_follows_another_will_receive_profile_without_follow(
    app: FastAPI, authorized_client: AsyncClient, pool: Pool
) -> None:
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        user = await users_repo.create_user(
            username="user_for_following",
            email="test-for-following@email.com",
            password="password",
        )

    response = await authorized_client.get(
        app.url_path_for("profiles:get-profile", username=user.username)
    )
    profile = ProfileInResponse(**response.json())
    assert profile.profile.username == user.username
    assert not profile.profile.following 
Example #5
Source File: test_users.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_update_own_profile(
    app: FastAPI,
    authorized_client: AsyncClient,
    test_user: UserInDB,
    token: str,
    update_value: str,
    update_field: str,
) -> None:
    response = await authorized_client.put(
        app.url_path_for("users:update-current-user"),
        json={"user": {update_field: update_value}},
    )
    assert response.status_code == status.HTTP_200_OK

    user_profile = UserInResponse(**response.json()).dict()
    assert user_profile["user"][update_field] == update_value 
Example #6
Source File: test_users.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_change_password(
    app: FastAPI,
    authorized_client: AsyncClient,
    test_user: UserInDB,
    token: str,
    pool: Pool,
) -> None:
    response = await authorized_client.put(
        app.url_path_for("users:update-current-user"),
        json={"user": {"password": "new_password"}},
    )
    assert response.status_code == status.HTTP_200_OK
    user_profile = UserInResponse(**response.json())

    async with pool.acquire() as connection:
        users_repo = UsersRepository(connection)
        user = await users_repo.get_user_by_username(
            username=user_profile.user.username
        )

    assert user.check_password("new_password") 
Example #7
Source File: test_users.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_not_take_already_used_credentials(
    app: FastAPI,
    authorized_client: AsyncClient,
    pool: Pool,
    token: str,
    credentials_part: str,
    credentials_value: str,
) -> None:
    user_dict = {
        "username": "not_taken_username",
        "password": "password",
        "email": "free_email@email.com",
    }
    user_dict.update({credentials_part: credentials_value})
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        await users_repo.create_user(**user_dict)

    response = await authorized_client.put(
        app.url_path_for("users:update-current-user"),
        json={"user": {credentials_part: credentials_value}},
    )
    assert response.status_code == status.HTTP_400_BAD_REQUEST 
Example #8
Source File: test_comments.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_add_comment_for_article(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article
) -> None:
    created_comment_response = await authorized_client.post(
        app.url_path_for("comments:create-comment-for-article", slug=test_article.slug),
        json={"comment": {"body": "comment"}},
    )

    created_comment = CommentInResponse(**created_comment_response.json())

    comments_for_article_response = await authorized_client.get(
        app.url_path_for("comments:get-comments-for-article", slug=test_article.slug)
    )

    comments = ListOfCommentsInResponse(**comments_for_article_response.json())

    assert created_comment.comment == comments.comments[0] 
Example #9
Source File: test_comments.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_delete_own_comment(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article
) -> None:
    created_comment_response = await authorized_client.post(
        app.url_path_for("comments:create-comment-for-article", slug=test_article.slug),
        json={"comment": {"body": "comment"}},
    )

    created_comment = CommentInResponse(**created_comment_response.json())

    await authorized_client.delete(
        app.url_path_for(
            "comments:delete-comment-from-article",
            slug=test_article.slug,
            comment_id=str(created_comment.comment.id_),
        )
    )

    comments_for_article_response = await authorized_client.get(
        app.url_path_for("comments:get-comments-for-article", slug=test_article.slug)
    )

    comments = ListOfCommentsInResponse(**comments_for_article_response.json())

    assert len(comments.comments) == 0 
Example #10
Source File: api_impl.py    From aiocqhttp with MIT License 6 votes vote down vote up
def call_action(self, action: str, **params) -> Any:
        if not self._api_root:
            raise ApiNotAvailable

        headers = {}
        if self._access_token:
            headers['Authorization'] = 'Bearer ' + self._access_token

        try:
            async with httpx.AsyncClient() as client:
                resp = await client.post(self._api_root + action,
                                         json=params, headers=headers)
            if 200 <= resp.status_code < 300:
                return _handle_api_result(json.loads(resp.text))
            raise HttpFailed(resp.status_code)
        except httpx.InvalidURL:
            raise NetworkError('API root url invalid')
        except httpx.HTTPError:
            raise NetworkError('HTTP request failed') 
Example #11
Source File: service.py    From avwx-engine with MIT License 6 votes vote down vote up
def async_fetch(
        self,
        station: str = None,
        lat: float = None,
        lon: float = None,
        timeout: int = 10,
    ) -> str:
        """
        Asynchronously fetch a report string from the service
        """
        if station:
            valid_station(station)
        elif lat is None or lon is None:
            raise ValueError("No valid fetch parameters")
        url, params = self._make_url(station, lat, lon)
        try:
            async with httpx.AsyncClient(timeout=timeout) as client:
                if self.method.lower() == "post":
                    resp = await client.post(
                        url, params=params, data=self._post_data(station)
                    )
                else:
                    resp = await client.get(url, params=params)
                if resp.status_code != 200:
                    raise SourceError(
                        f"{self.__class__.__name__} server returned {resp.status_code}"
                    )
        except (httpx.ConnectTimeout, httpx.ReadTimeout):
            raise TimeoutError(f"Timeout from {self.__class__.__name__} server")
        except gaierror:
            raise ConnectionError(
                f"Unable to connect to {self.__class__.__name__} server"
            )
        report = self._extract(resp.text, station)
        return self._clean_report(report)


# Multiple sources for NOAA data 
Example #12
Source File: httpx_vcr_stubs.py    From mergify-engine with Apache License 2.0 6 votes vote down vote up
def monkeypatch():
    @CassettePatcherBuilder._build_patchers_from_mock_triples_decorator
    def _async_httpx(self):
        new_async_client_send = async_vcr_send(self._cassette, httpx.AsyncClient.send)
        yield httpx.AsyncClient, "send", new_async_client_send

    @CassettePatcherBuilder._build_patchers_from_mock_triples_decorator
    def _sync_httpx(self):
        new_sync_client_send = sync_vcr_send(self._cassette, httpx.Client.send)
        yield httpx.Client, "send", new_sync_client_send

    real_build = CassettePatcherBuilder.build

    def patched_build(self):
        return itertools.chain(real_build(self), _sync_httpx(self), _async_httpx(self))

    CassettePatcherBuilder.build = patched_build 
Example #13
Source File: test_registration.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_success_registration(
    app: FastAPI, client: AsyncClient, pool: Pool
) -> None:
    email, username, password = "test@test.com", "username", "password"
    registration_json = {
        "user": {"email": email, "username": username, "password": password}
    }
    response = await client.post(
        app.url_path_for("auth:register"), json=registration_json
    )
    assert response.status_code == HTTP_201_CREATED

    async with pool.acquire() as conn:
        repo = UsersRepository(conn)
        user = await repo.get_user_by_email(email=email)
        assert user.email == email
        assert user.username == username
        assert user.check_password(password) 
Example #14
Source File: maths.py    From cyberdisc-bot with MIT License 6 votes vote down vote up
def get_challenges(
    client: httpx.AsyncClient, page_index: int = 0, page_size: int = 999
):
    """Get challenges, given the relevant parameters."""
    return (
        await client.post(
            constants.Challenges.URL,
            headers=dict(accessToken=constants.Challenges.TOKEN),
            json={
                "pageIndex": page_index,
                "pageSize": page_size,
                "orderBy": [{"desc": "answerDate"}],
                "where": [
                    {"field": "sys.versionStatus", "equalTo": "published"},
                    {"field": "sys.contentTypeId", "in": ["mathsQuiz"]},
                ],
                "fields": ["entryTitle", "category", "sys", "description", "answer"],
            },
        )
    ).json()["items"] 
Example #15
Source File: test_router_oauth.py    From fastapi-users with MIT License 6 votes vote down vote up
def test_success(self, test_app_client: httpx.AsyncClient, oauth_client):
        with asynctest.patch.object(oauth_client, "get_authorization_url") as mock:
            mock.return_value = "AUTHORIZATION_URL"
            response = await test_app_client.get(
                "/authorize",
                params={
                    "authentication_backend": "mock",
                    "scopes": ["scope1", "scope2"],
                },
            )

        assert response.status_code == status.HTTP_200_OK
        mock.assert_awaited_once()

        data = response.json()
        assert "authorization_url" in data 
Example #16
Source File: test_router_oauth.py    From fastapi-users with MIT License 6 votes vote down vote up
def test_with_redirect_url(
        self, test_app_client_redirect_url: httpx.AsyncClient, oauth_client
    ):
        with asynctest.patch.object(oauth_client, "get_authorization_url") as mock:
            mock.return_value = "AUTHORIZATION_URL"
            response = await test_app_client_redirect_url.get(
                "/authorize",
                params={
                    "authentication_backend": "mock",
                    "scopes": ["scope1", "scope2"],
                },
            )

        assert response.status_code == status.HTTP_200_OK
        mock.assert_awaited_once()

        data = response.json()
        assert "authorization_url" in data 
Example #17
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_user_can_not_change_article_state_twice(
    app: FastAPI,
    authorized_client: AsyncClient,
    test_article: Article,
    test_user: UserInDB,
    pool: Pool,
    api_method: str,
    route_name: str,
    favorite_state: bool,
) -> None:
    if favorite_state:
        async with pool.acquire() as connection:
            articles_repo = ArticlesRepository(connection)
            await articles_repo.add_article_into_favorites(
                article=test_article, user=test_user
            )

    response = await authorized_client.request(
        api_method, app.url_path_for(route_name, slug=test_article.slug)
    )

    assert response.status_code == status.HTTP_400_BAD_REQUEST 
Example #18
Source File: test_registration.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
def test_failed_user_registration_when_some_credentials_are_taken(
    app: FastAPI,
    client: AsyncClient,
    test_user: UserInDB,
    credentials_part: str,
    credentials_value: str,
) -> None:
    registration_json = {
        "user": {
            "email": "test@test.com",
            "username": "username",
            "password": "password",
        }
    }
    registration_json["user"][credentials_part] = credentials_value

    response = await client.post(
        app.url_path_for("auth:register"), json=registration_json
    )
    assert response.status_code == HTTP_400_BAD_REQUEST 
Example #19
Source File: test_unix_socket.py    From sanic with MIT License 6 votes vote down vote up
def test_unix_connection():
    app = Sanic(name=__name__)

    @app.get("/")
    def handler(request):
        return text(f"{request.conn_info.server}")

    @app.listener("after_server_start")
    async def client(app, loop):
        try:
            async with httpx.AsyncClient(uds=SOCKPATH) as client:
                r = await client.get("http://myhost.invalid/")
                assert r.status_code == 200
                assert r.text == os.path.abspath(SOCKPATH)
        finally:
            app.stop()

    app.run(host="myhost.invalid", unix=SOCKPATH) 
Example #20
Source File: maths.py    From cyberdisc-bot with MIT License 6 votes vote down vote up
def update_challenge(self):
        """Check the Kings site for the latest challenges."""
        print("Updating maths challenges...")
        latest_challenge = float("inf")
        latest_challenge = int(
            self.channel.topic.split("Nerds, the lot of you | Challenge ")[1].split(
                " "
            )[0][:-1]
        )
        async with httpx.AsyncClient() as client:
            challenges = await get_challenges(client)
        for number, challenge in enumerate(challenges[::-1], 1):
            title = challenge["entryTitle"]
            if number > latest_challenge:
                await self.challenge(self.channel, len(challenges) - number + 1)
                await self.channel.edit(topic=constants.Challenges.TOPIC.format(title))
        print("Maths challenges successfully updated.") 
Example #21
Source File: test_router_oauth.py    From fastapi-users with MIT License 5 votes vote down vote up
def get_test_app_client(
    mock_user_db_oauth,
    mock_authentication,
    oauth_client,
    after_register,
    get_test_client,
):
    async def _get_test_app_client(redirect_url: str = None) -> httpx.AsyncClient:
        mock_authentication_bis = MockAuthentication(name="mock-bis")
        authenticator = Authenticator(
            [mock_authentication, mock_authentication_bis], mock_user_db_oauth
        )

        oauth_router = get_oauth_router(
            oauth_client,
            mock_user_db_oauth,
            UserDB,
            authenticator,
            SECRET,
            redirect_url,
            after_register,
        )

        app = FastAPI()
        app.include_router(oauth_router)

        return await get_test_client(app)

    return _get_test_app_client 
Example #22
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_user_can_not_modify_article_that_is_not_authored_by_him(
    app: FastAPI,
    authorized_client: AsyncClient,
    pool: Pool,
    api_method: str,
    route_name: str,
) -> None:
    async with pool.acquire() as connection:
        users_repo = UsersRepository(connection)
        user = await users_repo.create_user(
            username="test_author", email="author@email.com", password="password"
        )
        articles_repo = ArticlesRepository(connection)
        await articles_repo.create_article(
            slug="test-slug",
            title="Test Slug",
            description="Slug for tests",
            body="Test " * 100,
            author=user,
            tags=["tests", "testing", "pytest"],
        )

    response = await authorized_client.request(
        api_method,
        app.url_path_for(route_name, slug="test-slug"),
        json={"article": {"title": "Updated Title"}},
    )
    assert response.status_code == status.HTTP_403_FORBIDDEN 
Example #23
Source File: transport.py    From linepy-modified with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open(self):
        if self.request == 'hyper':
            if self.http2:
                self.__http = hyper.HTTP20Connection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
            else:
                self.__http = hyper.HTTPConnection(self.host, self.port, proxy_host=self.realhost, proxy_port=self.realport, proxy_headers=self.proxy_headers)
        elif self.request == 'httpx':
            if self.http2:
                self.__http = httpx.AsyncClient(base_url='%s://%s' % (self.scheme, self.host), http2=self.http2)
            else:
                self.__http = httpx.Client(base_url='%s://%s' % (self.scheme, self.host))
        elif self.request == 'requests':
            self.__http = requests.Session()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'requests-futures':
            self.__http = FuturesSession()
            if self.using_proxy():
                self.__http.proxies = urllib.request.getproxies()
        elif self.request == 'httplib2':
            self.__http = httplib2.Http()
        else:
            if self.scheme == 'http':
                self.__http = http_client.HTTPConnection(self.host, self.port)
            elif self.scheme == 'https':
                self.__http = http_client.HTTPSConnection(self.host, self.port)
                if self.using_proxy():
                    self.__http.set_tunnel(self.realhost, self.realport, self.proxy_headers) 
Example #24
Source File: conftest.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def authorized_client(
    client: AsyncClient, token: str, authorization_prefix: str
) -> AsyncClient:
    client.headers = {
        "Authorization": f"{authorization_prefix} {token}",
        **client.headers,
    }
    return client 
Example #25
Source File: conftest.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def client(initialized_app: FastAPI) -> AsyncClient:
    async with AsyncClient(
        app=initialized_app,
        base_url="http://testserver",
        headers={"Content-Type": "application/json"},
    ) as client:
        yield client 
Example #26
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_filtering_with_limit_and_offset(
    app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB, pool: Pool
) -> None:
    async with pool.acquire() as connection:
        articles_repo = ArticlesRepository(connection)

        for i in range(5, 10):
            await articles_repo.create_article(
                slug=f"slug-{i}",
                title="tmp",
                description="tmp",
                body="tmp",
                author=test_user,
            )

    full_response = await authorized_client.get(
        app.url_path_for("articles:list-articles")
    )
    full_articles = ListOfArticlesInResponse(**full_response.json())

    response = await authorized_client.get(
        app.url_path_for("articles:list-articles"), params={"limit": 2, "offset": 3}
    )

    articles_from_response = ListOfArticlesInResponse(**response.json())
    assert full_articles.articles[3:] == articles_from_response.articles 
Example #27
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_article_will_contain_only_attached_tags(
    app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB, pool: Pool
) -> None:
    attached_tags = ["tag1", "tag3"]

    async with pool.acquire() as connection:
        articles_repo = ArticlesRepository(connection)

        await articles_repo.create_article(
            slug=f"test-slug",
            title="tmp",
            description="tmp",
            body="tmp",
            author=test_user,
            tags=attached_tags,
        )

        for i in range(5):
            await articles_repo.create_article(
                slug=f"slug-{i}",
                title="tmp",
                description="tmp",
                body="tmp",
                author=test_user,
                tags=[f"tag-{i}"],
            )

    response = await authorized_client.get(
        app.url_path_for("articles:get-article", slug="test-slug")
    )
    article = ArticleInResponse(**response.json())
    assert len(article.article.tags) == len(attached_tags)
    assert set(article.article.tags) == set(attached_tags) 
Example #28
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_empty_feed_if_user_has_not_followings(
    app: FastAPI,
    authorized_client: AsyncClient,
    test_article: Article,
    test_user: UserInDB,
    pool: Pool,
) -> None:
    async with pool.acquire() as connection:
        users_repo = UsersRepository(connection)
        articles_repo = ArticlesRepository(connection)

        for i in range(5):
            user = await users_repo.create_user(
                username=f"user-{i}", email=f"user-{i}@email.com", password="password"
            )
            for j in range(5):
                await articles_repo.create_article(
                    slug=f"slug-{i}-{j}",
                    title="tmp",
                    description="tmp",
                    body="tmp",
                    author=user,
                    tags=[f"tag-{i}-{j}"],
                )

    response = await authorized_client.get(
        app.url_path_for("articles:get-user-feed-articles")
    )

    articles = ListOfArticlesInResponse(**response.json())
    assert articles.articles == [] 
Example #29
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_user_can_delete_his_article(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article, pool: Pool,
) -> None:
    await authorized_client.delete(
        app.url_path_for("articles:delete-article", slug=test_article.slug)
    )

    async with pool.acquire() as connection:
        articles_repo = ArticlesRepository(connection)
        with pytest.raises(EntityDoesNotExist):
            await articles_repo.get_article_by_slug(slug=test_article.slug) 
Example #30
Source File: test_articles.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def test_user_can_create_article(
    app: FastAPI, authorized_client: AsyncClient, test_user: UserInDB
) -> None:
    article_data = {
        "title": "Test Slug",
        "body": "does not matter",
        "description": "¯\\_(ツ)_/¯",
    }
    response = await authorized_client.post(
        app.url_path_for("articles:create-article"), json={"article": article_data}
    )
    article = ArticleInResponse(**response.json())
    assert article.article.title == article_data["title"]
    assert article.article.author.username == test_user.username