如何在db django模型中保存数据?

时间:2016-02-29 20:03:32

标签: python django django-models beautifulsoup

美好的一天,我无法真正理解我在这里做错了什么。我正在使用此功能基本视图使用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]))

2 个答案:

答案 0 :(得分:0)

我会先说你应该清理你的代码。它根本不是模块化的。您应该将端点视图划分为模块化函数,以便更容易阅读。你在变量命名中混合了camelCase和under_score样式,这被认为是糟糕的风格。

完成此操作后,您已准备好继续解决实际问题:)。为此,我希望你熟悉The python debugger。有了它,你可以轻松调试python代码。 Oldschool的方式是在你的代码中插入打印件,但这通常很慢,除非你闻到问题所在。

答案 1 :(得分: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)