【发布时间】:2016-02-23 11:28:38
【问题描述】:
我正在尝试在 Python 中创建一个 POST 请求脚本,它会自动将数据发送到数据库。由于我的 Web 应用程序(用 Django 制作)仍在进行中(在 localhost 上),我尝试通过 IPv4:port 从同一网络上的另一台计算机发送此 POST 请求。
执行此操作时,我收到 HTTP 错误 500:内部服务器错误,并回溯到“response = urllib2.urlopen(req)”行 我的脚本如下所示:
import urllib, urllib2, cookielib
import re
cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)
url_1 = 'http://192.168.1.104:8000/legacy'
req = urllib2.Request(url_1)
rsp = urllib2.urlopen(req)
url_2 = 'http://192.168.1.104:8000/legacy'
params = {
'temperature_max' : '186',
'temperature_min' : '88',
'submit': 'Submit',
}
data = urllib.urlencode(params)
req = urllib2.Request(url_2, data)
response = urllib2.urlopen(req)
the_page = response.read()
pat = re.compile('Title:.*')
print pat.search(the_page).group()
在托管服务器的另一台计算机上,我收到以下错误:
Exception happened during processing of request from ('192.168.1.65', 56996)
Traceback (most recent call last):
File "c:\python27\Lib\SocketServer.py", line 599, in process_request_thread
self.finish_request(request, client_address)
File "c:\python27\Lib\SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Users\Alex\Envs\rango\lib\site-packages\django\core\servers\basehttp.
py", line 129, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "c:\python27\Lib\SocketServer.py", line 657, in __init__
self.finish()
File "c:\python27\Lib\SocketServer.py", line 716, in finish
self.wfile.close()
File "c:\python27\Lib\socket.py", line 283, in close
self.flush()
File "c:\python27\Lib\socket.py", line 307, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 10054] An existing connection was forcibly closed by the remote host
编辑:我想让您知道,如果我使用浏览器连接到我的应用程序,我可以将数据从另一台计算机发布到我的数据库。
【问题讨论】:
-
CSRF 令牌从何而来?你确定它有效吗?
-
因为它是我的网络应用程序,所以我去了我要插入数据的页面,点击“查看源代码”,它就在那里。
-
该令牌可能与会话相关联。但是,您不会复制会话 cookie,否则会使其无效。
-
既然你这么说,我检查了我使用的token和source中显示的token,它们确实是不同的。如果我从脚本中删除令牌,我仍然会收到同样的错误,那么您建议我怎么做?
-
您不能只删除令牌。然后,您必须在后端创建方法
@csrf_exempt。获取表单,提取 CSRF 令牌并发布表单。当然,您需要在请求中保留会话 cookie。阅读 the docs 以了解 CSRF 令牌是什么以及它们的作用。