示例#1
0
    def check_sinoptik(self):
        """Check and process weather data from sinoptik.ua."""
        date = datetime.strftime(datetime.now(), "%Y-%m-%d")
        last_update = UpdateDay.objects.all().filter(id=1).first()
        if (last_update is None) or (last_update.day != date):
            weather = Sinoptik()
            if weather.load():
                weather.get_weather()

                weather_db = Weather.objects.all().filter(id=1).first()
                if weather_db is None:
                    weather_db = Weather(
                        today=weather.today_str(),
                        days=weather.days_str(),
                        water=weather.water_str(),
                        infoDaylight=weather.infoDaylight_str(),
                        warnings=weather.warnings,
                        description=weather.description)
                else:
                    weather_db.today = weather.today_str()
                    weather_db.days = weather.days_str()
                    weather_db.water = weather.water_str()
                    weather_db.infoDaylight = weather.infoDaylight_str()
                    weather_db.warnings = weather.warnings
                    weather_db.description = weather.description
                weather_db.save()

                if last_update is None:
                    last_update = UpdateDay(day=date)
                else:
                    last_update.day = date
                last_update.save()
示例#2
0
def update(request):
    action = 'update'
    #title = '更新'
    try :                
        phone_num = request.session['update_phone_num']
        u = User.objects.get(phone_num=phone_num)
        msg = {'phone_num':u.phone_num, 'fid':u.fid}    
        msg['area'] = u.wid
        msg['sub_type'] = User.TYPE_CHOICES[0][1] if u.sub_type == User.TYPE_CHOICES[0][0] else User.TYPE_CHOICES[1][1]
        t = loader.get_template('user_info.html')
        msg = t.render(Context({'msg':msg}))
        if request.method == 'POST':
            #post_args = request.POST
            #post_args['phone_num'] = phone_num
            form = UpdateSubForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                #执行更新逻辑
                                
                try:
                    weather = Weather.objects.get(cid=cd['city'], hour=cd['hour'])
                except Weather.DoesNotExist:
                    city = City.objects.get(cid=cd['city'])
                    weather = Weather(cid=city, hour=cd['hour'])
                    weather.save()
                
                #更改订阅类型
                u.wid = weather
                u.sub_type = cd['sub_type']
                u.save()
                
                request.session['announce'] = u'更改成功'
                Log(level=2,event=u'%s:%s' % (u.phone_num,request.session['announce'])).save()
                request.session['user'] = u
                #if not settings.DEBUG:   
                del request.session['update_phone_num']        
                return HttpResponseRedirect('/weather/announce/')
                                                
            #表单字段无效时
            else:
                pass
        else:
            default_hour = int(strftime('%H')) + 1
            form = UpdateSubForm(initial={'hour':default_hour, 'sub_type':'E'}) #定义字段的option默认值
        return render_to_response('index.html', {'form':form, 'msg':msg, 'action':action,'form_id':'subscribe'}, context_instance=RequestContext(request))
    except Exception, e:
        #print Exception
        #raise e
        raise Http404('非法请求')
示例#3
0
def add_new_weather(currentCity,pm25,data,Picture,the_weather,temperature,today_or_future=1):
    """
    currentCity:城市名
    pm25:PM25值
    data:日期
    Picture:图片
    the_weather:天气
    temperature:温度
    today_or_future=1:今天还是未来(今天为:1,未来为:2),默认为今天
    :return:
    """
    weather = Weather()  # 实例化新的天气
    weather.currentCity = currentCity
    weather.pm25 = pm25
    weather.data = data
    weather.Picture = Picture
    weather.the_weather = the_weather
    weather.temperature = temperature
    weather.today_or_future = today_or_future
    weather.save()
示例#4
0
def index(request):
    msg = '请先填写手机号码和订阅信息, 天气短信将发送到你的手机。'
    if request.method == 'POST':
        form = SubscribeForm(request.POST)            
        if form.is_valid():
            fid = form.fid
            cd = form.cleaned_data
            
            
            #向天气订阅表增加记录或找出指定城市的订阅实例
            try:
                weather = Weather.objects.get(cid=cd['city'], hour=cd['hour'])
            except Weather.DoesNotExist:
                city = City.objects.get(cid=cd['city'])
                weather = Weather(cid=city, hour=cd['hour'])
                weather.save()
            
            #发送加为好友的短信
            ft = MyFetion(PHONE,PSW)
            add_res = ft.addfriend(cd['phone_num'], NICK, '2')
            if add_res:
                Log(level=2,event='success to send adding friend sms to %s' % cd['phone_num']).save()
            else:
                Log(level=1,event='failed to send adding friend sms to %s ,maybe he/she has been your friend.' % cd['phone_num']).save()

            #用户与天气订阅表关联,仅使用新增            
            user = User(fid=fid, phone_num=cd['phone_num'], wid=weather, sub_type=cd['sub_type'], active=True)
            user.save()            
            
            if add_res:
                msg = '你将收到一条"%s"的好友请求短信,请于24小时内确认,逾期无效' %  NICK
            else:
                msg = '订制成功'
            form = None
    
    else:    
        default_hour = int(strftime('%H')) + 1
        form = SubscribeForm(initial={'hour':default_hour, 'sub_type':'E'}) #定义字段的option默认值        
    return render_to_response('index.html', {'form':form, 'msg':msg, 'form_id':'subscribe'}, context_instance=RequestContext(request))
示例#5
0
    def handle(self, *args, **options):

        channel_layer = channels.layers.get_channel_layer()
        for location in options["location"]:
            res = requests.get(
                "http://wttr.in/%s?0" % location,
                headers={
                    "User-Agent":
                    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
                },
            )
            if res.status_code == 200:
                try:
                    weather = Weather.objects.get(location=location)
                except Weather.DoesNotExist:
                    weather = Weather(location=location)
                data_start_index = res.text.find("<pre>")
                data_end_index = res.text.find("</pre>", data_start_index)
                if data_start_index < 0 or data_end_index < 0:
                    self.stdout.write(
                        self.style.ERROR(
                            'Failed fetch weather of location "%s"' %
                            location))
                    continue
                weather.data = res.text[data_start_index +
                                        len("<pre>"):data_end_index]
                weather.save()
                async_to_sync(channel_layer.group_send)("weather", {
                    "type": "weather_message",
                    "message": "update"
                })
            else:
                self.stdout.write(
                    self.style.ERROR('Failed fetch weather of location "%s"' %
                                     location))

            self.stdout.write(
                self.style.SUCCESS('Success fetch weather of location "%s"' %
                                   location))