python实现跨域代理服务器

  • 准备环境
  1. python3.7+
  2. 依赖: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)

  • 测试
  1. 写个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();
}
  1. 下载测试
downloadfile(url, fileName)
  1. 结果

    可以正常下载
    并且在响应头中能看到Server:is my server
    同时可以看到添加成功的Allow-Origin响应头

热门相关:冉冉心动   修真界败类   富贵不能吟   神算大小姐   修真界败类