我试图在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
编辑:如果我使用浏览器连接到我的应用程序,我想告诉您我可以将数据从其他计算机发布到我的数据库。
答案 0 :(得分:0)
您需要获取会话cookie,然后阅读该会话生成的cookie。
最好的方法是首先使用表单获取页面,保存所有cookie。您可以使用cookielib作为演示here。如果你想让自己的生活更轻松,也可以使用请求而不是urllib。然后代码变为a lot simpler。
要获取CSRF令牌,您可以使用BeautifulSoup抓取表单页面。您可以在Google上轻松找到很多tutorials。
答案 1 :(得分:-1)
试试:
import urllib.request
from urllib.error import HTTPError
url = "<enter_URL_here>"
try:
res = urllib.request.urlopen(url)
except HTTPError as e:
content = e.read()
print("HTTP error encountered while reading URL")