Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 雅虎2019年天气API-类型错误/属性错误_Python_Python 3.x_Yahoo Weather Api - Fatal编程技术网

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

Python 雅虎2019年天气API-类型错误/属性错误,python,python-3.x,yahoo-weather-api,Python,Python 3.x,Yahoo Weather Api,希望在Python 3.5.3中的Raspberry Pi上运行Yahoo 2019天气API。 通过成功运行Yahoo 2.7.10的示例代码验证了Yahoo访问代码 所有示例代码均来自: 运行2to3转换并收到以下脚本类型错误指示: #Weather API Python sample code** #Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see #https://opensource.o

希望在Python 3.5.3中的Raspberry Pi上运行Yahoo 2019天气API。
通过成功运行Yahoo 2.7.10的示例代码验证了Yahoo访问代码

所有示例代码均来自:

运行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'
#天气API Python示例代码**
#版权所有2019宣誓公司根据zLib许可证条款获得许可,请参见
#https://opensource.org/licenses/Zlib 关于条款**
#$python—版本**
#Python 2.7.10-经过2到3的转换**
导入时间,uuid,urllib.request,urllib.parse,urllib.error,urllib.request,urllib.error,urllib.parse
导入hmac、hashlib
从base64导入b64encode
#基本信息
url='1〕https://weather-ydn-yql.media.yahoo.com/forecastrss'
方法='GET'
app_id='XXX'
消费者密钥='XXX'
消费者机密='XXX'
concat='&'
查询={'location':'sunnyvale,ca','format':'json'}
oauth={
“oauth_consumer_key”:consumer_key,
'oauth_nonce':uuid.uuid4().hex,
“oauth_签名_方法”:“HMAC-SHA1”,
'oauth_timestamp':str(int(time.time()),
“oauth_版本”:“1.0”
}
#准备签名字符串(合并所有参数并对其排序)
merged_params=query.copy()
合并参数更新(oauth)
排序的参数=[k+'='+urllib.parse.quote(合并的参数[k],安全=''),用于排序的k(合并的参数.keys())]
signature_base_str=method+concat+urllib.parse.quote(url,safe='')+concat+urllib.parse.quote(concat.join(排序参数),safe='')
#生成签名
composite_key=urllib.parse.quote(consumer_secret,safe='')+concat
oauth_signature=b64encode(hmac.new(复合_密钥,signature_base_str,hashlib.sha1.digest())
#准备授权标头
oauth['oauth_签名']=oauth_签名
auth_头='OAuth'+','.join(['{}=“{}”。格式(k,v)表示OAuth.items()中的k,v)
#发送请求
url=url+'?'+urllib.parse.urlencode(查询)
request=urllib.request.request(url)
请求。添加标题(“授权”,认证标题)
请求。添加标题('X-Yahoo-App-Id',App\U Id)
response=urllib.request.urlopen(request.read())
打印(答复)
错误:
pi@raspberrypi:~/Weather$python3 yahoo2TO3.py
回溯(最近一次呼叫最后一次):
文件“yahoo2.py”,第41行,在
oauth_signature=b64encode(hmac.new(复合_密钥,signature_base_str,hashlib.sha1.digest())
文件“/usr/lib/python3.5/hmac.py”,第144行,新格式
返回HMAC(键、消息、digestmod)
文件“/usr/lib/python3.5/hmac.py”,第42行,在__
raise TypeError(“键:应为字节或字节数组,但获得了%r”%type(键)。\uuuu name\uuuu)
TypeError:key:应为字节或bytearray,但得到'str'
尝试了3.7代码示例并收到AttributeError:

#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 3.7.x

import time, uuid, urllib, json
import hmac, hashlib
from base64 import b64encode

#Basic info

app_id = 'XXX'
consumer_key = 'XXX'
consumer_secret = 'XXX'
query = {'location': 'macau,mo', 'format': 'json', 'u': 'c'}

url = 'https://weather-ydn-yql.media.yahoo.com/forecastrss'
method = 'GET'
concat = '&'
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.encode('utf-8'), signature_base_str.encode('utf-8'), hashlib.sha1).digest())
#Prepare Authorization header

oauth['oauth_signature'] = oauth_signature.decode('utf-8')
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.headers['Authorization'] = auth_header
request.headers['X-Yahoo-App-Id']= app_id
response = urllib.request.urlopen(request).read()
print(response)

ERROR:
pi@raspberrypi:~/Weather3 $ python3 yahoo3.py
Traceback (most recent call last):
  File "yahoo3.py", line 34, in <module>
    sorted_params = [k + '=' + urllib.parse.quote(merged_params[k], safe='') for k in sorted(merged_params.keys())]
  File "yahoo3.py", line 34, in <listcomp>
    sorted_params = [k + '=' + urllib.parse.quote(merged_params[k], safe='') for k in sorted(merged_params.keys())]
AttributeError: module 'urllib' has no attribute 'parse'
#天气API Python示例代码
#版权所有2019宣誓公司根据zLib许可证条款获得许可,请参见#https://opensource.org/licenses/Zlib 关于条款。
#$python—版本
#Python 3.7.x
导入时间、uuid、urllib、json
导入hmac、hashlib
从base64导入b64encode
#基本信息
app_id='XXX'
消费者密钥='XXX'
消费者机密='XXX'
查询={'location':'macau,mo','format':'json','u':'c'}
url='1〕https://weather-ydn-yql.media.yahoo.com/forecastrss'
方法='GET'
concat='&'
oauth={
“oauth_consumer_key”:consumer_key,
'oauth_nonce':uuid.uuid4().hex,
“oauth_签名_方法”:“HMAC-SHA1”,
'oauth_timestamp':str(int(time.time()),
“oauth_版本”:“1.0”
}
#准备签名字符串(合并所有参数并对其排序)
merged_params=query.copy()
合并参数更新(oauth)
排序的参数=[k+'='+urllib.parse.quote(合并的参数[k],安全=''),用于排序的k(合并的参数.keys())]
signature_base_str=method+concat+urllib.parse.quote(url,safe='')+concat+urllib.parse.quote(concat.join(排序参数),safe='')
#生成签名
composite_key=urllib.parse.quote(consumer_secret,safe='')+concat
oauth_signature=b64encode(hmac.new(composite_key.encode('utf-8')、signature_base_str.encode('utf-8')、hashlib.sha1.digest())
#准备授权标头
oauth['oauth_签名']=oauth_签名。解码('utf-8')
auth_头='OAuth'+','.join(['{}=“{}”。格式(k,v)表示OAuth.items()中的k,v)
#发送请求
url=url+'?'+urllib.parse.urlencode(查询)
request=urllib.request.request(url)
request.headers['Authorization']=auth_header
request.headers['X-Yahoo-App-Id']=App\u Id
response=urllib.request.urlopen(request.read())
打印(答复)
错误:
pi@raspberrypi:~/Weather3$python3 yahoo3.py
回溯(最近一次呼叫最后一次):
文件“yahoo3.py”,第34行,在
排序的参数=[k+'='+urllib.parse.quote(合并的参数[k],安全=''),用于排序的k(合并的参数.keys())]
文件“yahoo3.py”,第34行,在
排序的参数=[k+'='+urllib.parse.quote(合并的参数[k],安全=''),用于排序的k(合并的参数.keys())]
AttributeError:模块“urllib”没有属性“parse”
请求帮助运行3.5中的一个或另一个。

已解决:
在Python 3.7的示例代码中,将标题
import-urllib
更改为
import-urllib.request
。在进行此更改之后,使用Raspberry Pi Python 3.5.3它就可以正常工作。

为什么不使用中的请求作为HTTP客户端库?我相信你的建议是正确的。我在Python3中添加了请求库,并在测试文件的头部添加了“导入请求”。我已经研究并尝试了各种配置,但不断得到“TypeError:“tuple”对象是不可调用的。这可能与试图传递三个安全代码Id、Key和Secret来访问文件有关?