【发布时间】:2020-12-19 15:16:36
【问题描述】:
我需要让我的 Django 应用程序能够在没有 CSRF 令牌的情况下接收未经请求的 POST 请求。
这个问题在here 之前被问过,但是给出的答案是,使用函数get 和post 实现基于类的视图并没有帮助我。
这是我的视图类:
class WebHooks(TemplateView):
def get(self, request):
return HttpResponse("get")
def post(self, request):
return HttpResponse("post")
我还添加了指令
<Location "/">
AllowMethods GET POST OPTIONS
</Location>
到我的httpd.conf for Apache 并将 Django 的 settings.py 中的 CSRF_USE_SESSION 常量设置为 False。
使用 Postman 对此进行测试不断返回“get”。服务器访问日志为POST /url HTTP/1.1" 403 3366。
如何启用 POST 请求?
编辑:
我在服务器上做了一些本地测试,发现一定是 Apache 把我搞砸了。向 Django 的开发服务器发送 post 请求返回“post”,而在 Apache 服务器上返回“get”。
EDIT2:
默认情况下,Apache 似乎会重定向所有流量。为了使它能够将 POST 请求转发到 django 应用程序,我需要根据 this 问题的 mod_proxy 和 mod_rewrite 模块。
我加载了模块并编辑了我的 VirtualHost,如下所示:
<VirtualHost *:443>
RewriteEngine On
RewriteRule /proxy/(.*)$ https://www.my.domain/$1 [P,L]
ServerName my.domain
SSLEngine on
SSLProxyEngine on
SSLCertificateFile "path/to/cert"
SSLCertificateKeyFile "path/to/key"
</VirtualHost>
我仍然不确定在哪个 Directory 指令中放置这些行
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
POST 请求仍然会变成 GET 请求...
EDIT3:
在编写完 EDIT2 之后,我重新阅读了我的问题,并注意到我的问题从 django 拒绝 POST 请求到 Apache 将 POST 请求转为 GET 请求。我不知道为什么。这让我非常困惑。
【问题讨论】:
-
使用
@csrf_exempt装饰器。 docs.djangoproject.com/en/3.1/ref/csrf/… -
遗憾的是,这既不适用于基于类的视图,也不适用于基于函数的视图
-
对于基于类的它是这样的
@method_decorator(csrf_exempt, name='dispatch')。但如果它在基于函数的视图中不起作用,也许这不是问题。