雅虎天气API 2019类型错误/属性

2024-04-27 01:00:50 发布

您现在位置:Python中文网/ 问答频道 /正文

想在python3.5.3的Raspberry Pi上运行Yahoo 2019天气API。
通过成功运行Yahoo 2.7.10的示例代码验证了Yahoo访问代码。在

所有示例代码: https://gist.github.com/VerizonMediaOwner/e6be950f74c5a8071329f1d9a50e3158#file-weather_ydn_sample-py

运行2to3转换并收到指示的以下脚本类型错误:

#Weather API Python sample code**
#Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see
#https://opensource.org/licenses/Zlib for terms.**
#$ python --version**
#Python 2.7.10 - AFTER 2TO 3 CONVERSION**

import time, uuid, urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
import hmac, hashlib
from base64 import b64encode

#Basic info

url = 'https://weather-ydn-yql.media.yahoo.com/forecastrss'
method = 'GET'
app_id = 'XXX'
consumer_key = 'XXX'
consumer_secret = 'XXX'
concat = '&'
query = {'location': 'sunnyvale,ca', 'format': 'json'}
oauth = {
    'oauth_consumer_key': consumer_key,
    'oauth_nonce': uuid.uuid4().hex,
    'oauth_signature_method': 'HMAC-SHA1',
    'oauth_timestamp': str(int(time.time())),
    'oauth_version': '1.0'
}

#Prepare signature string (merge all params and SORT them)

merged_params = query.copy()
merged_params.update(oauth)
sorted_params = [k + '=' + urllib.parse.quote(merged_params[k], safe='') for k in sorted(merged_params.keys())]
signature_base_str =  method + concat + urllib.parse.quote(url, safe='') + concat + urllib.parse.quote(concat.join(sorted_params), safe='')

#Generate signature

composite_key = urllib.parse.quote(consumer_secret, safe='') + concat
oauth_signature = b64encode(hmac.new(composite_key, signature_base_str, hashlib.sha1).digest())

#Prepare Authorization header

oauth['oauth_signature'] = oauth_signature
auth_header = 'OAuth ' + ', '.join(['{}="{}"'.format(k,v) for k,v in oauth.items()])

#Send request

url = url + '?' + urllib.parse.urlencode(query)
request = urllib.request.Request(url)
request.add_header('Authorization', auth_header)
request.add_header('X-Yahoo-App-Id', app_id)
response = urllib.request.urlopen(request).read()
print(response)

ERROR:
pi@raspberrypi:~/Weather $ python3 yahoo2TO3.py
Traceback (most recent call last):
  File "yahoo2.py", line 41, in <module>
    oauth_signature = b64encode(hmac.new(composite_key, signature_base_str, hashlib.sha1).digest())
  File "/usr/lib/python3.5/hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib/python3.5/hmac.py", line 42, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'

尝试了3.7代码示例并收到AttributeError:

^{pr2}$

请求帮助运行3.5中的一个或另一个。在


Tags: keyinpyurlconsumerparserequestparams
1条回答
网友
1楼 · 发布于 2024-04-27 01:00:50

决议: 在python3.7的示例代码中,将头import urllib更改为import urllib.request。在这个改变之后,使用Raspberry pipython3.5.3就可以正常工作了。在

相关问题 更多 >