- 準備環境 1. python3.7+ 2. 依賴:aiohttp - 代碼實現(代理伺服器,返迴響應體和進行跨域處理後的headers) ``` python3.7 import aiohttp from functools import wraps from aiohttp import we ...
- 準備環境
- python3.7+
- 依賴:aiohttp
- 代碼實現(代理伺服器,返迴響應體和進行跨域處理後的headers)
import aiohttp
from functools import wraps
from aiohttp import web
corscode = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', # 需要限制請求就在這裡增刪
'Access-Control-Allow-Headers': '*',
'Server':'is my server',
}
# 實例化路由
routes = web.RouteTableDef()
# 非同步json序列化
def jsondump(func):
@wraps(func)
async def wrapper(*args,**kwargs):
result = await func(*args,**kwargs)
try:
return json.dumps(result ,ensure_ascii=False)
except:
return result
return wrapper
# 封裝一下web.json_resp
# def wj(dt):
# return web.json_response(dt)
wj = lambda dt: web.json_response(dt)
# 處理OPTIONS和跨域的中間件
@jsondump
async def options_middleware(app, handler):
async def middleware(request):
# 處理 OPTIONS 請求,直接返回空數據和允許跨域的 header
if request.method == 'OPTIONS':
return web.Response(headers=corscode)
# 繼續處理其他請求
response = await handler(request)
# 為每次響應添加header
try:
response.headers.update(corscode)
except Exception as e:
return response
return response
return middleware
@jsondump
@routes.view(r'/get')
async def geturl(request):
url = request.query.get('url')
if not url:
return wj({"data":"參數錯誤"})
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
# 檢查請求是否成功,如果不成功,可以根據需要進行處理
if response.status == 200:
file = await response.read()
return web.Response(body=file, headers=response.headers)
if __name__ == '__main__':
app = web.Application()
app.add_routes(routes)
app.middlewares.append(options_middleware)
web.run_app(app)
- 測試
- 寫個get的方法
function downloadfile(url, fileName) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
var blob = xhr.response;
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}
};
xhr.send();
}
- 下載測試
downloadfile(url, fileName)
- 結果
可以正常下載
並且在響應頭中能看到Server:is my server
同時可以看到添加成功的Allow-Origin響應頭