TypeError:urlopen()得到了一个意外的关键字参数' headers'

时间:2015-08-18 11:36:41

标签: python celery urllib2 pyramid urlopen

我使用rest api发送推送通知。 文档are here. 我使用金字塔并使用芹菜安排这些推送通知。

这是我的代码示例:

result = urllib2.urlopen(urlRequest, headers={
      "X-Parse-Application-Id": settings["parse.application.id"],
      "X-Parse-REST-API-Key": settings["parse.restapi.key"],
      "Content-Type": "application/json"
     })

connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()

connection.request('POST', '/1/push', json.dumps(data), )
result = json.loads(connection.getresponse().read())

但是芹菜记录了这个错误:

2015-08-18 16:39:45,092 INFO  [celery.worker.strategy][MainThread] Received task: app_v1_1.tasks.push_notification[877906d8-1ea7-4b1f-8a54-aa61bffb40e8]
2015-08-18 16:39:45,094 ERROR [celery.worker.job][MainThread] Task app_v1_1.tasks.push_notification[877906d8-1ea7-4b1f-8a54-aa61bffb40e8] raised unexpected: TypeError("urlopen() got an unexpected keyword argument 'headers'",)
Traceback (most recent call last):
  File "/home/apnistreet/work/ve/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/home/comp/work/ve/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/home/comp/work/site/code/apnistreet_v1_1/tasks.py", line 168, in push_notification
    # "Content-Type": "application/json"
TypeError: urlopen() got an unexpected keyword argument 'headers'

有什么问题?

2 个答案:

答案 0 :(得分:6)

urllib2.urlopen没有名为headers的参数:

  

urllib2.urlopen :( url,data = None,timeout = socket._GLOBAL_DEFAULT_TIMEOUT)

     

打开URL网址,可以是字符串或请求对象。

使用urllib2.Request传递headers

req = urllib2.Request(url, headers={
      "X-Parse-Application-Id": settings["parse.application.id"],
      "X-Parse-REST-API-Key": settings["parse.restapi.key"],
      "Content-Type": "application/json"
     })
result = urllib2.urlopen(req)

答案 1 :(得分:3)

<强>问题

方法urllib2.urlopen没有headers参数。这是错误消息

所指示的内容
  

TypeError:urlopen()得到了一个意外的关键字参数&#39; headers&#39;

<强>解决方案

connection.request是您定义headers

的地方

有关示例,请参阅this answer