2016-02-29 49 views
-1

美好的一天,我真的不明白我在这里做错了什么。我正在使用这个功能的基本视图来存储我的报废数据与django模型的数据库,但现在它不再保存。我不明白为什么。任何想法?如何在db django模型中保存数据?

def weather_fetch(request): 
    context = None 
    corrected_rainChance = None 
    url = 'http://weather.news24.com/sa/cape-town' 
    extracted_city = url.split('/')[-1] 
    city = extracted_city.replace('-', " ") 
    print(city) 
    url_request = urlopen(url) 
    soup = BeautifulSoup(url_request.read(), 'html.parser') 
    city_list = soup.find(id="ctl00_WeatherContentHolder_ddlCity") 
    city_as_on_website = city_list.find(text=re.compile(city, re.I)).parent 
    cityId = city_as_on_website['value'] 
    json_url = "http://weather.news24.com/ajaxpro/TwentyFour.Weather.Web.Ajax,App_Code.ashx" 

    headers = { 
     'Content-Type': 'text/plain; charset=UTF-8', 
     'Host': 'weather.news24.com', 
     'Origin': 'http://weather.news24.com', 
     'Referer': url, 
     'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/48.0.2564.82 Chrome/48.0.2564.82 Safari/537.36', 
     'X-AjaxPro-Method': 'GetCurrentOne'} 

    payload = { 
     "cityId": cityId 
    } 
    request_post = requests.post(json_url, headers=headers, data=json.dumps(payload)) 
    data = re.sub(r"new Date\(Date\.UTC\((\d+),(\d+),(\d+),(\d+),(\d+),(\d+),(\d+)\)\)", convert_date, request_post.text) 
    data = data.strip(";/*") 
    data = json.loads(data) 
    forecast = data['Forecast'] 
    if forecast["Rainfall"] == '*': 
     rainChance = 0 
     corrected_rainChance = rainChance 
    else: 
     try: 
      obj = WeatherData.objects.get_or_create(
       min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"], 
       date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance 
      ) 
     except WeatherData.DoesNotExist: 
      obj = WeatherData.objects.get_or_create(
       min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"], 
       date=forecast["Date"], wind_speed=forecast["WindSpeed"], 
       rain=corrected_rainChance 
      ) 
      obj.save() 
      context = {'context': obj} 
      print(context) 
    return render(request, 'forecastApp/pages/fetch_weather.html', context) 

class WeatherData(models.Model): 
    date = models.DateTimeField(default=timezone.now) 
    wind_speed = models.DecimalField(max_digits=3, decimal_places=1) 
    high_temp = models.DecimalField(max_digits=3, decimal_places=1) 
    min_temp = models.DecimalField(max_digits=3, decimal_places=1) 
    rain = models.IntegerField(default=0) 

    def __str__(self): 
     return ' '.join(str([self.date.month, self.date.day, self.date.year])) 
+0

你什么确切改变? “它不是储蓄”是什么意思? - 你是否遇到错误,或者你在数据库中找不到对象? – ben432rew

+0

另外,你可以发布你的'WeatherData'类定义吗? – ben432rew

+0

@ ben432rew我可以说的是我看不到任何东西在我的数据库中,而当我打印上下文时它没有任何问题 –

回答

0

你的try/except块肯定有问题。有趣的代码工作,直到对象创建,你应该改变该部分:

if forecast["Rainfall"] == '*': 
    rainChance = 0 
    corrected_rainChance = rainChance 
else: 
    obj = WeatherData.objects.get_or_create(
      min_temp=forecast["LowTemp"], high_temp=forecast["HighTemp"], 
      date=forecast["Date"], wind_speed=forecast["WindSpeed"], rain=corrected_rainChance 
     ) 
    # obj.save() --> you don't need to save the obj again. 
    context = {'context': obj} 
    print(context) 
+0

这就是问题所在这个接近也没有工作。它不保存 –

+0

这种情况下'context'的输出是什么? – ilse2005

+0

没什么,它甚至不打印。但我现在保存这样做rainChance = 0 corrected_rainChance = rainChance obj = WeatherData.objects.get_or_create( min_temp = forecast [“LowTemp”],high_temp = forecast [“HighTemp”], date = forecast [“”日期“],wind_speed = forecast [”WindSpeed“],rain = corrected_rainChance ) context = {'context':obj} return render(request,'forecastApp/pages/fetch_weather.html',context) –

0

我会说你应该先清理你的代码。它确实没有看起来是模块化的。您应该将端点视图划分为模块化函数,以便读取更容易。你在变量命名中混合了camelCase和under_score风格,这被认为是不好的风格。

完成此操作后,您就可以开始讨论实际问题了:)。为此,我希望你熟悉The python debugger。有了这个,你可以轻松地调试Python代码。 Oldschool的方式是在你的代码中插入打印件,但通常很慢,除非你嗅到问题出在哪里。

+0

我不知道它是否真的不同,但我使用django-debug-toolbar进行调试 –