本文介绍: 是MIDDLEWARE_CLASSES 不是MIDDLEWARE,否则不生效。使用httpx代替requests

参考:
https://zhuanlan.zhihu.com/p/416978320
https://blog.csdn.net/SweetHeartHuaZai/article/details/130983179

使用httpx代替requests

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中添加如下配置

INSTALLED_APPS = [

'corsheaders',

]

MIDDLEWARE_CLASSES = [

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

]

注意:
是MIDDLEWARE_CLASSES 不是MIDDLEWARE,否则不生效。

如果处理后报如下错误:

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 ):

MIDDLEWARE_CLASSES = [
    'corsheaders.middleware.CorsMiddleware',
]

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

原文地址:https://blog.csdn.net/sinat_26809255/article/details/134591086

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_674.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注