【问题标题】:Django problem with missing " underscore" in urlurl 中缺少“下划线”的 Django 问题
【发布时间】:2021-10-12 07:00:25
【问题描述】:

我是初学者,需要一点支持。 在应用程序中一切正常,但在表单中输入“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 ' ')

我正在互联网上寻找解决方案,但我自己无法解决。非常感谢大家的帮助

【问题讨论】:

  • 让我们试试 new+york?
  • 你的代码有错别字,res = res = urllib...
  • 我已经更正了谢谢

标签: python django url


【解决方案1】:

您只需将 city 中的空格替换为编码值即可。

试试这个:

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 中编码城市。

【讨论】:

  • 然后得到这个:TypeError at / can only concatenate str (not "set") to str
  • 您可以编辑您的代码以打印值和城市类型吗?
  • 您对替换的建议。当我输入 berlin 时,一切正常,但是当我输入 new york 时,它得到 HTTP 错误 404:未找到
  • 我刚刚检查了它是因为它是无效的 URL,开放的天气 API 在城市名称中没有 _,您必须将空格编码为 %20 才能工作
  • @Tomekr 我已经更新了我的答案,现在应该可以使用了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2011-07-10
  • 2018-10-16
  • 1970-01-01
  • 2016-03-31
相关资源
最近更新 更多