forked from guiguiabloc/api-domogeek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apidomogeek.py
1437 lines (1332 loc) · 50.6 KB
/
apidomogeek.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Gruik coded by GuiguiAbloc
# http://blog.guiguiabloc.fr
# http://api.domogeek.fr
#
import web, sys, time
import json,hashlib,socket
from datetime import datetime,date,timedelta
import urllib, urllib2
from Daemon import Daemon
from xml.dom.minidom import parseString
import Holiday
import ClassTempo
import ClassSchoolCalendar
import ClassVigilance
import ClassGeoLocation
import ClassDawnDusk
import ClassWeather
import ClassEJP
# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)
school = ClassSchoolCalendar.schoolcalendar()
dayrequest = Holiday.jourferie()
temporequest = ClassTempo.EDFTempo()
vigilancerequest = ClassVigilance.vigilance()
geolocationrequest = ClassGeoLocation.geolocation()
dawnduskrequest = ClassDawnDusk.sunriseClass()
weatherrequest = ClassWeather.weather()
ejprequest = ClassEJP.EDFejp()
##########
# CONFIG #
##########
listenip = "0.0.0.0"
listenport = "80"
localapiurl= "http://api.domogeek.fr"
googleapikey = ''
bingmapapikey = ''
geonameskey = ''
worldweatheronlineapikey = ''
redis_host = "127.0.0.1"
redis_port = 6379
##############
# END CONFIG #
##############
##############
# Test REDIS #
##############
try:
import redis
except:
print "No Redis module : https://pypi.python.org/pypi/redis/"
sys.exit(1)
rc= redis.Redis(host=redis_host, port=redis_port)
rc.set("test", "ok")
rc.expire("test" ,10)
value = rc.get("test")
if value is None:
print "Could not connect to Redis " + redis_host + " port " + redis_port
web.config.debug = False
urls = (
'/holiday/(.*)', 'holiday',
'/tempoedf/(.*)', 'tempoedf',
'/ejpedf/(.*)', 'ejpedf',
'/schoolholiday/(.*)', 'schoolholiday',
'/weekend/(.*)', 'weekend',
'/holidayall/(.*)', 'holidayall',
'/vigilance/(.*)', 'vigilance',
'/geolocation/(.*)', 'geolocation',
'/sun/(.*)', 'dawndusk',
'/weather/(.*)', 'weather',
'/season(.*)', 'season',
'/myip(.*)', 'myip',
'/feastedsaint/(.*)', 'feastedsaint',
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
# redirect to the static file ...
raise web.seeother('/static/index.html')
"""
@api {get} /holiday/:date/:responsetype Holiday Status Request
@apiName GetHoliday
@apiGroup Domogeek
@apiDescription Ask to know if :date is a holiday
@apiParam {String} now Ask for today.
@apiParam {String} tomorrow Ask for tomorrow.
@apiParam {String} all Ask for all entry.
@apiParam {Datetime} D-M-YYYY Ask for specific date.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
Jour de Noel
HTTP/1.1 200 OK
no
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/holiday/now
curl http://api.domogeek.fr/holiday/now/json
curl http://api.domogeek.fr/holiday/all
curl http://api.domogeek.fr/holiday/25-12-2014/json
"""
class holiday:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /holiday/{now|tomorrow|date(D-M-YYYY)}\n"
try:
format = request[1]
except:
format = None
if request[0] == "now":
datenow = datetime.now()
year = datenow.year
month = datenow.month
day = datenow.day
result = dayrequest.estferie([day,month,year])
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": result})
else:
return result
if request[0] == "tomorrow":
datenow = datetime.now()
datetomorrow = datenow + timedelta(days=1)
year = datetomorrow.year
month = datetomorrow.month
day = datetomorrow.day
result = dayrequest.estferie([day,month,year])
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": result})
else:
return result
if request[0] == "all":
datenow = datetime.now()
year = datenow.year
listvalue = []
F, J, L = dayrequest.joursferies(year,1,'/')
for i in xrange(0,len(F)):
result = F[i], "%10s" % (J[i]), L[i]
listvalue.append(result)
response = json.dumps(listvalue)
return response
if request[0] != "now" and request[0] != "all" and request[0] != "tomorrow":
try:
daterequest = request[0]
result = daterequest.split('-')
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
try:
day = int(result[0])
month = int(result[1])
year = int(result[2])
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
if day > 31 or month > 12:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
result = dayrequest.estferie([day,month,year])
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": result})
else:
return result
"""
@api {get} /weekend/:daterequest/:responsetype Week-end Status Request
@apiName GetWeekend
@apiGroup Domogeek
@apiDescription Ask to know if :daterequest is a week-end day
@apiParam {String} daterequest Ask for specific date {now | tomorrow | D-M-YYYY}.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
True
HTTP/1.1 200 OK
False
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/weekend/now
curl http://api.domogeek.fr/weekend/tomorrow
curl http://api.domogeek.fr/weekend/now/json
curl http://api.domogeek.fr/weekend/16-07-2014/json
"""
class weekend:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /weekend/{now|tomorrow|date(D-M-YYYY)}\n"
try:
format = request[1]
except:
format = None
if request[0] == "now":
datenow = datetime.now()
daynow = datetime.now().weekday()
day = datenow.day
if daynow == 5 or daynow == 6:
result = "True"
else:
result = "False"
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"weekend": result})
else:
return result
if request[0] == "tomorrow":
today = date.today()
datetomorrow = today + timedelta(days=1)
day = datetomorrow.weekday()
if day == 5 or day == 6:
result = "True"
else:
result = "False"
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"weekend": result})
else:
return result
if request[0] != "now" and request[0] != "tomorrow":
try:
daterequest = request[0]
day,month,year = daterequest.split('-')
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
try:
int(day)
int(month)
int(year)
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
requestday = date(int(year),int(month),int(day)).weekday()
if requestday == 5 or requestday == 6:
result = "True"
else:
result = "False"
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"weekend": result})
else:
return result
"""
@api {get} /holidayall/:zone/:daterequest All Holidays Status Request
@apiName GetHolidayall
@apiGroup Domogeek
@apiDescription Ask to know if :daterequest is a holiday, school holiday and week-end day
@apiParam {String} zone School Zone (A, B or C).
@apiParam {String} daterequest Ask for specific date {now | tomorrow | D-M-YYYY}.
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{"holiday": "False", "weekend": "False", "schoolholiday": "Vacances de printemps - Zone A"}
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/holidayall/A/now
curl http://api.domogeek.fr/holidayall/A/tomorrow
curl http://api.domogeek.fr/holidayall/B/25-02-2014
"""
class holidayall:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /holidayall/{zone}/{now|tomorrow|date(D-M-YYYY)}\n"
try:
zone = request[0]
except:
return "Incorrect request : /holidayall/{zone}/{now|tomorrow|date(D-M-YYYY)}\n"
try:
zoneok = str(zone.upper())
except:
return "Wrong Zone (must be A, B or C)"
if len(zoneok) > 1:
return "Wrong Zone (must be A, B or C)"
if zoneok not in ["A","B","C"]:
return "Incorrect request : /holidayall/{zone}/{now|tomorrow|date(D-M-YYYY)}\n"
try:
daterequest = request[1]
except:
return "Incorrect request : /holidayall/{zone}/{now|tomorrow|date(D-M-YYYY)}\n"
if request[1] == "now":
try:
responseholiday = urllib2.urlopen(localapiurl+'/holiday/now')
responseschoolholiday = urllib2.urlopen(localapiurl+'/schoolholiday/'+zoneok+'/now')
responseweekend = urllib2.urlopen(localapiurl+'/weekend/now')
resultholiday = responseholiday.read()
resultschoolholiday = responseschoolholiday.read()
resultschoolholidays = resultschoolholiday.decode('utf-8')
resultweekend = responseweekend.read()
except:
return "no data available"
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": resultholiday, "schoolholiday": resultschoolholidays, "weekend": resultweekend}, ensure_ascii=False).encode('utf8')
if request[1] == "tomorrow":
try:
responseholiday = urllib2.urlopen(localapiurl+'/holiday/tomorrow')
responseschoolholiday = urllib2.urlopen(localapiurl+'/schoolholiday/'+zoneok+'/tomorrow')
responseweekend = urllib2.urlopen(localapiurl+'/weekend/tomorrow')
resultholiday = responseholiday.read()
resultschoolholiday = responseschoolholiday.read()
resultschoolholidays = resultschoolholiday.decode('utf-8')
resultweekend = responseweekend.read()
except:
return "no data available"
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": resultholiday, "schoolholiday": resultschoolholidays, "weekend": resultweekend}, ensure_ascii=False).encode('utf8')
if request[1] != "now" and request[1] != "tomorrow":
try:
daterequest = request[1]
day,month,year = daterequest.split('-')
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
try:
int(day)
int(month)
int(year)
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
try:
responseholiday = urllib2.urlopen(localapiurl+'/holiday/'+daterequest)
responseschoolholiday = urllib2.urlopen(localapiurl+'/schoolholiday/'+zoneok+'/'+daterequest)
responseweekend = urllib2.urlopen(localapiurl+'/weekend/'+daterequest)
resultholiday = responseholiday.read()
resultschoolholiday = responseschoolholiday.read()
resultschoolholidays = resultschoolholiday.decode('utf-8')
resultweekend = responseweekend.read()
except:
return "no data available"
web.header('Content-Type', 'application/json')
return json.dumps({"holiday": resultholiday, "schoolholiday": resultschoolholidays, "weekend": resultweekend}, ensure_ascii=False).encode('utf8')
"""
@api {get} /tempoedf/:date/:responsetype Tempo EDF color Request
@apiName GetTempo
@apiGroup Domogeek
@apiDescription Ask the EDF Tempo color
@apiParam {String} now Ask for today.
@apiParam {String} tomorrow Ask for tomorrow.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 03 Jul 2014 17:16:47 GMT
Server: localhost
{"tempocolor": "bleu"}
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/tempoedf/now
curl http://api.domogeek.fr/tempoedf/now/json
curl http://api.domogeek.fr/tempoedf/tomorrow
curl http://api.domogeek.fr/tempoedf/tomorrow/json
"""
class tempoedf:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /tempoedf/{now | tomorrow}\n"
try:
format = request[1]
except:
format = None
if request[0] == "now":
try:
rediskeytemponow = hashlib.md5("temponow").hexdigest()
gettemponow = rc.get(rediskeytemponow)
if gettemponow is None:
result = temporequest.TempoToday()
rediskeytemponow = hashlib.md5("temponow").hexdigest()
rc.set(rediskeytemponow, result, 1800)
rc.expire(rediskeytemponow ,1800)
print "SET TEMPO NOW IN REDIS"
else:
result = gettemponow
print "FOUND TEMPO NOW IN REDIS"
except:
result = temporequest.TempoToday()
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"tempocolor": result})
else:
return result
if request[0] == "tomorrow":
try:
rediskeytempotomorrow = hashlib.md5("tempotomorrow").hexdigest()
gettempotomorrow = rc.get(rediskeytempotomorrow)
if gettempotomorrow is None:
result = temporequest.TempoTomorrow()
rediskeytempotomorrow = hashlib.md5("tempotomorrow").hexdigest()
rc.set(rediskeytempotomorrow, result, 1800)
rc.expire(rediskeytempotomorrow ,1800)
print "SET TEMPO TOMORROW IN REDIS"
else:
result = gettempotomorrow
print "FOUND TEMPO TOMORROW IN REDIS"
except:
result = temporequest.TempoTomorrow()
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"tempocolor": result})
else:
return result
web.badrequest()
return "Incorrect request : /tempoedf/{now | tomorrow}\n"
"""
@api {get} /schoolholiday/:zone/:daterequest/:responsetype School Holiday Status Request
@apiName GetSchoolHoliday
@apiGroup Domogeek
@apiDescription Ask to know if :daterequest is a school holiday (UTF-8 response)
@apiParam {String} zone School Zone (A, B or C).
@apiParam {String} daterequest Ask for specific date {now | all | D-M-YYYY}.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
Vacances de la Toussaint
HTTP/1.1 200 OK
False
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/schoolholiday/A/now
curl http://api.domogeek.fr/schoolholiday/A/now/json
curl http://api.domogeek.fr/schoolholiday/A/all
curl http://api.domogeek.fr/schoolholiday/A/25-12-2014/json
"""
class schoolholiday:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /schoolholiday/{zone}/{now|tomorrow|all|date(D-M-YYYY)}\n"
try:
zone = request[0]
except:
return "Incorrect request : /schoolholiday/{zone}/{now|tomorrow|all|date(D-M-YYYY)}\n"
try:
zoneok = str(zone.upper())
except:
return "Wrong Zone (must be A, B or C)"
if len(zoneok) > 1:
return "Wrong Zone (must be A, B or C)"
if zoneok not in ["A","B","C"]:
return "Incorrect request : /schoolholiday/{zone}/{now|tomorrow|all|date(D-M-YYYY)}\n"
try:
daterequest = request[1]
except:
return "Incorrect request : /schoolholiday/{zone}/{now|tomorrow|all|date(D-M-YYYY)}\n"
try:
format = request[2]
except:
format = None
datenow = datetime.now()
year = datenow.year
month = datenow.month
day = datenow.day
if daterequest == "now":
try:
rediskeyschoolholidaynow = hashlib.md5("schoolholidaynow"+zoneok).hexdigest()
getschoolholidaynow = rc.get(rediskeyschoolholidaynow)
if getschoolholidaynow is None:
result = school.isschoolcalendar(zoneok,day,month,year)
rediskeyschoolholidaynow = hashlib.md5("schoolholidaynow"+zoneok).hexdigest()
rc.set(rediskeyschoolholidaynow, result, 1800)
rc.expire(rediskeyschoolholidaynow ,1800)
print "SET SCHOOL HOLIDAY "+zoneok+ " NOW IN REDIS"
else:
result = getschoolholidaynow
print "FOUND SCHOOL HOLIDAY "+zoneok+" NOW IN REDIS"
except:
result = school.isschoolcalendar(zoneok,day,month,year)
if result == None or result == "None":
result = "False"
try:
description = result.decode('utf-8')
except:
description = result
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"schoolholiday": description}, ensure_ascii=False).encode('utf8')
else:
return description
if daterequest == "tomorrow":
datenow = datetime.now()
datetomorrow = datenow + timedelta(days=1)
yeartomorrow = datetomorrow.year
monthtomorrow = datetomorrow.month
daytomorrow = datetomorrow.day
try:
rediskeyschoolholidaytomorrow = hashlib.md5("schoolholidaytomorrow"+zoneok).hexdigest()
getschoolholidaytomorrow = rc.get(rediskeyschoolholidaytomorrow)
if getschoolholidaytomorrow is None:
result = school.isschoolcalendar(zoneok,daytomorrow,monthtomorrow,yeartomorrow)
rediskeyschoolholidaytomorrow = hashlib.md5("schoolholidaytomorrow"+zoneok).hexdigest()
rc.set(rediskeyschoolholidaytomorrow, result, 1800)
rc.expire(rediskeyschoolholidaytomorrow ,1800)
print "SET SCHOOL HOLIDAY "+zoneok+ " TOMORROW IN REDIS"
else:
result = getschoolholidaytomorrow
print "FOUND SCHOOL HOLIDAY "+zoneok+" TOMORROW IN REDIS"
except:
result = school.isschoolcalendar(zoneok,daytomorrow,monthtomorrow,yeartomorrow)
if result == None or result == "None":
result = "False"
try:
description = result.decode('utf-8')
except:
description = result
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"schoolholiday": description}, ensure_ascii=False).encode('utf8')
else:
return description
if daterequest == "all":
result = school.getschoolcalendar(zone)
try:
description = result.decode('unicode_escape')
except:
description = result
web.header('Content-Type', 'application/json')
return description
if daterequest != "now" and daterequest != "all" and daterequest != "tomorrow":
try:
result = daterequest.split('-')
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
try:
day = int(result[0])
month = int(result[1])
year = int(result[2])
except:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
if day > 31 or month > 12:
web.badrequest()
return "Incorrect date format : D-M-YYYY\n"
result = school.isschoolcalendar(zoneok,day,month,year)
if result == None :
result = "False"
try:
description = result.decode('utf-8')
except:
description = result
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"schoolholiday": description}, ensure_ascii=False).encode('utf8')
else:
return description
"""
@api {get} /vigilance/:department/:vigilancerequest/:responsetype Vigilance MeteoFrance
@apiName GetVigilance
@apiGroup Domogeek
@apiDescription Ask Vigilance MeteoFrance for :department
@apiParam {String} department Department number (France Metropolitan).
@apiParam {String} vigilancerequest Vigilance request {color|risk|flood|all}.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{"vigilanceflood": "jaune", "vigilancecolor": "orange", "vigilancerisk": "orages"}
HTTP/1.1 200 OK
vert
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/vigilance/29/color
curl http://api.domogeek.fr/vigilance/29/color/json
curl http://api.domogeek.fr/vigilance/29/risk/json
curl http://api.domogeek.fr/vigilance/29/all
"""
class vigilance:
def GET(self,uri):
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /vigilance/{department}/{color|risk|flood|all}\n"
try:
dep = request[0]
except:
web.badrequest()
return "Incorrect request : /vigilance/{department}/{color|risk|flood|all}\n"
try:
vigilancequery = request[1]
except:
web.badrequest()
return "Incorrect request : /vigilance/{department}/{color|risk|flood|all}\n"
try:
format = request[2]
except:
format = None
if len(dep) > 2:
web.badrequest()
return "Incorrect request : /vigilance/{department number}/{color|risk|flood|all}\n"
if vigilancequery not in ["color","risk","flood", "all"]:
web.badrequest()
return "Incorrect request : /vigilance/{department}/{color|risk|flood|all}\n"
if dep == "92" or dep == "93" or dep == "94":
dep = "75"
if dep == "20":
dep = "2A"
try:
rediskeyvigilance = hashlib.md5(dep+"vigilance").hexdigest()
getvigilance = rc.get(rediskeyvigilance)
if getvigilance is None:
result = vigilancerequest.getvigilance(dep)
rediskeyvigilance = hashlib.md5(dep+"vigilance").hexdigest()
rc.set(rediskeyvigilance, result, 1800)
rc.expire(rediskeyvigilance ,1800)
print "SET VIGILANCE "+dep+" IN REDIS"
else:
tr1 = getvigilance.replace("(","")
tr2 = tr1.replace(")","")
tr3 = tr2.replace("'","")
tr4 = tr3.replace(" ","")
result = tr4.split(',')
print "FOUND VIGILANCE "+dep+" IN REDIS"
except:
result = vigilancerequest.getvigilance(dep)
color = result[0]
risk = result[1]
flood = result[2]
if vigilancequery == "color":
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"vigilancecolor": color})
else:
return color
if vigilancequery == "risk":
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"vigilancerisk": risk})
else:
return risk
if vigilancequery == "flood":
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"vigilanceflood": flood})
else:
return flood
if vigilancequery == "all":
web.header('Content-Type', 'application/json')
return json.dumps({"vigilancecolor": color, "vigilancerisk": risk, "vigilanceflood": flood})
"""
@api {get} /geolocation/:city City Geolocation
@apiName GetGeolocation
@apiGroup Domogeek
@apiDescription Ask geolocation (latitude/longitude) :city
@apiParam {String} city City name (avoid accents, no space, no guarantee works other than France Metropolitan).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{"latitude": 48.390394000000001, "longitude": -4.4860759999999997}
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/geolocation/brest
"""
class geolocation:
def GET(self,uri):
checkgoogle = False
checkbing = False
checkgeonames = False
inredis = False
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /geolocation/{city}\n"
try:
city = request[0]
except:
return "Incorrect request : /geolocation/{city}\n"
try:
rediskey = hashlib.md5(city).hexdigest()
getlocation = rc.get(rediskey)
if getlocation is None:
pass
else:
print "FOUND LOCATION IN REDIS !!!"
inredis = "ok"
tr1 = getlocation.replace("(","")
tr2 = tr1.replace(")","")
data = tr2.split(',')
web.header('Content-Type', 'application/json')
return json.dumps({"latitude": float(data[0]), "longitude": float(data[1])})
except:
pass
if googleapikey == '' or inredis == "ok":
pass
else:
try:
data = geolocationrequest.geogoogle(city, googleapikey)
checkgoogle = True
rediskey = hashlib.md5(city).hexdigest()
rc.set(rediskey, (data[0], data[1]))
web.header('Content-Type', 'application/json')
return json.dumps({"latitude": data[0], "longitude": data[1]})
except:
print "NO VALUE FROM GOOGLE"
if bingmapapikey == '' or inredis == "ok":
pass
else:
if checkgoogle:
pass
else:
try:
data = geolocationrequest.geobing(city, bingmapapikey)
except:
print "NO VALUE FROM BING"
data = False
if not data :
print "NO BING"
else:
checkbing = True
rediskey = hashlib.md5(city).hexdigest()
rc.set(rediskey, (data[0], data[1]))
web.header('Content-Type', 'application/json')
return json.dumps({"latitude": data[0], "longitude": data[1]})
if geonameskey == '' or inredis == "ok":
pass
else:
if checkbing:
pass
else:
try:
data = geolocationrequest.geonames(city, geonameskey)
except:
print "NO VALUE FROM GEONAMES"
data = False
if not data :
print "NO VALUE FROM GEONAMES"
else:
checkgeonames = True
rediskey = hashlib.md5(city).hexdigest()
rc.set(rediskey, (data[0], data[1]))
web.header('Content-Type', 'application/json')
return json.dumps({"latitude": data[0], "longitude": data[1]})
if not checkgoogle and not checkbing and not checkgeonames and not inredis:
return "NO GEOLOCATION DATA AVAILABLE\n"
"""
@api {get} /sun/:city/:sunrequest/:date/:responsetype Sun Status Request
@apiName GetSun
@apiGroup Domogeek
@apiDescription Ask to know sunrise, sunset, zenith, day duration for :date in :city (France)
@apiParam {String} city City name (avoid accents, no space, France Metropolitan).
@apiParam {String} sunrequest Ask for {sunrise | sunset | zenith | dayduration | all}.
@apiParam {String} date Date request {now | tomorrow}.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{"sunset": "20:59"}
HTTP/1.1 200 OK
{"dayduration": "15:06", "sunset": "21:18", "zenith": "13:44", "sunrise": "6:11"}
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/sun/brest/all/now
curl http://api.domogeek.fr/sun/bastia/sunset/now/json
curl http://api.domogeek.fr/sun/strasbourg/sunrise/tomorrow
"""
class dawndusk:
def GET(self,uri):
getutc = float(time.strftime("%z")[:3])
request = uri.split('/')
if request == ['']:
web.badrequest()
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
city = request[0]
except:
web.badrequest()
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
if len(city) < 1:
web.badrequest()
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
print str(city)
except UnicodeEncodeError:
web.badrequest()
return "Incorrect city format : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
dawnduskrequestelement = request[1]
except:
web.badrequest()
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
daterequest = request[2]
except:
web.badrequest()
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
format = request[3]
except:
format = None
if dawnduskrequestelement not in ["sunrise", "sunset", "zenith", "dayduration", "all"]:
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
try:
rediskey = hashlib.md5(city).hexdigest()
getlocation = rc.get(rediskey)
if getlocation is None:
print "NO KEY IN REDIS"
responsegeolocation = urllib2.urlopen(localapiurl+'/geolocation/'+city)
resultgeolocation = json.load(responsegeolocation)
latitude = resultgeolocation["latitude"]
longitude = resultgeolocation["longitude"]
else:
print "FOUND LOCATION IN REDIS !!!"
tr1 = getlocation.replace("(","")
tr2 = tr1.replace(")","")
data = tr2.split(',')
latitude = float(data[0])
longitude = float(data[1])
except:
return "no data available"
if request[2] == "now":
today=date.today()
elif request[2] == "tomorrow":
today = date.today() + timedelta(days=1)
else:
return "Incorrect request : /sun/city/{sunrise|sunset|zenith|dayduration|all}/{now|tomorrow}\n"
dawnduskrequest.setNumericalDate(today.day,today.month,today.year)
dawnduskrequest.setLocation(latitude, longitude)
dawnduskrequest.calculateWithUTC(getutc)
sunrise = dawnduskrequest.sunriseTime
zenith = dawnduskrequest.meridianTime
sunset = dawnduskrequest.sunsetTime
dayduration =dawnduskrequest.durationTime
if request[2] == "now" and dawnduskrequestelement == "all" :
web.header('Content-Type', 'application/json')
return json.dumps({"sunrise": sunrise, "zenith": zenith, "sunset": sunset, "dayduration": dayduration})
if request[2] == "now" and dawnduskrequestelement == "sunrise" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"sunrise": sunrise})
else:
return sunrise
if request[2] == "now" and dawnduskrequestelement == "sunset" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"sunset": sunset})
else:
return sunset
if request[2] == "now" and dawnduskrequestelement == "zenith" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"zenith": zenith})
else:
return zenith
if request[2] == "now" and dawnduskrequestelement == "dayduration" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"dayduration": dayduration})
else:
return dayduration
if request[2] == "tomorrow" and dawnduskrequestelement == "all" :
web.header('Content-Type', 'application/json')
return json.dumps({"sunrise": sunrise, "zenith": zenith, "sunset": sunset, "dayduration": dayduration})
if request[2] == "tomorrow" and dawnduskrequestelement == "sunrise" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"sunrise": sunrise})
else:
return sunrise
if request[2] == "tomorrow" and dawnduskrequestelement == "sunset" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"sunset": sunset})
else:
return sunset
if request[2] == "tomorrow" and dawnduskrequestelement == "zenith" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"zenith": zenith})
else:
return zenith
if request[2] == "tomorrow" and dawnduskrequestelement == "dayduration" :
if format == "json":
web.header('Content-Type', 'application/json')
return json.dumps({"dayduration": dayduration})
else:
return dayduration
"""
@api {get} /weather/:city/:weatherrequest/:date/:responsetype Weather Status Request
@apiName GetWeather
@apiGroup Domogeek
@apiDescription Ask for weather (temperature, humidity, pressure, windspeed...) for :date in :city (France)
@apiParam {String} city City name (avoid accents, no space, France Metropolitan).
@apiParam {String} weatherrequest Ask for {temperature|humidity[pressure|windspeed|weather|rain|all}.
@apiParam {String} date Date request {today | tomorrow}.
@apiParam {String} [responsetype] Specify Response Type (raw by default or specify json, only for single element).
@apiSuccessExample Success-Response:
HTTP/1.1 200 OK
{u'min': 15.039999999999999, u'max': 20.34, u'eve': 19.989999999999998, u'morn': 20.34, u'night': 15.039999999999999, u'day': 20.34}
HTTP/1.1 200 OK
{"pressure": 1031.0799999999999}
@apiErrorExample Error-Response:
HTTP/1.1 400 Bad Request
400 Bad Request
@apiExample Example usage:
curl http://api.domogeek.fr/weather/brest/all/today
curl http://api.domogeek.fr/weather/brest/pressure/today/json
curl http://api.domogeek.fr/weather/brest/weather/tomorrow