django HTTP错误500:内部服务器错误

y0u0uwnf  于 2023-03-04  发布在  Go
关注(0)|答案(2)|浏览(234)

我正在尝试用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

编辑:我想让你知道,如果我用浏览器连接到我的应用程序,我可以将数据从另一台计算机发布到我的数据库。

mcdcgff0

mcdcgff01#

您需要获取一个会话cookie,然后读取为该会话生成的cookie。
最好的方法是先获取包含表单的页面,然后保存所有的cookie,你可以使用cookielib来完成这个任务,就像here演示的那样,如果你想让自己的工作更轻松,也可以使用requests来代替urllib,代码就变成a lot simpler了。
要获得CSRF令牌,你可以用BeautifulSoup刮取表单页面。有很多tutorials可以实现这一点,你可以很容易地在谷歌上找到。

5cnsuln7

5cnsuln72#

试试看:

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")

相关问题