首页
/ Sanic框架中CORS配置问题的分析与解决

Sanic框架中CORS配置问题的分析与解决

2025-05-12 16:21:24作者:宣利权Counsellor

Sanic是一个基于Python的异步Web框架,以其高性能和易用性著称。在使用Sanic开发Web应用时,跨域资源共享(CORS)是一个常见的需求。本文将深入分析Sanic官方文档中CORS配置存在的问题,并提供经过验证的解决方案。

问题背景

在Sanic 24.6.0版本中,按照官方文档配置CORS时,开发者会遇到路由中间件相关的异常。具体表现为当请求到达时,系统抛出AttributeError: 'types.SimpleNamespace' object has no attribute 'request_middleware'错误,这表明路由中间件处理出现了问题。

错误分析

通过调试发现,问题根源在于options.py文件中的app.router.reset()app.router.finalize()调用。这两个操作会干扰Sanic的路由系统正常工作,导致路由中间件信息丢失。

解决方案

经过实践验证,可以简化CORS配置方案如下:

核心CORS处理模块

from sanic import Request, HTTPResponse
from typing import Iterable

def _add_cors_headers(request: Request, response: HTTPResponse, methods: str) -> None:
    response.headers['Access-Control-Allow-Headers'] = "origin, content-type, accept, authorization, x-xsrf-token, x-request-id"
    response.headers['Access-Control-Allow-Methods'] = methods
    response.headers['Access-Control-Allow-Origin'] = request.headers.get('Origin') or '*'

def add_cors_headers(request: Request, response: HTTPResponse):
    _add_cors_headers(request, response, request.app.ctx.uri_methods_mapping[request.route.uri])

OPTIONS请求处理模块

from collections import defaultdict
from typing import Dict
from sanic import empty, Request, HTTPResponse, Sanic
from sanic.router import Route

def _compile_routes_needing_options(routes: Dict[str, Route]) -> Dict[str, str]:
    needs_options = defaultdict(list)
    for route in routes:
        if "OPTIONS" not in route.methods:
            needs_options[route.uri].extend(route.methods)
    return {uri: ",".join(methods) for uri, methods in dict(needs_options).items()}

async def options_handler(request: Request, *args, **kwargs) -> HTTPResponse:
    return empty()

def setup_options(app: Sanic, _):
    uri_methods_mapping = _compile_routes_needing_options(app.router.routes)
    app.ctx.uri_methods_mapping = uri_methods_mapping
    for uri, methods in uri_methods_mapping.items():
        app.add_route(options_handler, uri, methods = ["OPTIONS"])

实现原理

  1. 路由分析_compile_routes_needing_options函数扫描所有路由,找出需要添加OPTIONS方法的路由
  2. 上下文存储:将路由与方法映射关系存储在应用上下文中,便于后续访问
  3. OPTIONS处理:为每个需要CORS的路由添加OPTIONS方法处理
  4. CORS头处理:在响应中添加必要的CORS头信息

注意事项

  1. 此方案适用于Sanic 24.6.0及以上版本
  2. 如果需要更复杂的OPTIONS处理逻辑,可以扩展options_handler函数
  3. 确保在应用启动时正确注册这些中间件和路由

总结

通过简化CORS配置方案,避免了路由系统的干扰,同时保持了完整的CORS功能。这个方案经过实际项目验证,能够稳定处理跨域请求,为Sanic开发者提供了一个可靠的CORS实现参考。

登录后查看全文

项目优选

收起
leetcodeleetcode
🔥LeetCode solutions in any programming language | 多种编程语言实现 LeetCode、《剑指 Offer(第 2 版)》、《程序员面试金典(第 6 版)》题解
Java
51
15
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
574
416
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
125
208
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
77
146
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
442
39
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
98
253
MateChatMateChat
前端智能化场景解决方案UI库,轻松构建你的AI应用,我们将持续完善更新,欢迎你的使用与建议。 官网地址:https://matechat.gitcode.com
693
91
folibfolib
FOLib 是一个为Ai研发而生的、全语言制品库和供应链服务平台
Java
108
6
CS-BooksCS-Books
🔥🔥超过1000本的计算机经典书籍、个人笔记资料以及本人在各平台发表文章中所涉及的资源等。书籍资源包括C/C++、Java、Python、Go语言、数据结构与算法、操作系统、后端架构、计算机系统知识、数据库、计算机网络、设计模式、前端、汇编以及校招社招各种面经~
120
16
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
299
1.03 K