Django SECURE_SSL_REDIRECT and 301 HTTP responses

吃可爱长大的小学妹 提交于 2019-12-07 07:05:26

问题


In environments different from local, I set DJ_SSL_REDIRECT = True for my Django project.

But now, all my unit tests related to REST API endpoints failed when they are run in another environment (for example, in Travis CI).

What is happening is that all HTTP responses are 301 (I'm expecting 2XX or 4XX in my tests) because of the DJ_SSL_REDIRECT setting, as explained in doc :

If you set the SECURE_SSL_REDIRECT setting to True, SecurityMiddleware will permanently (HTTP 301) redirect all HTTP connections to HTTPS.

How can I deal with this in a simple way, keeping my unit tests relevant? Thanks.

Note : I'm using Django Rest Framework 3.5


回答1:


I've had a similar problem and solved it using the "secure"-attribute for the testing client post ang get functions, like

    response = self.client.post('/accounts/signup/', self.getvalues(), follow=True, secure=True)

Hope this helps!

Mikko




回答2:


You can set SECURE_SSL_REDIRECT based on whether the code is being called by manage.py test. Put this in your settings.py:

# Are we testing? i.e. was this code run via "manage.py test"
TESTING = len(sys.argv) > 1 and sys.argv[1] == 'test'
SECURE_SSL_REDIRECT = False if TESTING else True


来源:https://stackoverflow.com/questions/40472094/django-secure-ssl-redirect-and-301-http-responses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!