requests请求django接口跨域问题处理

参考:

https://zhuanlan.zhihu.com/p/416978320

https://blog.csdn.net/SweetHeartHuaZai/article/details/130983179

使用httpx代替requests

bash 复制代码
import httpx

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
}

res = httpx.get(url='https://www.baidu.com/', headers=headers, timeout=10, verify=False)
print(res.text)

django中添加如下配置:

bash 复制代码
INSTALLED_APPS = [

'corsheaders',

]

MIDDLEWARE_CLASSES = [

'corsheaders.middleware.CorsMiddleware', #这个放到第一位

]

注意:

是MIDDLEWARE_CLASSES 不是MIDDLEWARE,否则不生效。

如果处理后报如下错误:

bash 复制代码
ERRORS:
?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.
        HINT: Insert 'django.contrib.sessions.middleware.SessionMiddleware' before 'django.contrib.auth.middleware.AuthenticationMiddleware'.

处理办法如下(同时添加MIDDLEWARE_CLASSES 和 MIDDLEWARE ):

bash 复制代码
MIDDLEWARE_CLASSES = [
    'corsheaders.middleware.CorsMiddleware',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]
相关推荐
万邦科技Lafite11 分钟前
利用淘宝开放API接口监控商品状态,掌握第一信息
大数据·python·电商开放平台·开放api接口·淘宝开放平台
Victor35613 分钟前
Redis(14)Redis的列表(List)类型有哪些常用命令?
后端
Victor35613 分钟前
Redis(15)Redis的集合(Set)类型有哪些常用命令?
后端
卷福同学15 分钟前
来上海三个月,我在马路边上遇到了阿里前同事...
java·后端
Hy行者勇哥2 小时前
Python 与 VS Code 结合操作指南
开发语言·python
大力水手(Popeye)2 小时前
Pytorch——tensor
人工智能·pytorch·python
飞翔的佩奇6 小时前
【完整源码+数据集+部署教程】表盘指针检测系统源码和数据集:改进yolo11-CA-HSFPN
python·yolo·计算机视觉·数据集·yolo11·表盘指针检测
larance7 小时前
SQLAlchemy 的异步操作来批量保存对象列表
数据库·python
搏博7 小时前
基于Python3.10.6与jieba库的中文分词模型接口在Windows Server 2022上的实现与部署教程
windows·python·自然语言处理·flask·中文分词
lxmyzzs8 小时前
pyqt5无法显示opencv绘制文本和掩码信息
python·qt·opencv