Skip to content
The Chat Archive
claude-sonnet-4-20250514-thinking-32k· Anthropic LMArena Human Preference 140K

Python 3.12, Flet 0.28.3. ページ(アプリ)が開いている間だけhttpxのクライアントを利用できるように保持しておくコードを書いて。…

  1. User

    Python 3.12, Flet 0.28.3. ページ(アプリ)が開いている間だけhttpxのクライアントを利用できるように保持しておくコードを書いて。 FletはGUIとして使用するだけで、ローカルからしか利用しない。

  2. Assistant

    Fletアプリケーションでhttpxクライアントを適切に管理するコードを書きます。アプリが開いている間だけクライアントを保持し、アプリが閉じられた時にクリーンアップを行います。

    import flet as ft
    import httpx
    import asyncio
    from typing import Optional
    
    class HttpClientManager:
        def __init__(self):
            self.client: Optional[httpx.AsyncClient] = None
        
        async def get_client(self) -> httpx.AsyncClient:
            """httpxクライアントを取得(初回は作成)"""
            if self.client is None:
                self.client = httpx.AsyncClient(
                    timeout=httpx.Timeout(10.0),
                    limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
                )
            return self.client
        
        async def close_client(self):
            """httpxクライアントをクローズ"""
            if self.client is not None:
                await self.client.aclose()
                self.client = None
    
    # グローバルなクライアントマネージャー
    http_manager = HttpClientManager()
    
    async def main(page: ft.Page):
        page.title = "HTTP Client Manager Sample"
        page.window_width = 600
        page.window_height = 400
        
        # アプリ終了時のクリーンアップを設定
        async def cleanup_on_close(e):
            print("アプリ終了中... HTTPクライアントをクローズします")
            await http_manager.close_client()
        
        page.on_close = cleanup_on_close
        
        # HTTPリクエストの例
        async def make_request(e):
            result_text.value = "リクエスト中..."
            await page.update_async()
            
            try:
                client = await http_manager.get_client()
                response = await client.get("https://httpbin.org/json")
                result_text.value = f"ステータス: {response.status_code}\n{response.text[:200]}..."
            except Exception as ex:
                result_text.value = f"エラー: {str(ex)}"
            
            await page.update_async()
        
        # UI要素
        request_button = ft.ElevatedButton(
            text="HTTPリクエスト実行",
            on_click=make_request
        )
        
        result_text = ft.Text(
            value="HTTPリクエストボタンを押してください",
            width=500,
            height=200
        )
        
        # レイアウト
        page.add(
            ft.Column([
                ft.Text("HTTP Client Manager Sample", size=20, weight=ft.FontWeight.BOLD),
                ft.Divider(),
                request_button,
                ft.Container(
                    content=result_text,
                    border=ft.border.all(1, ft.colors.GREY_400),
                    border_radius=5,
                    padding=10,
                    margin=ft.margin.symmetric(vertical=10)
                )
            ])
        )
    
    # アプリケーション実行
    if __name__ == "__main__":
        ft.app(target=main)
    

    さらに、複数のページや複雑なアプリケーション構造に対応する場合は、以下のようなより高度な実装も可能です:

    import flet as ft
    import httpx
    import asyncio
    from typing import Optional
    from contextlib import asynccontextmanager
    
    class FletHttpApp:
        def __init__(self):
            self.client: Optional[httpx.AsyncClient] = None
        
        async def initialize(self):
            """アプリケーション初期化時にHTTPクライアントを作成"""
            self.client = httpx.AsyncClient(
                timeout=httpx.Timeout(10.0),
                limits=httpx.Limits(max_keepalive_connections=5, max_connections=10)
            )
            print("HTTPクライアントを初期化しました")
        
        async def cleanup(self):
            """アプリ終了時のクリーンアップ"""
            if self.client:
                await self.client.aclose()
                self.client = None
                print("HTTPクライアントをクローズしました")
        
        async def get_client(self) -> httpx.AsyncClient:
            """HTTPクライアントを取得"""
            if self.client is None:
                await self.initialize()
            return self.client
    
    # アプリケーションインスタンス
    app_instance = FletHttpApp()
    
    async def main(page: ft.Page):
        page.title = "Advanced HTTP Client Manager"
        page.window_width = 700
        page.window_height = 500
        
        # アプリ初期化
        await app_instance.initialize()
        
        # アプリ終了時のクリーンアップ
        async def on_app_close(e):
            await app_instance.cleanup()
        
        page.on_close = on_app_close
        
        # 複数のAPIエンドポイントをテスト
        async def test_api(endpoint: str, text_field: ft.Text):
            text_field.value = "リクエスト中..."
            await page.update_async()
            
            try:
                client = await app_instance.get_client()
                response = await client.get(f"https://httpbin.org/{endpoint}")
                text_field.value = f"✅ {response.status_code}: {response.text[:100]}..."
            except Exception as ex:
                text_field.value = f"❌ エラー: {str(ex)}"
            
            await page.update_async()
        
        # UI要素
        json_result = ft.Text("未実行", width=600, height=60)
        ip_result = ft.Text("未実行", width=600, height=60)
        headers_result = ft.Text("未実行", width=600, height=60)
        
        page.add(
            ft.Column([
                ft.Text("Advanced HTTP Client Manager", size=24, weight=ft.FontWeight.BOLD),
                ft.Divider(),
                
                # JSONエンドポイント
                ft.Row([
                    ft.ElevatedButton(
                        "JSON取得",
                        on_click=lambda e: asyncio.create_task(test_api("json", json_result))
                    ),
                    json_result
                ]),
                
                # IPエンドポイント
                ft.Row([
                    ft.ElevatedButton(
                        "IP取得",
                        on_click=lambda e: asyncio.create_task(test_api("ip", ip_result))
                    ),
                    ip_result
                ]),
                
                # ヘッダーエンドポイント
                ft.Row([
                    ft.ElevatedButton(
                        "ヘッダー取得",
                        on_click=lambda e: asyncio.create_task(test_api("headers", headers_result))
                    ),
                    headers_result
                ]),
            ])
        )
    
    if __name__ == "__main__":
        ft.app(target=main)
    

    この実装の特徴:

    1. クライアント管理: HttpClientManagerクラスでhttpxクライアントの生成とクローズを管理
    2. ライフサイクル管理: page.on_closeでアプリ終了時のクリーンアップを実行
    3. リソース効率: アプリが動いている間は同じクライアントインスタンスを再利用
    4. エラーハンドリング: HTTP請求時の例外処理を含む
    5. 非同期対応: Fletの非同期機能を活用

    これでアプリケーションが開いている間だけhttpxクライアントを適切に保持し、アプリ終了時にクリーンアップが行われます。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.