-
Notifications
You must be signed in to change notification settings - Fork 1
/
models.py
2915 lines (2143 loc) · 149 KB
/
models.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
from __future__ import unicode_literals
'''
Copyright 2013 Jonathan Morgan
This file is part of http://github.com/jonathanmorgan/reddit_data.
reddit_data is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
reddit_data is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with http://github.com/jonathanmorgan/reddit_data. If not, see
<http://www.gnu.org/licenses/>.
'''
# imports
# base python
import datetime
import gc
import sys
# django
from django.conf import settings
from django.db import models
import django.utils.encoding
from django.utils.encoding import python_2_unicode_compatible
# django_time_series
from django_time_series.models import AbstractTimeSeriesDataModel
# python_utilities
#from python_utilities.research.time_series_data import AbstractTimeSeriesDataModel
from python_utilities.database.database_helper_factory import Database_Helper_Factory
#from python_utilities.database.MySQLdb_helper import MySQLdb_Helper
# reddit_collect
import reddit_collect.models
# Create your models here.
# !TODO abstract parent class, since just about everything is identical between these.
@python_2_unicode_compatible
class Subreddit_Time_Series_Data( AbstractTimeSeriesDataModel ):
#============================================================================
# constants-ish
#============================================================================
# status values
STATUS_SUCCESS = "Success!"
STATUS_PREFIX_ERROR = "ERROR - "
# MYSQL strftime date-time format
MYSQL_DATE_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
# SQL constants
SQL_AND = "AND"
SQL_OR = "OR"
# Current database config
SETTINGS_DATABASES = getattr( settings, "DATABASES", None )
SETTINGS_DB_ENGINE = SETTINGS_DATABASES[ "default" ][ "ENGINE" ]
#============================================================================
# Django model fields from parent.
#============================================================================
#start_date = models.DateTimeField( null = True, blank = True )
#end_date = models.DateTimeField( null = True, blank = True )
#time_period_type = models.CharField( max_length = 255, null = True, blank = True ) # - hourly, by minute, etc.
#filter_type = models.CharField( max_length = 255, null = True, blank = True ) # - place to keep track of different filter types, if you want. Example: "text_contains"
#filter_value = models.CharField( max_length = 255, null = True, blank = True )
#time_period_label = models.CharField( max_length = 255, null = True, blank = True ) # could give each hour, etc. a separate identifier "start+1", "start+2", etc. - not naming _id to start, so you leave room for this to be a separate table.
#match_value = models.CharField( max_length = 255, null = True, blank = True )
subreddit = models.ForeignKey( reddit_collect.models.Subreddit, null = True, blank = True )
subreddit_name = models.TextField( null = True, blank = True )
subreddit_reddit_id = models.CharField( max_length = 255, null = True, blank = True, db_index = True )
subreddit_reddit_full_id = models.CharField( max_length = 255, null = True, blank = True, db_index = True )
post_count = models.IntegerField( null = True, blank = True )
self_post_count = models.IntegerField( null = True, blank = True )
over_18_count = models.IntegerField( null = True, blank = True )
unique_author_count = models.IntegerField( null = True, blank = True )
score_average = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
score_min = models.IntegerField( null = True, blank = True )
score_max = models.IntegerField( null = True, blank = True )
score_variance = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
upvotes_average = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
upvotes_min = models.IntegerField( null = True, blank = True )
upvotes_max = models.IntegerField( null = True, blank = True )
upvotes_variance = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
downvotes_average = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
downvotes_min = models.IntegerField( null = True, blank = True )
downvotes_max = models.IntegerField( null = True, blank = True )
downvotes_variance = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
num_comments_average = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
num_comments_min = models.IntegerField( null = True, blank = True )
num_comments_max = models.IntegerField( null = True, blank = True )
num_comments_variance = models.DecimalField( max_digits = 19, decimal_places = 10, null = True, blank = True )
#============================================================================
# class variables (always access via class, not instance).
#============================================================================
# database helper.
my_db_helper = None
#============================================================================
# meta class
#============================================================================
'''
class Meta:
# multi-column indexes
index_together = [
[ "start_date", "end_date", "time_period_category", "time_period_type" ],
]
#-- END Meta class --#
'''
#============================================================================
# class methods
#============================================================================
@classmethod
def db_close( cls ):
# instance variables
db_helper = None
# get database helper
db_helper = cls.my_db_helper
# got anything?
if ( ( db_helper ) and ( db_helper != None ) ):
# yes. Close it down.
db_helper.close()
#-- END check to see if helper is present --#
#-- END method db_close() --#
@classmethod
def db_initialize_mysql( cls, db_host_IN = "localhost", db_port_IN = 3306, db_username_IN = "", db_password_IN = "", db_database_IN = "" ):
# instance variables
cls.db_initialize( Database_Helper_Factory.DATABASE_TYPE_MYSQLDB, db_host_IN, db_port_IN, db_username_IN, db_password_IN, db_database_IN )
#-- END method db_initialize_mysql() --#
@classmethod
def db_initialize( cls, db_type_IN = "", db_host_IN = "localhost", db_port_IN = -1, db_username_IN = "", db_password_IN = "", db_database_IN = "" ):
# instance variables
cls.my_db_helper = Database_Helper_Factory.get_database_helper( db_type_IN, db_host_IN, db_port_IN, db_username_IN, db_password_IN, db_database_IN )
#-- END method db_initialize() --#
@classmethod
def filter_data_on_text( cls,
start_dt_IN,
end_dt_IN,
interval_td_IN,
time_period_type_IN = "",
time_period_category_IN = "",
text_contains_and_IN = [],
text_contains_or_IN = [],
filter_number_IN = 1,
*args,
**kwargs ):
'''
Accepts a start and end datetime, the interval you want captured in time-
series data in a timedelta instance, and optional string time-period
type, time period label, and where you want an aggregate counter to
start counting if other than zero. This works on existing time-series
records created with make_data, so for parameters to this method that
are shared with make_data, you need to set the same values so this
method can filter your data. Loops over interval-sized time slices
from your start datetime to your end datetime, filtering the posts in
each time slice based on the filter criteria passed in. For each
subreddit that matches filter criteria passed in, sets filter flag in
that sub-reddit's time-series record to True. Loops until the end
date of a time slice is greater than the end date you specified.
Parameters:
- start_dt_IN - datetime.datetime instance of date and time on which you want to start deriving time-series data.
- end_dt_IN - datetime.datetime instance of date and time on which you want to stop deriving time-series data.
- interval_td_IN - datetime.timedelta instance containing the amount of time you want each time slice to contain.
- time_period_type_IN - (optional) time period type value you want stored in each time-series record. Defaults to empty string.
- time_period_category_IN - (optional) label to use in labeling. If set, this is appended to the front of an integer counter that counts up each time period, is stored in time_period_label. If not set, the integer time period counter is the only thing stored in time period label.
- text_contains_and_IN = list of text strings you want to search for inside any text field in the post (title, self_text), AND-ed together.
- text_contains_or_IN = list of text strings you want to search for inside any text field in the post (title, self_text), OR-ed together.
- filter_number_IN = the parent class has 10 filter booleans - lets you specify which to store the flag for this filter in. Defaults to 1.
'''
# return reference
status_OUT = cls.STATUS_SUCCESS
# declare variables
me = "filter_data_on_text"
started_at_dt = None
ended_at_dt = None
duration_td = None
post_query = None
mysqldb = None
my_connection = None
my_read_cursor = None
# counters.
time_period_counter = -1
total_match_count = -1
total_updated_count = -1
period_updated_count = -1
# building SQL.
filter_sql = ""
current_start_dt = None
current_end_dt = None
current_select_sql = ""
current_prefix = ""
# results
period_match_count = -1
current_row = None
current_subreddit_name = ""
current_subreddit_id = ""
current_subreddit_post_count = -1
# updating
lookup_rs = None
lookup_count = -1
current_instance = None
filter_column_name = ""
match_count_column_name = ""
# exception handling
exception_message = ""
exception_status = ""
# start time.
started_at_dt = datetime.datetime.now()
# make sure we have start date, end date, and interval.
if ( ( start_dt_IN ) and ( start_dt_IN != None ) ):
if ( ( end_dt_IN ) and ( end_dt_IN != None ) ):
if ( ( interval_td_IN ) and ( interval_td_IN != None ) ):
print( "In " + me + "() [" + started_at_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "] - Category: '" + time_period_category_IN + "'; start dt: " + start_dt_IN.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; end dt: " + end_dt_IN.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; interval: " + str( interval_td_IN ) )
# create database connection - get database helper
mysqldb = cls.my_db_helper
# create connection
my_connection = mysqldb.get_connection()
# get read and write cursors.
my_read_cursor = mysqldb.get_cursor()
# loop - go from start_dt_IN to end_dt_IN in increments of
# interval_td_IN.
# initialize variables
time_period_counter = 0
current_start_dt = start_dt_IN
current_end_dt = start_dt_IN + interval_td_IN
total_match_count = 0
total_updated_count = 0
# continue as long as the end date is less than or equal to
# the overall end datetime.
while ( current_end_dt <= end_dt_IN ):
print( "- At top of time period loop [" + datetime.datetime.now().strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "] - start dt: " + current_start_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; end dt: " + current_end_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT ) )
# increment counters
time_period_counter += 1
period_updated_count = 0
# create SQL
current_select_sql = "SELECT subreddit_name"
current_select_sql += ", subreddit_reddit_id"
current_select_sql += ", COUNT( * ) AS post_count"
current_select_sql += " FROM reddit_collect_post"
current_select_sql += " WHERE created_utc_dt BETWEEN '"
current_select_sql += current_start_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT )
current_select_sql += "' AND '"
current_select_sql += current_end_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT )
current_select_sql += "'"
# are we AND-ing any contains?
if ( len( text_contains_and_IN ) > 0 ):
# we are. output SQL.
filter_sql = reddit_collect.models.Post.sql_text_filter( text_contains_and_IN, cls.SQL_AND )
# got anything back?
if ( filter_sql != "" ):
current_select_sql += " AND ( " + filter_sql + " )"
#-- END check to make sure we got something back. --#
#-- END check to see if we are AND-ing text
# are we OR-ing any contains?
if ( len( text_contains_or_IN ) > 0 ):
# we are. output SQL.
filter_sql = reddit_collect.models.Post.sql_text_filter( text_contains_or_IN, cls.SQL_OR )
# got anything back?
if ( filter_sql != "" ):
current_select_sql += " AND ( " + filter_sql + " )"
#-- END check to make sure we got something back. --#
#-- END check to see if we are OR-ing text
current_select_sql += " GROUP BY subreddit_name;"
print( "SQL: " + current_select_sql )
# execute SQL
my_read_cursor.execute( current_select_sql )
# loop over the results.
period_match_count = int( my_read_cursor.rowcount )
for i in range( period_match_count ):
# get row.
current_row = my_read_cursor.fetchone()
# get values
current_subreddit_name = current_row[ 'subreddit_name' ]
current_subreddit_id = current_row[ 'subreddit_reddit_id' ]
current_subreddit_post_count = current_row[ 'post_count' ]
# look up instance for this time period and subreddit.
# !TODO - look up instance, potentially abstract this.
lookup_rs = cls.lookup_records( current_subreddit_name, current_subreddit_id, current_start_dt, current_end_dt, time_period_type_IN, time_period_category_IN )
# got something?
lookup_count = lookup_rs.count()
print( "====> In " + me + "() - lookup ( for name: " + current_subreddit_name + "; id: " + current_subreddit_id + "; start date: " + str( current_start_dt ) + "; end date: " + str( current_end_dt ) + "; period type: " + time_period_type_IN + "; period category: " + time_period_category_IN + " ) returned " + str( lookup_count ) + " matches." )
if ( lookup_count == 1 ):
# get instance.
current_instance = lookup_rs[ 0 ]
# populate values. Just set filter and match
# count for filter number passed in.
# generate column names
filter_column_name = "filter_" + str( filter_number_IN )
match_count_column_name = "match_count_" + str( filter_number_IN )
# set attributes.
setattr( current_instance, filter_column_name, True )
setattr( current_instance, match_count_column_name, current_subreddit_post_count )
# try/except around saving.
try:
# save method.
current_instance.save()
# increment total count
period_updated_count += 1
except Exception as e:
# error saving. Probably encoding error.
# process the exception
exception_message = "ERROR - Exception caught in " + me + "(): save() processing filter for post " + str( current_post.id ) + " ( reddit ID: " + current_post.reddit_id + " )"
exception_status = cls.process_exception( exception_IN = e, message_IN = exception_message, print_details_IN = True )
# set status to description of exception
status_OUT = exception_status
# send email to let me know this crashed?
# throw exception?
raise( e )
#-- END try/except around saving. --#
else:
# either no matches or more than one. Either
# way, error.
print( "====> In " + me + "() - lookup ( for name: " + current_subreddit_name + "; id: " + current_subreddit_id + "; start date: " + str( current_start_dt ) + "; end date: " + str( current_end_dt ) + "; period type: " + time_period_type_IN + "; period category: " + time_period_category_IN + " ) returned " + str( lookup_count ) + " matches, not 1. Can't update this row." )
#-- END check to see if we can find matching record to update. --#
#-- END loop over subreddit data for this time period. --#
print( " - found " + str( period_match_count ) + " matches, updated " + str( period_updated_count ) + " records." )
# update total counts.
total_match_count += period_match_count
total_updated_count += period_updated_count
# clear caches, performance stuff, etc. Try garbage
# collecting, not clearing django cache, to start.
gc.collect()
django.db.reset_queries()
# increment start and end dt.
current_start_dt = current_end_dt
current_end_dt = current_start_dt + interval_td_IN
#-- END loop over increments of time --#
else:
status_OUT = cls.STATUS_PREFIX_ERROR + "no interval time-delta passed in, so can't create time-series data."
#-- END check to make sure we have an interval. --#
else:
# no end date. Error.
status_OUT = cls.STATUS_PREFIX_ERROR + "no end date passed in, so can't create time-series data."
#-- END check to see if end date passed in. --#
else:
# no start date. Error.
status_OUT = cls.STATUS_PREFIX_ERROR + "no start date passed in, so can't create time-series data."
#-- END check to see if end date passed in. --#
# output overall summary
print( "==> Matches found: " + str( total_match_count ) )
print( "==> Matches updated: " + str( total_updated_count ) )
print( "==> Filtering started: " + str( started_at_dt ) )
ended_at_dt = datetime.datetime.now()
print( "==> Filtering ended: " + str( ended_at_dt ) )
duration_td = ended_at_dt - started_at_dt
print( "==> Duration: " + str( duration_td ) )
return status_OUT
#-- END method filter_data() --#
@classmethod
def lookup_records( cls,
original_name_IN = "",
original_id_IN = "",
start_dt_IN = None,
end_dt_IN = None,
time_period_type_IN = "",
time_period_category_IN = "",
time_period_index_IN = -1,
subreddit_name_IN = "",
subreddit_reddit_id_IN = "",
subreddit_reddit_full_id_IN = "",
*args,
**kwargs ):
'''
Accepts a subreddit name and ID, start and end datetime, time period
type, and time period category. Uses these values to filter
time-series records. If you are working with existing time-series
records created with make_data, to make it more likely you'll get
matches, pass the same values to these parameters that you did when
you created the data (so same time period type, time period category,
time period index, start and end date of the period, and subreddit
name or full ID).
Parameters:
- subreddit_name_IN - name of subreddit we are trying to find time-series record(s) for.
- subreddit_reddit_id_IN - ID of subreddit we are trying to find time-series record(s) for (without prefix of "t5_".
- subreddit_reddit_full_id_IN - full ID of subreddit we are trying to find time-series record(s) for (with prefix "t5_").
- start_dt_IN - datetime.datetime instance of date and time on which you want to start deriving time-series data.
- end_dt_IN - datetime.datetime instance of date and time on which you want to stop deriving time-series data.
- time_period_type_IN - (optional) time period type value you want stored in each time-series record. Defaults to empty string.
- time_period_category_IN - (optional) category used in labeling. If set, this was stored in time_period_category, appended to the front of an integer counter that counts up each time period, which was then stored in time_period_label.
- time_period_index_IN - (optional) index to keep track of time periods within a category. Generated values are non-zero, so only included in filter if value is greater than 0.
'''
# return reference
rs_OUT = None
# declare variables.
# start out lookup by using parent to lookup for all shared fields.
rs_OUT = super( Subreddit_Time_Series_Data, cls ).lookup_records( original_name_IN = original_name_IN,
original_id_IN = original_id_IN,
start_dt_IN = start_dt_IN,
end_dt_IN = end_dt_IN,
time_period_type_IN = time_period_type_IN,
time_period_category_IN = time_period_category_IN,
time_period_index_IN = time_period_index_IN )
# for each parameter, check for a non-empty value, if present, filter.
# subreddit name
if ( ( subreddit_name_IN ) and ( subreddit_name_IN != "" ) ):
rs_OUT = rs_OUT.filter( subreddit_name__iexact = subreddit_name_IN )
#-- END check for subreddit name --#
# subreddit reddit ID
if ( ( subreddit_reddit_id_IN ) and ( subreddit_reddit_id_IN != "" ) ):
rs_OUT = rs_OUT.filter( subreddit_reddit_id__iexact = subreddit_reddit_id_IN )
#-- END check for subreddit reddit ID --#
# subreddit_reddit_full_id_IN
if ( ( subreddit_reddit_full_id_IN ) and ( subreddit_reddit_full_id_IN != "" ) ):
rs_OUT = rs_OUT.filter( subreddit_reddit_id__iexact = subreddit_reddit_full_id_IN )
#-- END check for subreddit reddit full ID --#
return rs_OUT
#-- END class method lookup_record --#
@classmethod
def make_data( cls,
start_dt_IN,
end_dt_IN,
interval_td_IN,
time_period_type_IN = "",
time_period_category_IN = "",
aggregate_counter_start_IN = 0,
include_filters_IN = True,
update_existing_IN = True,
do_batch_insert_IN = True,
output_details_IN = False,
process_inactive_subreddits_IN = True,
counter_start_IN = -1,
*args,
**kwargs ):
'''
Accepts a start and end datetime, the interval you want captured in time-
series data in a timedelta instance, and optional string time-period
type, time period label, and where you want an aggregate counter to
start counting if other than zero. Loops over interval-sized time
slices from your start datetime to your end datetime, calculating
aggregate information for each subreddit posted to within that time
period, then saving the time-slice data to the database. Loops until
the end date of a time slice is greater than the end date you
specified.
Preconditions: For this to include all sub-reddits in each time period,
even those that don't have posts in the time period, need to have
used the data_creator to populate subreddit database from posts.
An example of how to do this is in:
/reddit_data/examples/subreddit_rows_from_posts.py
Parameters:
- start_dt_IN - datetime.datetime instance of date and time on which you want to start deriving time-series data.
- end_dt_IN - datetime.datetime instance of date and time on which you want to stop deriving time-series data.
- interval_td_IN - datetime.timedelta instance containing the amount of time you want each time slice to contain.
- time_period_type_IN - time period type value you want stored in each time-series record. Defaults to empty string.
- time_period_category_IN - (optional) label to use in labeling. If set, this is appended to the front of an integer counter that counts up each time period, is stored in time_period_label. If not set, the integer time period counter is the only thing stored in time period label.
- aggregate_counter_start_IN - (optional) value you want aggregate counter to begin at for this set of data. This lets you track increasing time-series across labels (before - 1 to 366 - and after - 367 and up - for instance).
- include_filters_IN - (optional) Boolean - True if you want to use the posts' filter fields to set the time series values, False if you want to set them separately. Defaults to True.
- update_existing_IN - (optional) Boolean - True if you want to update existing records. False if not. Defaults to True. If you are running for the first time on an empty database, set to False, and it should run more quickly.
- do_batch_insert_IN = (optional) Boolean - True if you want to do batch insert, False if you want to save each new record one at a time. Defaults to True. If you choose to update existing, will always be False (no way to do a batch update).
- output_details_IN = (optional) Boolean - True if you want the process to output detailed logging as it runs, False if not. Defaults to False.
- process_inactive_subreddits_IN = (optional) Boolean - True if you want to create rows for all subreddits present in your data set for each time period. False if you want to just create rows for active subreddits. Defaults to True. If your data hasn't changed and you just add a few new fields, or if you pulled in comments and just want to update active rows, for example, you can set this to False.
- counter_start_IN = (optional) integer - Base counter you want to start with. Used if you have an error and want to start in the middle of a period. Defaults to starting at one and counting up.
'''
# return reference
status_OUT = cls.STATUS_SUCCESS
# declare variables
me = "make_data"
post_query = None
mysqldb = None
my_connection = None
my_read_cursor = None
time_period_counter = -1
current_start_dt = None
current_end_dt = None
current_select_sql = ""
include_filters = True
result_count = -1
row_counter = -1
current_row = None
current_subreddit_name = ""
current_subreddit_id = ""
current_subreddit_full_id = ""
current_subreddit_post_count = -1
subreddit_match_rs = None
current_instance = None
subreddit_instance = None
bulk_create_list = None
bulk_create_count = -1
total_created_count = -1
aggregate_counter = -1
# update control
update_existing = False
do_batch_insert = False
is_row_in_database = False
do_call_save = False
# exception handling
exception_helper = None
exception_message = ""
exception_status = ""
# database handling
is_postgres = False
# performance and auditing
period_found_count = -1
period_not_found_count = -1
processed_count = -1
found_count = -1
not_found_count = -1
start_dt = None
end_dt = None
start_dt = datetime.datetime.now()
# Set control variables from input parameters.
# Include filters?
include_filters = include_filters_IN
# do batch insert?
do_batch_insert = do_batch_insert_IN
# update existing?
update_existing = update_existing_IN
#if ( ( update_existing ) and ( update_existing != None ) and ( update_existing == True ) ):
# yes - no batch insert.
#do_batch_insert = False
#-- END check to see if updating existing --#
# is it Postgres?
if ( "psycopg" in cls.SETTINGS_DB_ENGINE ):
# yes
is_postgres = True
#-- END check to see if DB ENGINE indicates postgresql --#
# make sure we have start date, end date, and interval.
if ( ( start_dt_IN ) and ( start_dt_IN != None ) ):
if ( ( end_dt_IN ) and ( end_dt_IN != None ) ):
if ( ( interval_td_IN ) and ( interval_td_IN != None ) ):
if ( output_details_IN == True ):
print( "In " + me + "() [" + datetime.datetime.now().strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "] - category: '" + time_period_category_IN + "'; start dt: " + start_dt_IN.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; end dt: " + end_dt_IN.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; interval: " + str( interval_td_IN ) + "; filter?: " + str( include_filters ) + "; update?: " + str( update_existing ) + "; batch?: " + str( do_batch_insert ) )
#-- END check to see if we should output details --#
# create database connection - get database helper
mysqldb = cls.my_db_helper
# create connection
my_connection = mysqldb.get_connection()
# get read and write cursors.
my_read_cursor = mysqldb.get_cursor()
# loop - go from start_dt_IN to end_dt_IN in increments of
# interval_td_IN.
# initialize variables
current_start_dt = start_dt_IN
current_end_dt = start_dt_IN + interval_td_IN
total_created_count = 0
processed_count = 0
found_count = 0
not_found_count = 0
# time period counter
time_period_counter = 0
# Got a counter start value passed in?
if ( ( counter_start_IN ) and ( counter_start_IN != None ) and ( counter_start_IN > 0 ) ):
# we do. Use it (subtract 1 so we increment to this
# value in first pass through loop).
time_period_counter = counter_start_IN - 1
#-- END check to see if counter start value passed in --#
# aggregate counter.
aggregate_counter = aggregate_counter_start_IN
if ( aggregate_counter > 0 ):
# value passed in is starting counter. Subtract 1 so we
# start with this value once counter is incremented at
# the top of the loop.
aggregate_counter -= 1
#-- END check to see if aggregate counter set (> 0) --#
# continue as long as the end date is less than or equal to
# the overall end datetime.
while ( current_end_dt <= end_dt_IN ):
if ( output_details_IN == True ):
print( "- At top of time period loop [" + datetime.datetime.now().strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "] - start dt: " + current_start_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT ) + "; end dt: " + current_end_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT ) )
#-- END check to see if we should output details --#
# increment counters
time_period_counter += 1
aggregate_counter += 1
# reset save list.
bulk_create_list = []
# create SQL
current_select_sql = "SELECT subreddit_name"
current_select_sql += ", subreddit_reddit_id"
current_select_sql += ", COUNT( * ) AS post_count"
current_select_sql += ", COUNT( DISTINCT author_name ) AS unique_author_count"
current_select_sql += ", SUM( is_self"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS self_post_count"
current_select_sql += ", SUM( over_18"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS over_18_count"
current_select_sql += ", AVG( score ) AS score_average"
current_select_sql += ", MIN( score ) AS score_min"
current_select_sql += ", MAX( score ) AS score_max"
current_select_sql += ", VAR_SAMP( score ) AS score_variance"
current_select_sql += ", AVG( upvotes ) AS upvotes_average"
current_select_sql += ", MIN( upvotes ) AS upvotes_min"
current_select_sql += ", MAX( upvotes ) AS upvotes_max"
current_select_sql += ", VAR_SAMP( upvotes ) AS upvotes_variance"
current_select_sql += ", AVG( downvotes ) AS downvotes_average"
current_select_sql += ", MIN( downvotes ) AS downvotes_min"
current_select_sql += ", MAX( downvotes ) AS downvotes_max"
current_select_sql += ", VAR_SAMP( downvotes ) AS downvotes_variance"
current_select_sql += ", AVG( num_comments ) AS num_comments_average"
current_select_sql += ", MIN( num_comments ) AS num_comments_min"
current_select_sql += ", MAX( num_comments ) AS num_comments_max"
current_select_sql += ", VAR_SAMP( num_comments ) AS num_comments_variance"
# also aggregate filter flags - just MAX, SUM to count matches.
if ( include_filters == True ):
# yes (for now, we always do).
current_select_sql += ", MAX( filter_1"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_1"
current_select_sql += ", SUM( filter_1"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_1"
current_select_sql += ", MAX( filter_2"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_2"
current_select_sql += ", SUM( filter_2"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_2"
current_select_sql += ", MAX( filter_3"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_3"
current_select_sql += ", SUM( filter_3"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_3"
current_select_sql += ", MAX( filter_4"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_4"
current_select_sql += ", SUM( filter_4"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_4"
current_select_sql += ", MAX( filter_5"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_5"
current_select_sql += ", SUM( filter_5"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_5"
current_select_sql += ", MAX( filter_6"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_6"
current_select_sql += ", SUM( filter_6"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_6"
current_select_sql += ", MAX( filter_7"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_7"
current_select_sql += ", SUM( filter_7"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_7"
current_select_sql += ", MAX( filter_8"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_8"
current_select_sql += ", SUM( filter_8"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_8"
current_select_sql += ", MAX( filter_9"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_9"
current_select_sql += ", SUM( filter_9"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_9"
current_select_sql += ", MAX( filter_10"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS filter_10"
current_select_sql += ", SUM( filter_10"
# if postgres, cast booleans to int.
if ( is_postgres == True ):
current_select_sql += "::int"
#-- END check to see if postgreSQL
current_select_sql += " ) AS match_count_10"
#-- END check to see if we include filters --#
current_select_sql += " FROM reddit_collect_post"
current_select_sql += " WHERE created_utc_dt BETWEEN '"
current_select_sql += current_start_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT )
current_select_sql += "' AND '"
current_select_sql += current_end_dt.strftime( cls.MYSQL_DATE_TIME_FORMAT )
current_select_sql += "' GROUP BY subreddit_name, subreddit_reddit_id";
current_select_sql += " ORDER BY subreddit_name ASC;"
# if outputting details, output SQL
if ( output_details_IN == True ):
print( "<<< SQL: " + current_select_sql )
#-- END check to see if we output details. --#
# !execute SQL
my_read_cursor.execute( current_select_sql )
# !loop over the results, creating a new instance of this
# class for each.
result_count = int( my_read_cursor.rowcount )
row_counter = 0
period_found_count = 0
period_not_found_count = 0
for i in range( result_count ):
# increment counter
row_counter += 1
# initialize variables
do_call_save = False
# get row.
current_row = my_read_cursor.fetchone()
# get values
current_subreddit_name = current_row[ 'subreddit_name' ]
current_subreddit_id = current_row[ 'subreddit_reddit_id' ]
current_subreddit_full_id = current_row[ 'subreddit_reddit_id' ]