django URLError at /weather/ <urlopen error no host given>


django项目里app名叫weather,需要从网络直接获取百度的天气api,所以models.py没有定义任何类,只在views.py和urls.py操作,加了个get_weather.py供views.py调用,代码如下:
get_weather.py


 # -*- coding: utf-8 -*-
import sys, urllib, urllib2, json
reload(sys)
sys.setdefaultencoding("utf-8")

def get_weather_pm25(ip):
    url_ip = "http://apis.baidu.com/apistore/iplookupservice/iplookup?ip="+str(ip)
    req_ip = urllib2.Request(url_ip)
    req_ip.add_header("apikey", "1ee9ad85f14e9b4e51b8eeab2daea31f")
    resp_ip = urllib2.urlopen(req_ip)
    content_ip = resp_ip.read()
    print resp_ip
    if(content_ip):
        json_ip = json.loads(content_ip)
        city =json_ip['retData']['city']
        url_pm25 = "http://apis.baidu.com/apistore/aqiservice/aqi?city="+city
        print url_pm25
        req_pm25 = urllib2.Request(url_pm25)
        req_pm25.add_header("apikey", "1ee9ad85f14e9b4e51b8eeab2daea31f")
        resp_pm25 = urllib2.urlopen(req_pm25)
        content_pm25 = resp_pm25.read()
        if(content_pm25):
            return content_pm25
        else:
            return false
    else:
        return false

views.py


 # Create your views here.
from django.shortcuts import render
from django.template import loader, Context
from django.http import HttpResponse
from get_weather import get_weather_pm25
import json

def show_pm25(request):
#    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
#       ip = request.META['HTTP_X_FORWARDED_FOR']
#   else:
#       ip = request.META['REMOTE_ADDR']
    ip = '117.89.35.58'
    pm25_json = get_weather_pm25(ip)
    pm25 = json.loads(pm25_json)
    location = pm25['retData']['city']
    level = pm25['retData']['level']
    aqi = pm25['retData']['aqi']
    t = loader.get_template("weather.html")
    c = Context({'location':location,'level':level,'aqi':aqi})
    return HttpResponse(t.render(c))

runserver后提示的错误为:
URLError at /weather/

Request Method: GET
Request URL: http://127.0.0.1:8000/weather/
Django Version: 1.4
Exception Type: URLError
Exception Value:

Exception Location: /usr/lib64/python2.7/urllib2.py in do_request_, line 1127
Python Executable: /usr/bin/python
Python Version: 2.7.10
Python Path:

['/home/chinesejar/sae/findonweb/1',
'/usr/lib64/python27.zip',
'/usr/lib64/python2.7',
'/usr/lib64/python2.7/plat-linux2',
'/usr/lib64/python2.7/lib-tk',
'/usr/lib64/python2.7/lib-old',
'/usr/lib64/python2.7/lib-dynload',
'/usr/lib64/python2.7/site-packages',
'/usr/lib64/python2.7/site-packages/gtk-2.0',
'/usr/lib/python2.7/site-packages']

Server time: Sat, 27 Jun 2015 18:32:18 +0800

urllib2 python django urllib

想吓死爹啊 9 years, 6 months ago

Your Answer