main.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from flask import Flask, request, Response
  2. from flask_cors import CORS
  3. import requests
  4. import json
  5. from config import OLLAMA_API_BASE_URL
  6. app = Flask(__name__)
  7. CORS(
  8. app
  9. ) # Enable Cross-Origin Resource Sharing (CORS) to allow requests from different domains
  10. # Define the target server URL
  11. TARGET_SERVER_URL = OLLAMA_API_BASE_URL
  12. @app.route("/", defaults={"path": ""}, methods=["GET", "POST", "PUT", "DELETE"])
  13. @app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE"])
  14. def proxy(path):
  15. # Combine the base URL of the target server with the requested path
  16. target_url = f"{TARGET_SERVER_URL}/{path}"
  17. print(target_url)
  18. # Get data from the original request
  19. data = request.get_data()
  20. headers = dict(request.headers)
  21. # Make a request to the target server
  22. target_response = requests.request(
  23. method=request.method,
  24. url=target_url,
  25. data=data,
  26. headers=headers,
  27. stream=True, # Enable streaming for server-sent events
  28. )
  29. # Proxy the target server's response to the client
  30. def generate():
  31. for chunk in target_response.iter_content(chunk_size=8192):
  32. yield chunk
  33. response = Response(generate(), status=target_response.status_code)
  34. # Copy headers from the target server's response to the client's response
  35. for key, value in target_response.headers.items():
  36. response.headers[key] = value
  37. return response
  38. if __name__ == "__main__":
  39. app.run(debug=True)