[javascript]py script、pyodide、API 和查询的问题
· 收录于 2024-01-06 16:47:07 · source URL
问题详情
我正在做一个项目,我需要打印天气预报,它似乎没有给出错误代码,但页面是空的。没有任何东西输出你的文本
<!DOCTYPE html>
<html>
<head>
<script defer src="https://pyscript.net/releases/2022.12.1/pyscript.js"></script>
<link rel="stylesheet" href="https://pyscript.net/releases/2022.12.1/pyscript.css"/>
</head>
<body>
<py-script>
import pyodide
import asyncio
API_KEY = '8e4cf478-53b6-45bc-8597-9946db9f1fd5'
url = 'https://api.weather.yandex.ru/v2/forecast'
params = {
'lat': 55.753215,
'lon': 37.622504,
'lang': 'ru_RU'
}
headers = {
'X-Yandex-API-Key': API_KEY
}
async def get_weather():
response = await pyodide.fetch(url=url, params=params, headers=headers, method="GET")
response_dict = await response.json()
data = response.json()
fact = data.get('fact')
temperature = fact.get('temp')
print(f'Погода в Москве: {temperature} градусов по Цельсию')
asyncio.ensure_future(get_weather())
</py-script>
</body>
</html>
最佳回答
您调用了 response.json() 两次。 下面是代码的更正版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Forecast</title>
</head>
<body>
<script type="module">
import asyncio
const API_KEY = '8e4cf478-53b6-45bc-8597-9946db9f1fd5';
const url = 'https://api.weather.yandex.ru/v2/forecast';
const params = {
'lat': 55.753215,
'lon': 37.622504,
'lang': 'ru_RU'
};
const headers = {
'X-Yandex-API-Key': API_KEY
};
async function get_weather() {
const response = await fetch(`${url}?lat=${params.lat}&lon=${params.lon}&lang=${params.lang}`, {
method: 'GET',
headers: headers
});
const data = await response.json();
const fact = data.fact;
const temperature = fact.temp;
console.log(`Погода в Москве: ${temperature} градусов по Цельсию`);
}
get_weather();
</script>
</body>
</html>
删除了不必要的 import 语句。 将 API 参数合并到 URL 中。 使用 fetch 而不是 pyodide.fetch。 删除了对 response.json() 的额外调用。