Python POST 不工作
我正在尝试将 POST 数据从 python 脚本发送到 url。代码如下:
def createperson(self,name=None):
SERVER_BASE_ADDR = 'http://localhost:8000/'
postdata = urllib.urlencode({'name':name})
req = urllib2.Request(SERVER_BASE_ADDR + 'people/add')
fd = urllib2.urlopen(req,postdata)
return name
但这会返回
HTTPError: HTTP Error 500: INTERNAL SERVER ERROR
在 url 上添加一个人就可以了。有什么想法吗?
编辑
服务器端使用 django 装饰器来处理 POST 和 GET。
@require_http_methods(["GET", "POST"])
def add(request):
if request.method == "POST":
#do stuff with post data
上面的python代码不是和在html模板上提交表单一样吗?如果相同,那么处理程序不应该以相同的方式处理它吗?
谢谢,
通过使用解决:
c = urllib2.build_opener()
postdata = urllib.urlencode({'name':name})
r = c.open(url,postdata)
一种不同的方法,但可以完成工作。感谢您的所有回答。
I am trying to send POST data from a python script to a url. Here is the code:
def createperson(self,name=None):
SERVER_BASE_ADDR = 'http://localhost:8000/'
postdata = urllib.urlencode({'name':name})
req = urllib2.Request(SERVER_BASE_ADDR + 'people/add')
fd = urllib2.urlopen(req,postdata)
return name
But this returns
HTTPError: HTTP Error 500: INTERNAL SERVER ERROR
Adding a person on the url is fine. Any ideas?
EDIT
The server side uses django decorators to handle POST and GET.
@require_http_methods(["GET", "POST"])
def add(request):
if request.method == "POST":
#do stuff with post data
Isn't the above python code the same as submitting a form on a html template? If its the same then shouldn't the handlers handle it the same way?
Thank you
Solved by using:
c = urllib2.build_opener()
postdata = urllib.urlencode({'name':name})
r = c.open(url,postdata)
A different approach but does the job. Thank you for all your answers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HTTP 500错误意味着问题不是发生在客户端python脚本上,而是发生在服务器端。
检查你的服务器端代码,也许它只从 GET 读取数据,而不是 POST。
The HTTP 500 error means that the problem doesn't occur on the client-side python script, but on the server side.
Check your server side code, maybe it reads data only from GET, not POST.
HTTP 500 错误绝对是内部服务器错误。正如 @dlutxx 所指出的,问题发生在服务器上。
为了进一步调试这个问题,我认为你应该检查你的 Django 处理程序。如果它确实适用于 GET 请求但不适用于 POST 请求,也许您应该看看 GET 处理程序和 POST 处理程序之间有什么不同。
编辑为使用Python日志框架(根据Django文档)而不是标准输出。
HTTP 500 errors are definitely internal server errors. The problem occurs on the server, as @dlutxx has pointed out.
To debug this further, I think you should examine your Django handler. If it really does work for GET requests but not POST requests, perhaps you should look at what is different between the GET handler and the POST handler.
EDITed to use Python logging framework (per Django docs) instead of stdout.