TL; DR :我有一个POST请求(来自Requests模块),该请求在Django视图外部运行,但在视图内部引发类型为'OpenSSL.SSL.Error'的异常。有人可以告诉我如何解决吗?
问题:
我正在使用Django 1.7.11,Requests 2.14.2和Python 2.7.14在Linux on AWS上托管Web应用程序。
Web应用程序的目录结构设置如下:
myproject
|___myapp
| |
| |___templates
| | |
| | |___mytemplate.html
| |
| |___views.py
| |___urls.py
|
|___post_request.py
我在views.py中有一个函数,可以直接从Django模板mytemplate.html中的链接调用它。模板中的链接不是表单的一部分,其指定方式如下:
<li><a href="{% url 'myapp:myview' %}">The Link to My View</a></li>
myapp / urls.py中的相应条目为:
url(r"^myview/$", the_view_function, name="myview")
myapp / views.py中的函数如下:
def the_view_function(request):
if request.user.is_authenticated():
context = {}
data = {}
headers = {}
headers['Authorization'] = 'Token aaaaabbbbbcccc'
the_url = "https://www.example.com/rest/endpoint/"
logger.info("view function called")
if 'variable_1' in request.session:
variable_1 = request.session['variable_1']
logger.info("Variable 1 is set")
else:
variable_1 = 0
logger.info("Variable 1 is zero")
if 'variable_2' in request.session:
variable_2 = request.session['variable_2']
else:
variable_2 = -1
if variable_1 == 0:
logger.info("First time")
data['first_name'] = 'firstname'
data['last_name'] = 'lastname'
data['email'] = 'user@not.valid.email.com'
data['role'] = "User"
the_response = requests.post(the_url, headers=headers, data=data, verify=False)
以下行失败:
the_response = requests.post(the_url, headers=headers, data=data, verify=False)
当我从Web浏览器的页面中单击“链接到我的视图”时,请求将引发类型为“ OpenSSL.SSL.Error”的异常。
但是:
post_request.py文件中有以下代码:
import requests
the_url = "https://www.example.com/rest/endpoint/"
headers = {'Authorization': 'Token aaaaabbbbbcccc'}
post_data = dict()
post_data['first_name'] = 'firstname'
post_data['last_name'] = 'lastname'
post_data['email'] = 'user@not.valid.email.com'
post_data['role'] = "User"
the_response = requests.post(the_url, headers=headers, data=post_data, verify=False)
print(the_response.status_code)
当我使用以下命令从myproject目录运行此代码时:
python post_request.py
我收到201响应,这是我从视图中应该得到的。
有人可以解释为什么不在Django视图中运行时POST请求可以工作,但在视图内部失败的原因?以及我该如何解决?