refactor: replace requests with httpx in Bitcoin wallet and blockchain services
- Replace requests.Session with httpx.Client in BitcoinWallet class - Add graceful fallback when httpx is not available with HTTP_CLIENT_AVAILABLE flag - Add session null check in _rpc_call to prevent errors when httpx unavailable - Update get_balance in blockchain service to use httpx.Client context manager - Add warning log when httpx import fails to disable wallet functions
This commit is contained in:
@@ -7,9 +7,15 @@ Uses RPC to connect to Bitcoin Core (or alternative like Block.io)
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import requests
|
||||
from typing import Dict, Optional
|
||||
|
||||
try:
|
||||
import httpx
|
||||
HTTP_CLIENT_AVAILABLE = True
|
||||
except ImportError:
|
||||
HTTP_CLIENT_AVAILABLE = False
|
||||
logging.warning("httpx not available, bitcoin wallet functions will be disabled")
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Bitcoin wallet configuration (credentials from environment)
|
||||
@@ -25,8 +31,12 @@ WALLET_CONFIG = {
|
||||
class BitcoinWallet:
|
||||
def __init__(self):
|
||||
self.config = WALLET_CONFIG
|
||||
self.session = requests.Session()
|
||||
self.session.auth = (self.config['rpc_user'], self.config['rpc_password'])
|
||||
if not HTTP_CLIENT_AVAILABLE:
|
||||
logger.error("httpx not available - bitcoin wallet functions disabled")
|
||||
self.session = None
|
||||
else:
|
||||
self.session = httpx.Client()
|
||||
self.session.auth = (self.config['rpc_user'], self.config['rpc_password'])
|
||||
|
||||
def get_balance(self) -> float:
|
||||
"""Get the current Bitcoin balance"""
|
||||
@@ -68,6 +78,9 @@ class BitcoinWallet:
|
||||
"""Make an RPC call to Bitcoin Core"""
|
||||
if params is None:
|
||||
params = []
|
||||
|
||||
if not self.session:
|
||||
return {"error": "httpx not available"}
|
||||
|
||||
payload = {
|
||||
"jsonrpc": "2.0",
|
||||
|
||||
@@ -35,16 +35,15 @@ def get_balance(address: str) -> Optional[float]:
|
||||
"""Get AITBC balance for an address"""
|
||||
|
||||
try:
|
||||
import requests
|
||||
|
||||
response = requests.get(
|
||||
f"{BLOCKCHAIN_RPC}/getBalance/{address}",
|
||||
headers={"X-Api-Key": settings.admin_api_keys[0] if settings.admin_api_keys else ""}
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return float(data.get("balance", 0))
|
||||
with httpx.Client() as client:
|
||||
response = client.get(
|
||||
f"{BLOCKCHAIN_RPC}/getBalance/{address}",
|
||||
headers={"X-Api-Key": settings.admin_api_keys[0] if settings.admin_api_keys else ""}
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return float(data.get("balance", 0))
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Error getting balance: %s", e)
|
||||
|
||||
Reference in New Issue
Block a user