From f6a91b8b64f851839ce2ff50830e3d0d8e55ea5a Mon Sep 17 00:00:00 2001 From: Tim O'Farrell Date: Thu, 16 Jan 2025 16:21:08 -0700 Subject: [PATCH] Example usage of httpx --- openhands/server/routes/github.py | 42 ++++++++++++++----------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/openhands/server/routes/github.py b/openhands/server/routes/github.py index b024566e62f4..921d6df6d860 100644 --- a/openhands/server/routes/github.py +++ b/openhands/server/routes/github.py @@ -1,3 +1,4 @@ +import httpx import requests from fastapi import APIRouter, Depends, HTTPException, Request from fastapi.responses import JSONResponse @@ -47,46 +48,41 @@ async def get_github_repositories( # Fetch repositories from GitHub try: - response = await call_sync_from_async( - requests.get, github_api_url, headers=headers, params=params - ) - response.raise_for_status() # Raise an error for HTTP codes >= 400 + async with httpx.AsyncClient() as client: + response = await client.get(github_api_url, headers=headers, params=params) + response.raise_for_status() # Raise an error for HTTP codes >= 400 + json_response = JSONResponse(content=response.json()) + + # Forward the Link header if it exists + if 'Link' in response.headers: + json_response.headers['Link'] = response.headers['Link'] + + return json_response + except requests.exceptions.RequestException as e: raise HTTPException( status_code=response.status_code if response else 500, detail=f'Error fetching repositories: {str(e)}', ) - # Create response with the JSON content - json_response = JSONResponse(content=response.json()) - response.close() - - # Forward the Link header if it exists - if 'Link' in response.headers: - json_response.headers['Link'] = response.headers['Link'] - - return json_response - @app.get('/user') async def get_github_user(github_token: str = Depends(require_github_token)): headers = generate_github_headers(github_token) try: - response = await call_sync_from_async( - requests.get, 'https://api.github.com/user', headers=headers - ) - response.raise_for_status() + async with httpx.AsyncClient() as client: + response = await client.get('https://api.github.com/user', headers=headers) + response.raise_for_status() # Raise an error for HTTP codes >= 400 + json_response = JSONResponse(content=response.json()) + + return json_response + except requests.exceptions.RequestException as e: raise HTTPException( status_code=response.status_code if response else 500, detail=f'Error fetching user: {str(e)}', ) - json_response = JSONResponse(content=response.json()) - response.close() - - return json_response - @app.get('/installations') async def get_github_installation_ids(