Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Good day, I can't really understand what I'm doing wrong in here. I was using this function base view to store my scrap data in the database with the django model, but now it's not saving any more. I can't really understand why. Any idea?

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]))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is definitely a problem with your try/except block. Amusing your code works until the object creation, you should change that part to:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...