Juna190825 commited on
Commit
8a2d2c4
·
verified ·
1 Parent(s): dba2c72

Create proxy/proxy_server.py

Browse files
Files changed (1) hide show
  1. proxy/proxy_server.py +64 -0
proxy/proxy_server.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import requests
3
+ from flask import Flask, request, Response, send_from_directory
4
+
5
+ app = Flask(__name__, static_folder="static", template_folder="templates")
6
+
7
+ EDITOR_BASE = "http://localhost:5555"
8
+ API_BASE = "http://localhost:5556"
9
+
10
+ # ---------- Combined UI page ----------
11
+ @app.route("/")
12
+ def index():
13
+ return send_from_directory("templates", "index.html")
14
+
15
+ # ---------- Reverse proxy to ConlluEditor ----------
16
+ @app.route("/editor/<path:path>", methods=["GET", "POST"])
17
+ @app.route("/editor", defaults={"path": ""}, methods=["GET", "POST"])
18
+ def proxy_editor(path):
19
+ url = f"{EDITOR_BASE}/{path}"
20
+ if request.query_string:
21
+ url += "?" + request.query_string.decode()
22
+
23
+ if request.method == "GET":
24
+ r = requests.get(url, headers=_filtered_headers(), stream=True)
25
+ else:
26
+ r = requests.post(url, data=request.form or request.data,
27
+ headers=_filtered_headers(), stream=True)
28
+
29
+ return Response(r.iter_content(chunk_size=8192),
30
+ status=r.status_code,
31
+ headers=_proxied_response_headers(r))
32
+
33
+ # ---------- Reverse proxy to upload API ----------
34
+ @app.route("/api/<path:path>", methods=["GET", "POST"])
35
+ def proxy_api(path):
36
+ url = f"{API_BASE}/api/{path}"
37
+ if request.query_string:
38
+ url += "?" + request.query_string.decode()
39
+
40
+ if request.method == "GET":
41
+ r = requests.get(url, headers=_filtered_headers(), stream=True)
42
+ else:
43
+ r = requests.post(url, files=request.files or None,
44
+ data=request.form or None,
45
+ headers=_filtered_headers(), stream=True)
46
+
47
+ return Response(r.iter_content(chunk_size=8192),
48
+ status=r.status_code,
49
+ headers=_proxied_response_headers(r))
50
+
51
+ def _filtered_headers():
52
+ excluded = {"host", "content-length", "content-encoding", "connection"}
53
+ return {k: v for k, v in request.headers.items() if k.lower() not in excluded}
54
+
55
+ def _proxied_response_headers(r):
56
+ excluded = {"content-encoding", "transfer-encoding", "connection"}
57
+ headers = [(k, v) for k, v in r.headers.items() if k.lower() not in excluded]
58
+ return headers
59
+
60
+ if __name__ == "__main__":
61
+ parser = argparse.ArgumentParser()
62
+ parser.add_argument("--port", type=int, default=7860)
63
+ args = parser.parse_args()
64
+ app.run(host="0.0.0.0", port=args.port)