Spaces:
Running
Running
Update app.py
Browse files29 unmodified lines3031323334353637383940414243144 unmodified lines1881891901911921931941952 unmodified lines19819920020120220320413 unmodified lines2182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612621 unmodified line26426526626726826927027127227327427527627729 unmodified lines# "proc": None,# },#""""jihou": {"file": "jihou.py","proc": None,},"join": {"file": "join.py","proc": None,},#"""# "ngwords": {# "file": "ngwords.py",144 unmodified linesreturn cookies@app.route("/cors-proxy", methods=["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"], strict_slashes=False)def cors_proxy():# Preflight 対応if request.method == "OPTIONS":return Response(2 unmodified linesheaders={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers": "*","Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",},)13 unmodified lines# cookie_txt_url からif cookie_txt_url:try:txt_resp = requests.get(cookie_txt_url, timeout=10)txt_resp.raise_for_status()txt_cookies = parse_cookie_txt(txt_resp.text)cookies.update(txt_cookies)except requests.RequestException:return "cookie_txt_url の取得に失敗しました", 400if not cookies:cookies = Noneurl = request.args.get("url")if not url:return "url パラメータが必要です", 400if not url.startswith(("http://", "https://")):return "http または https のURLのみ使用できます", 400# 追加転送ヘッダ取得extra_headers = set()send_param = request.args.get("send")if send_param:extra_headers = {h.strip() for h in send_param.split(",") if h.strip()}allowed_headers = {h.lower() for h in FORWARD_HEADERS}allowed_headers.update(h.lower() for h in extra_headers)headers = {k: v for k, v in request.headers.items()if k.lower() in allowed_headers}headers.pop("Accept-Encoding", None)forward_params = request.args.to_dict(flat=True)forward_params.pop("url", None)forward_params.pop("send", None)forward_params.pop("cookie", None)forward_params.pop("cookie_txt_url", None)resp = requests.request(method=request.method,url=url,1 unmodified linedata=request.get_data(),params=forward_params,cookies=cookies,timeout=300,)response = Response(resp.content, resp.status_code)response.headers["Access-Control-Allow-Origin"] = "*"response.headers["Access-Control-Allow-Headers"] = "*"response.headers["Access-Control-Allow-Methods"] = "GET, POST, PATCH, PUT, DELETE, OPTIONS"if "Content-Type" in resp.headers:response.headers["Content-Type"] = resp.headers["Content-Type"]29 unmodified lines3031323334353637383940414243144 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682 unmodified lines27127227327427527627727827913 unmodified lines2932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923931 unmodified line39539639739839940040140240340440540640740840941041141241341429 unmodified lines# "proc": None,# },#"""# "jihou": {# "file": "jihou.py",# "proc": None,# },# "join": {# "file": "join.py",# "proc": None,# },#"""# "ngwords": {# "file": "ngwords.py",144 unmodified linesreturn cookiesimport randomfrom urllib.parse import quoteimport requestsfrom flask import request, Responsedef get_webshare_proxy(webshare_token):"""Webshare APIから有効なProxyを1件取得して、requests用のproxy URLを返す。"""if not webshare_token:raise ValueError("webshare_token が設定されていません")api_url = "https://proxy.webshare.io/api/v2/proxy/list/"resp = requests.get(api_url,headers={"Authorization": f"Token {webshare_token}",},params={"mode": "direct","page": 1,"page_size": 100,},timeout=15,)resp.raise_for_status()data = resp.json()proxies = [proxyfor proxy in data.get("results", [])if proxy.get("valid") is True]if not proxies:raise RuntimeError("Webshareから利用可能なProxyが取得できませんでした")proxy = random.choice(proxies)proxy_address = proxy["proxy_address"]proxy_port = proxy["port"]username = proxy.get("username")password = proxy.get("password")# username/password認証if username and password:username = quote(str(username), safe="")password = quote(str(password), safe="")proxy_url = (f"http://{username}:{password}"f"@{proxy_address}:{proxy_port}")else:# IP Authorizationの場合proxy_url = f"http://{proxy_address}:{proxy_port}"return {"http": proxy_url,"https": proxy_url,}@app.route("/cors-proxy",methods=["GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"],strict_slashes=False,)def cors_proxy():# Preflight 対応if request.method == "OPTIONS":return Response(2 unmodified linesheaders={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Headers": "*","Access-Control-Allow-Methods": ("GET, POST, PATCH, PUT, DELETE, OPTIONS"),},)13 unmodified lines# cookie_txt_url からif cookie_txt_url:try:txt_resp = requests.get(cookie_txt_url,timeout=10,)txt_resp.raise_for_status()txt_cookies = parse_cookie_txt(txt_resp.text)cookies.update(txt_cookies)except requests.RequestException:return "cookie_txt_url の取得に失敗しました", 400if not cookies:cookies = None# 転送先URLurl = request.args.get("url")if not url:return "url パラメータが必要です", 400if not url.startswith(("http://", "https://")):return "http または https のURLのみ使用できます", 400# =========================================================# Webshare Proxy# =========================================================useproxy = request.args.get("useproxy", "false").lower() == "true"proxies = Noneif useproxy:# 例:# webshare_token = "xxxxxxxxxxxxxxxx"## 本番では環境変数などから取得するのがおすすめwebshare_token = app.config.get("WEBSHARE_TOKEN")try:proxies = get_webshare_proxy(webshare_token)except requests.RequestException as e:return f"Webshare APIへの接続に失敗しました: {e}", 502except (ValueError, RuntimeError) as e:return str(e), 502# =========================================================# 追加転送ヘッダ取得# =========================================================extra_headers = set()send_param = request.args.get("send")if send_param:extra_headers = {h.strip()for h in send_param.split(",")if h.strip()}allowed_headers = {h.lower() for h in FORWARD_HEADERS}allowed_headers.update(h.lower() for h in extra_headers)headers = {k: vfor k, v in request.headers.items()if k.lower() in allowed_headers}headers.pop("Accept-Encoding", None)# =========================================================# 転送するGETパラメータ# =========================================================forward_params = request.args.to_dict(flat=True)forward_params.pop("url", None)forward_params.pop("send", None)forward_params.pop("cookie", None)forward_params.pop("cookie_txt_url", None)# useproxy / webshare_token は転送先へ送らないforward_params.pop("useproxy", None)forward_params.pop("webshare_token", None)# =========================================================# リクエスト# =========================================================resp = requests.request(method=request.method,url=url,1 unmodified linedata=request.get_data(),params=forward_params,cookies=cookies,proxies=proxies,timeout=300,)response = Response(resp.content,resp.status_code,)response.headers["Access-Control-Allow-Origin"] = "*"response.headers["Access-Control-Allow-Headers"] = "*"response.headers["Access-Control-Allow-Methods"] = ("GET, POST, PATCH, PUT, DELETE, OPTIONS")if "Content-Type" in resp.headers:response.headers["Content-Type"] = resp.headers["Content-Type"]
app.py+153-16