To transform your existing proxy wrapper into a robust local reverse proxy, we can leverage the aiohttp library to create an asynchronous HTTP server. This server will handle incoming requests, apply proxy rotation using the FreeProxy class, and forward the requests to the g4f.client.
Below is an enhanced and comprehensive implementation that integrates your existing proxy logic into a local reverse proxy. This implementation includes improved error handling, logging, and configuration flexibility.
1. Requirements
Before proceeding, ensure you have the necessary Python packages installed. You can install them using pip:
pip install aiohttp lxml requests g4f-client fp
Note:
- Replace
g4f-client and fp with the actual package names if they are different.
- Ensure that you have all required dependencies installed for
g4f.client and fp.fp.
2. Enhanced Proxy Wrapper
First, let's refine your proxy wrapper classes to better handle proxies and integrate seamlessly with an asynchronous server.
import asyncio
import logging
from functools import wraps
from fp.fp import FreeProxy
from g4f.client import Client, AsyncClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ProxyException(Exception):
pass
class ProxyManager:
"""
Manages proxy retrieval and validation.
"""
def __init__(self, timeout=5, rand=True):
self.timeout = timeout
self.rand = rand
def get_proxy(self):
try:
proxy = FreeProxy(timeout=self.timeout, rand=self.rand).get()
logger.debug(f"Obtained proxy: {proxy}")
return proxy
except Exception as e:
logger.error(f"Failed to get proxy: {e}")
raise ProxyException("No proxies available.")
async def get_proxy_async(self):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.get_proxy)
def retry_on_proxy_failure(max_retries=5):
"""
Decorator to retry a function with a new proxy upon failure.
"""
def decorator(func):
@wraps(func)
async def wrapper_async(self, *args, **kwargs):
retries = 0
while retries < max_retries:
try:
proxy = await self.proxy_manager.get_proxy_async()
kwargs["proxy"] = proxy
result = await func(self, *args, **kwargs)
return result
except Exception as e:
retries += 1
logger.warning(f"Proxy failed: {e}. Retrying {retries}/{max_retries}...")
raise ProxyException("Max retries exceeded with proxies.")
@wraps(func)
def wrapper_sync(self, *args, **kwargs):
retries = 0
while retries < max_retries:
try:
proxy = self.proxy_manager.get_proxy()
kwargs["proxy"] = proxy
result = func(self, *args, **kwargs)
return result
except Exception as e:
retries += 1
logger.warning(f"Proxy failed: {e}. Retrying {retries}/{max_retries}...")
raise ProxyException("Max retries exceeded with proxies.")
if asyncio.iscoroutinefunction(func):
return wrapper_async
else:
return wrapper_sync
return decorator
class ProxyClientWrapper:
"""
Synchronous Proxy Wrapper for g4f Client.
"""
def __init__(self):
self.client = Client()
self.proxy_manager = ProxyManager()
@retry_on_proxy_failure()
def __getattr__(self, name):
attr = getattr(self.client, name)
if callable(attr):
return attr
return attr
class ProxyAsyncClientWrapper:
"""
Asynchronous Proxy Wrapper for g4f AsyncClient.
"""
def __init__(self):
self.client = AsyncClient()
self.proxy_manager = ProxyManager()
@retry_on_proxy_failure()
async def __getattr__(self, name):
attr = getattr(self.client, name)
if callable(attr):
async def async_method(*args, **kwargs):
return await attr(*args, **kwargs)
return async_method
return attr
def get_sync_client():
"""
Returns a synchronous client wrapped with proxy handling.
"""
return ProxyClientWrapper()
def get_async_client():
"""
Returns an asynchronous client wrapped with proxy handling.
"""
return ProxyAsyncClientWrapper()
Enhancements:
- Logging: Integrated logging for better traceability and debugging.
- Retry Mechanism: Added a decorator
retry_on_proxy_failure to handle retries with different proxies upon failures.
- ProxyManager Class: Encapsulates proxy retrieval logic, making it reusable and easier to manage.
- Separation of Concerns: Distinguished between synchronous and asynchronous clients for clarity and better performance.
3. Creating the Local Reverse Proxy Server
Now, we'll set up the local reverse proxy server using aiohttp. This server will handle incoming HTTP requests, utilize the proxy wrapper to forward them through a proxy, and return the responses.
import asyncio
from aiohttp import web
import json
# Assuming the ProxyClientWrapper and ProxyAsyncClientWrapper are in proxy_wrapper.py
# from proxy_wrapper import get_sync_client, get_async_client, ProxyException
# Initialize clients
sync_client = get_sync_client()
async_client = get_async_client()
async def handle_request(request):
"""
Handle incoming HTTP requests and forward them to the g4f client.
"""
try:
# Parse the request
data = await request.json()
action = data.get("action")
params = data.get("params", {})
if not action:
return web.json_response({"error": "No action specified."}, status=400)
# Determine if the action is synchronous or asynchronous
if asyncio.iscoroutinefunction(getattr(async_client.client, action, None)):
# Asynchronous action
client = async_client
method = getattr(client, action, None)
if not method:
return web.json_response({"error": f"Action '{action}' not found."}, status=404)
response = await method(**params)
else:
# Synchronous action
client = sync_client
method = getattr(client, action, None)
if not method:
return web.json_response({"error": f"Action '{action}' not found."}, status=404)
response = method(**params)
return web.json_response({"response": response})
except ProxyException as pe:
logger.error(f"Proxy error: {pe}")
return web.json_response({"error": str(pe)}, status=502)
except Exception as e:
logger.exception("Unhandled exception")
return web.json_response({"error": "Internal Server Error"}, status=500)
def create_app():
app = web.Application()
app.router.add_post('/proxy', handle_request)
return app
if __name__ == '__main__':
app = create_app()
web.run_app(app, host='127.0.0.1', port=8080)
Explanation:
-
Endpoint Definition:
/proxy: A POST endpoint that accepts JSON payloads containing the action to perform and its parameters.
-
Request Handling:
- The server expects a JSON body with an
action key specifying the method to call on the g4f client and an optional params key containing the parameters for that method.
- It determines whether the requested action is synchronous or asynchronous based on the client's capabilities.
- The action is then invoked through the appropriate client wrapper (
sync_client or async_client), which automatically handles proxy rotation.
-
Error Handling:
- Proxy Exceptions: Returns a
502 Bad Gateway status if there are issues with proxies.
- General Exceptions: Catches all other exceptions and returns a
500 Internal Server Error.
-
Server Configuration:
- The server listens on
localhost (127.0.0.1) at port 8080. You can change these settings as needed.
4. Usage Example
Here's how you can interact with the local reverse proxy once it's running.
Sending a Request
Use curl, HTTPie, or any HTTP client to send a POST request to the /proxy endpoint.
Example with curl:
curl -X POST http://127.0.0.1:8080/proxy \
-H "Content-Type: application/json" \
-d '{
"action": "desired_method",
"params": {
"param1": "value1",
"param2": "value2"
}
}'
Example with Python requests:
import requests
url = "http://127.0.0.1:8080/proxy"
payload = {
"action": "desired_method",
"params": {
"param1": "value1",
"param2": "value2"
}
}
response = requests.post(url, json=payload)
print(response.json())
Response
The server will respond with a JSON object containing the result of the requested action or an error message.
{
"response": "Result from g4f client method."
}
Or in case of an error:
{
"error": "Error message detailing what went wrong."
}
5. Additional Enhancements
To further improve the reverse proxy, consider implementing the following features:
-
Authentication: Protect the proxy endpoint with API keys or other authentication mechanisms to prevent unauthorized access.
-
Rate Limiting: Implement rate limiting to control the number of requests a client can make within a certain timeframe.
-
Caching: Cache frequent responses to reduce latency and proxy usage.
-
Configuration Management: Externalize configurations (like proxy settings, server host/port) using environment variables or configuration files.
-
Health Checks: Implement health checks to monitor the status of the proxy server and the availability of g4f.client.
-
Logging Enhancements: Use structured logging or integrate with logging services for better monitoring and debugging.
6. Complete Code Listing
For your convenience, here's the complete code integrating all components discussed above.
proxy_wrapper.py
import asyncio
import logging
from functools import wraps
from fp.fp import FreeProxy
from g4f.client import Client, AsyncClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ProxyException(Exception):
pass
class ProxyManager:
"""
Manages proxy retrieval and validation.
"""
def __init__(self, timeout=5, rand=True):
self.timeout = timeout
self.rand = rand
def get_proxy(self):
try:
proxy = FreeProxy(timeout=self.timeout, rand=self.rand).get()
logger.debug(f"Obtained proxy: {proxy}")
return proxy
except Exception as e:
logger.error(f"Failed to get proxy: {e}")
raise ProxyException("No proxies available.")
async def get_proxy_async(self):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.get_proxy)
def retry_on_proxy_failure(max_retries=5):
"""
Decorator to retry a function with a new proxy upon failure.
"""
def decorator(func):
@wraps(func)
async def wrapper_async(self, *args, **kwargs):
retries = 0
while retries < max_retries:
try:
proxy = await self.proxy_manager.get_proxy_async()
kwargs["proxy"] = proxy
result = await func(self, *args, **kwargs)
return result
except Exception as e:
retries += 1
logger.warning(f"Proxy failed: {e}. Retrying {retries}/{max_retries}...")
raise ProxyException("Max retries exceeded with proxies.")
@wraps(func)
def wrapper_sync(self, *args, **kwargs):
retries = 0
while retries < max_retries:
try:
proxy = self.proxy_manager.get_proxy()
kwargs["proxy"] = proxy
result = func(self, *args, **kwargs)
return result
except Exception as e:
retries += 1
logger.warning(f"Proxy failed: {e}. Retrying {retries}/{max_retries}...")
raise ProxyException("Max retries exceeded with proxies.")
if asyncio.iscoroutinefunction(func):
return wrapper_async
else:
return wrapper_sync
return decorator
class ProxyClientWrapper:
"""
Synchronous Proxy Wrapper for g4f Client.
"""
def __init__(self):
self.client = Client()
self.proxy_manager = ProxyManager()
@retry_on_proxy_failure()
def __getattr__(self, name):
attr = getattr(self.client, name)
if callable(attr):
return attr
return attr
class ProxyAsyncClientWrapper:
"""
Asynchronous Proxy Wrapper for g4f AsyncClient.
"""
def __init__(self):
self.client = AsyncClient()
self.proxy_manager = ProxyManager()
@retry_on_proxy_failure()
async def __getattr__(self, name):
attr = getattr(self.client, name)
if callable(attr):
async def async_method(*args, **kwargs):
return await attr(*args, **kwargs)
return async_method
return attr
def get_sync_client():
"""
Returns a synchronous client wrapped with proxy handling.
"""
return ProxyClientWrapper()
def get_async_client():
"""
Returns an asynchronous client wrapped with proxy handling.
"""
return ProxyAsyncClientWrapper()
reverse_proxy_server.py
import asyncio
from aiohttp import web
import json
from proxy_wrapper import get_sync_client, get_async_client, ProxyException
# Initialize clients
sync_client = get_sync_client()
async_client = get_async_client()
async def handle_request(request):
"""
Handle incoming HTTP requests and forward them to the g4f client.
"""
try:
# Parse the request
data = await request.json()
action = data.get("action")
params = data.get("params", {})
if not action:
return web.json_response({"error": "No action specified."}, status=400)
# Determine if the action is asynchronous
client_attr = getattr(async_client.client, action, None)
if asyncio.iscoroutinefunction(client_attr):
# Asynchronous action
client = async_client
method = getattr(client, action, None)
if not method:
return web.json_response({"error": f"Action '{action}' not found."}, status=404)
response = await method(**params)
else:
# Synchronous action
client = sync_client
method = getattr(client, action, None)
if not method:
return web.json_response({"error": f"Action '{action}' not found."}, status=404)
response = method(**params)
return web.json_response({"response": response})
except ProxyException as pe:
logger.error(f"Proxy error: {pe}")
return web.json_response({"error": str(pe)}, status=502)
except Exception as e:
logger.exception("Unhandled exception")
return web.json_response({"error": "Internal Server Error"}, status=500)
def create_app():
app = web.Application()
app.router.add_post('/proxy', handle_request)
return app
if __name__ == '__main__':
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = create_app()
web.run_app(app, host='127.0.0.1', port=8080)
7. Conclusion
By following the above implementation, you've successfully transformed your existing proxy wrapper into a local reverse proxy. This setup ensures that all requests routed through the proxy server will utilize different proxies managed by the FreeProxy class, enhancing anonymity and reliability. The added error handling, logging, and configuration flexibility make the proxy server robust and production-ready.
Feel free to extend this implementation with additional features such as authentication, rate limiting, and caching based on your specific requirements.