Python跨域问题解决集合
Flask
安装插件
pip install flask-cors
使用 CORS函数配置全局路由
from flask_cors import *
app = Flask(__name__)
CORS(app, supports_credentials=True)
from flask_cors import CORS
app = Flask(__name__,)
# r‘/*‘ 是通配符,让本服务器所有的URL 都允许跨域请求
CORS(app, resources=r‘/*‘)
# 上传文件
@uploadFiles.route(‘/upload‘, methods=[‘POST‘])
def uploadFile():
result_text = {"statusCode": 200,"message": "文件上传成功"}
response = make_response(jsonify(result_text))
response.headers[‘Access-Control-Allow-Origin‘] = ‘*‘
response.headers[‘Access-Control-Allow-Methods‘] = ‘OPTIONS,HEAD,GET,POST‘
response.headers[‘Access-Control-Allow-Headers‘] = ‘x-requested-with‘
return response
Django
安装插件
pip install django-cors-headers
添加APP
INSTALLED_APPS = (
‘corsheaders‘,
)
添加中间件
MIDDLEWARE = [
‘corsheaders.middleware.CorsMiddleware‘, #最好添加至第一行
]
配置白名单
#单个配置
CORS_ORIGIN_WHITELIST =(
‘ 域名‘,
)
#正则配置:
CORS_ORIGIN_REGEX_WHITELIST =(r‘^(https?://)?(w+.)?jim.com $‘,)
或者直接允许所有主机跨域
CORS_ORIGIN_ALLOW_ALL = True 默认为False
允许携带cookie
CORS_ALLOW_CREDENTIALS = True
请求头及请求方法的配置:
#默认可以使用的非标准请求头,需要使用自定义请求头时,就可以进行修改
CORS_ALLOW_HEADERS = (
‘accept‘,
‘accept-encoding‘,
‘authorization‘,
‘content-type‘,
‘dnt‘,
‘origin‘,
‘user-agent‘,
‘x-csrftoken‘,
‘x-requested-with‘,
)
#默认请求方法
CORS_ALLOW_METHODS = (
‘DELETE‘,
‘GET‘,
‘OPTIONS‘,
‘PATCH‘,
‘POST‘,
‘PUT‘,
)
防止CSRF
#添加信任的站点 django1.9引入
CSRF_TRUSTED_ORIGINS = (
‘change.allowed.com‘,
)
更多配置详情点击这里
Tornado
解决方案
import tornado.web
class BaseHandler(tornado.web.RequestHandler):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.host = ""
self.port = ""
# 在初始化方法中添加设置跨域的方法
self.set_default_headers()
# 处理OPTIONS域检请求
def post(self):
self.set_status(204)
self.finish()
# 设置跨域的具体方法
def set_default_headers(self):
super().set_default_headers()
# 设置允许的请求头
self.set_header("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS")
self.set_header("X-XSS-Protecion","1")
self.set_header("Content-Security-Policy","default-src ‘self‘")
self.set_header("Access-Control-Allow-Credentials","true")
# 设置一些自己定义的请求头
self.set_header("Access-Control-Allow-Headers",
"Content-Type,Access-Control-Allow-Headers,X-Auth-Token,Y-Auth-Token"
)
self.set_header("Content-Type","application/json; charset=UTF-8")
# 设置允许本地调试的域名通过!
self.set_header("Access-Control-Allow-Origin",self.request.headers.get("Origin","http://localhost:9090"))
# 如果后面的域名设置为 * ,表示允许所有的域名通过
# self.set_header("Access-Control-Allow-Origin","*")
# self.set_header("Access-Control-Allow-Origin",self.request.headers.get("Origin","*"))
调用
class InterFaceHandler(BaseHandler):
def set_default_headers(self):
self.allowMyOrigin()
def get(self, *args, **kwargs):
pass
Python跨域问题解决集合
原文地址:https://www.cnblogs.com/liuyangQAQ/p/14898114.html