我是初學者,需要一點支持。在應用程式中一切正常,但是當它在表單中輸入“new york”時,url 中缺少“_”。
我的代碼是
def index(request):
if request.method == 'POST':
city = request.POST['city']
if city == '':
return redirect('index')
res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid=1b79ea7b1251b76ccda81d6bd').read()
json_data = json.loads(res)
datas = {
"country_code" : str(json_data['sys']['country']),
"cordinate": str(json_data['coord']['lon']) ''
str(json_data['coord']['lat']),
"temp": str(int(json_data['main']['temp']-273)) 'C',
"pressure" : str(json_data['main']['pressure']),
"humidity" : str(json_data['main']['humidity']),
}
作為回應收到“
InvalidURL at /
URL can't contain control characters. '/data/2.5/weather?q=bielsko biala&appid=1b79ea7b1251b76cc0b41a81d6bd' (found at least ' ')
我正在互聯網上尋找解決方案,但我無法自己解決。非常感謝您的幫助
uj5u.com熱心網友回復:
您只需要用編碼值替換城市中的空格。
嘗試這個:
import urllib.parse
res = urllib.request.urlopen(f'http://api.openweathermap.org/data/2.5/weather?q={urllib.parse.quote(city)}&appid=1b79ea7b1251b76ccda81d6bd').read()
這是在 URL 中編碼城市。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318220.html
上一篇:如何從url下載字典?
