-
Notifications
You must be signed in to change notification settings - Fork 2
/
index3.html
1300 lines (1193 loc) · 121 KB
/
index3.html
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
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js" lang="en"><!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="google-site-verification" content="5_8DTmIiEq4gFvNAfxAD6TsGOgrMAjp8lQFQvfA6zZc" />
<title>/var/</title>
<meta name="author" content="Serafeim Papastefanos">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://spapas.github.io/favicon.png" rel="icon">
<link href="http://spapas.github.io/theme/css/main.css" media="screen, projection"
rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=PT+Serif:regular,italic,bold,bolditalic"
rel="stylesheet" type="text/css">
<link href="//fonts.googleapis.com/css?family=PT+Sans:regular,italic,bold,bolditalic"
rel="stylesheet" type="text/css">
</head>
<body>
<header role="banner"><hgroup>
<h1><a href="http://spapas.github.io/">/var/</a></h1>
<h2>Various programming stuff</h2>
</hgroup></header>
<nav role="navigation"><ul class="subscription" data-subscription="rss">
</ul>
<ul class="main-navigation">
<li >
<a href="http://spapas.github.io/category/css.html">Css</a>
</li>
<li >
<a href="http://spapas.github.io/category/django.html">Django</a>
</li>
<li >
<a href="http://spapas.github.io/category/flask.html">Flask</a>
</li>
<li >
<a href="http://spapas.github.io/category/git.html">Git</a>
</li>
<li >
<a href="http://spapas.github.io/category/javascript.html">Javascript</a>
</li>
<li >
<a href="http://spapas.github.io/category/pelican.html">Pelican</a>
</li>
<li >
<a href="http://spapas.github.io/category/python.html">Python</a>
</li>
<li >
<a href="http://spapas.github.io/category/spring.html">Spring</a>
</li>
<li >
<a href="http://spapas.github.io/category/wagtail.html">Wagtail</a>
</li>
</ul></nav>
<div id="main">
<div id="content">
<div class="blog-index">
<article>
<header>
<h1 class="entry-title">
<a href="http://spapas.github.io/2015/02/06/python-pusher-rest/">Calling the REST API of Pusher from python</a>
</h1>
<p class="meta">
<time datetime="2015-02-06T12:20:00+02:00" pubdate>Παρ 06 Φεβρουάριος 2015</time> </p>
</header>
<div class="entry-content"><div class="section" id="introduction">
<h2>Introduction</h2>
<p><a class="reference external" href="https://pusher.com/">Pusher</a> is one of the best real time frameworks right now. Using it you can add real time
events in your projects without the need to configure and use <span class="caps">HTTP</span> servers that support
real-time events in your environment. I used it recently in a project and it worked really
good, having a very simple <span class="caps">API</span> and a nice interface for debugging your requests.</p>
<p>The only problem I’ve found was that the <a class="reference external" href="https://github.com/pusher/pusher_client_python">Pusher python <span class="caps">API</span></a> misses some features that
the APIs for other languages have, specifically finding out the users on a presence channel.</p>
<p>Pusher supports real-time events through the use of "channels". Each pusher client will
subscribe to a channel and receive messages that are sent to that channel. A special kind
of channel are presence channels which keep a list of their subscribers. You can query the
<a class="reference external" href="https://pusher.com/docs/rest_api">Pusher <span class="caps">REST</span> <span class="caps">API</span></a> (or f.e the Pusher Javascript <span class="caps">API</span>) to find out the names of the users
in a presence channel - however this is <em>not</em> currently possible with the python <span class="caps">API</span>.</p>
<p>Unfortuanately, calling the Pusher <span class="caps">REST</span> <span class="caps">API</span> is <em>not</em> so easy, since it needs a complicated
singining of each request, so I’ve written this post to help developers that need to call
this <span class="caps">API</span> from python (to get the users of a presence channel or for any other method the
<span class="caps">REST</span> <span class="caps">API</span> supports).</p>
</div>
<div class="section" id="signing-the-request">
<h2>Signing the request</h2>
<p>Quoting from the <a class="reference external" href="https://pusher.com/docs/rest_api">Pusher <span class="caps">REST</span> <span class="caps">API</span></a>, to sign a request we need a signature, which:</p>
<blockquote>
<p>The signature is a <span class="caps">HMAC</span> <span class="caps">SHA256</span> hex digest. This is generated by signing a string made up of the following components concatenated with newline characters \n:</p>
<ul class="simple">
<li>The uppercase request method (e.g. <span class="caps">POST</span>)</li>
<li>The request path (e.g. /some/resource)</li>
<li>The query parameters sorted by key, with keys converted to lowercase, then joined as in the query string. Note that the string must not be url escaped (e.g. given the keys auth_key: foo, Name: Something else, you get auth_key=foo&name=Something else)</li>
</ul>
</blockquote>
<p>So, we need to create a string and then sign it using our Pusher api_key and secret. To help with this, we create a <tt class="docutils literal">Token</tt>
class which will be initialzed with out pusher key/secret and correctly sign a string:</p>
<div class="highlight"><pre><span class="k">class</span> <span class="nc">Token</span><span class="p">(</span><span class="nb">object</span><span class="p">,):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">secret</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="o">=</span> <span class="n">key</span>
<span class="bp">self</span><span class="o">.</span><span class="n">secret</span> <span class="o">=</span> <span class="n">secret</span>
<span class="k">def</span> <span class="nf">sign</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">string</span><span class="p">):</span>
<span class="k">return</span> <span class="n">hmac</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">secret</span><span class="p">,</span> <span class="n">string</span><span class="p">,</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha256</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()</span>
</pre></div>
<p>It uses the <tt class="docutils literal">hmac</tt> and <tt class="docutils literal">hashlib</tt> python modules.</p>
</div>
<div class="section" id="generating-the-complete-query-string">
<h2>Generating the complete query string</h2>
<p>We can now create a function that will sign a request using an instance of the above token:</p>
<div class="highlight"><pre><span class="k">def</span> <span class="nf">create_signed_query_string</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="n">request_params</span><span class="p">):</span>
<span class="n">params</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'auth_key'</span><span class="p">:</span> <span class="n">token</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="s">'auth_timestamp'</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()),</span>
<span class="s">'auth_version'</span><span class="p">:</span> <span class="s">'1.0'</span>
<span class="p">}</span>
<span class="n">params</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">request_params</span><span class="p">)</span>
<span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">params</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="p">)</span>
<span class="n">params_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span>
<span class="n">params_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span> <span class="s">'{0}={1}'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">params</span><span class="p">[</span><span class="n">k</span><span class="p">])</span> <span class="p">)</span>
<span class="n">query_string</span> <span class="o">=</span> <span class="s">'&'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">params_list</span><span class="p">)</span>
<span class="n">sign_data</span> <span class="o">=</span> <span class="s">'</span><span class="se">\n</span><span class="s">'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s">'GET'</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="n">query_string</span><span class="p">])</span>
<span class="n">query_string</span> <span class="o">+=</span> <span class="s">'&auth_signature='</span> <span class="o">+</span> <span class="n">token</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="n">sign_data</span><span class="p">);</span>
<span class="k">return</span> <span class="n">query_string</span>
</pre></div>
<p><tt class="docutils literal">create_signed_query_string</tt> receives an instance of a <tt class="docutils literal">Token</tt>, the path that we want to request
without the server part (for example <tt class="docutils literal"><span class="pre">/apps/33/users/my-channel</span></tt>) and a dictionary of
request parameters. It then adds three extra fields to the request parameters (<tt class="docutils literal">auth_key, auth_timestamp, auth_version</tt>)
and creates a list of these parameters in the <tt class="docutils literal">key=value</tt> form, where the keys are alphabetically sorted.
After that it joins the above <tt class="docutils literal">key=value</tt> parameters using <tt class="docutils literal">&</tt> to create the <tt class="docutils literal">query_string</tt> and then it creates the string to be signed (<tt class="docutils literal">sign_data</tt>)
by concatenating the <span class="caps">HTTP</span> methdo (<span class="caps">GET</span>) with the path and the <tt class="docutils literal">query_string</tt>. Finally, it appends the signing result as an extra
query parameter named (<tt class="docutils literal">auth_signature</tt>).</p>
</div>
<div class="section" id="requesting-the-users-of-the-presence-channel">
<h2>Requesting the users of the presence channel</h2>
<p>The <tt class="docutils literal">create_signed_query_string</tt> can now be used to get the users of a presence channel like this:</p>
<div class="highlight"><pre><span class="k">def</span> <span class="nf">get_users</span><span class="p">(</span><span class="n">app_id</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">secret</span><span class="p">,</span> <span class="n">channel</span><span class="p">):</span>
<span class="n">partial_path</span> <span class="o">=</span> <span class="s">'/apps/{0}/channels/{1}/users'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">app_id</span><span class="p">,</span> <span class="n">channel</span><span class="p">)</span>
<span class="n">token</span> <span class="o">=</span> <span class="n">Token</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">secret</span><span class="p">)</span>
<span class="n">qs</span> <span class="o">=</span> <span class="n">create_signed_query_string</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="p">{})</span>
<span class="n">full_path</span> <span class="o">=</span> <span class="s">'http://api.pusherapp.com/{0}?{1}'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">partial_path</span><span class="p">,</span> <span class="n">qs</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">full_path</span><span class="p">)</span>
<span class="k">return</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span>
</pre></div>
<p>The <tt class="docutils literal">get_users</tt> function will generate the path of the pusher <span class="caps">REST</span> <span class="caps">API</span> (using
our pusher app_id and channel name) and initialize a signing <tt class="docutils literal">Token</tt> using
the pusher key and secret. It will then pass the previous to <tt class="docutils literal">create_signed_query_string</tt>
to generate the complete <tt class="docutils literal">query_string</tt> and generate the <tt class="docutils literal">full_path</tt> to which
a simple <span class="caps">HTTP</span> <span class="caps">GET</span> request is issued. The result will be a <span class="caps">JSON</span> list of the users in the
presence channel.</p>
</div>
<div class="section" id="complete-example">
<h2>Complete example</h2>
<p>A complete example of getting the presence users of a channel is the following:</p>
<div class="highlight"><pre><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">hashlib</span>
<span class="kn">import</span> <span class="nn">hmac</span>
<span class="kn">import</span> <span class="nn">requests</span>
<span class="n">app_id</span> <span class="o">=</span> <span class="s">'pusher_app_id'</span>
<span class="n">key</span> <span class="o">=</span> <span class="s">'pusher_key'</span>
<span class="n">secret</span> <span class="o">=</span> <span class="s">'pusher_secret'</span>
<span class="n">channel</span> <span class="o">=</span> <span class="s">'pusher_presence_channel'</span>
<span class="k">class</span> <span class="nc">Token</span><span class="p">(</span><span class="nb">object</span><span class="p">,):</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">secret</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">key</span> <span class="o">=</span> <span class="n">key</span>
<span class="bp">self</span><span class="o">.</span><span class="n">secret</span> <span class="o">=</span> <span class="n">secret</span>
<span class="k">def</span> <span class="nf">sign</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">string</span><span class="p">):</span>
<span class="k">return</span> <span class="n">hmac</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">secret</span><span class="p">,</span> <span class="n">string</span><span class="p">,</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha256</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">create_signed_query_string</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">request_params</span><span class="p">):</span>
<span class="n">params</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'auth_key'</span><span class="p">:</span> <span class="n">token</span><span class="o">.</span><span class="n">key</span><span class="p">,</span>
<span class="s">'auth_timestamp'</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()),</span>
<span class="s">'auth_version'</span><span class="p">:</span> <span class="s">'1.0'</span>
<span class="p">}</span>
<span class="n">params</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">request_params</span><span class="p">)</span>
<span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">params</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="p">)</span>
<span class="n">params_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span>
<span class="n">params_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span> <span class="s">'{0}={1}'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="n">params</span><span class="p">[</span><span class="n">k</span><span class="p">])</span> <span class="p">)</span>
<span class="n">query_string</span> <span class="o">=</span> <span class="s">'&'</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">params_list</span><span class="p">)</span>
<span class="n">sign_data</span> <span class="o">=</span> <span class="s">'</span><span class="se">\n</span><span class="s">'</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="n">method</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="n">query_string</span><span class="p">])</span>
<span class="n">query_string</span> <span class="o">+=</span> <span class="s">'&auth_signature='</span> <span class="o">+</span> <span class="n">token</span><span class="o">.</span><span class="n">sign</span><span class="p">(</span><span class="n">sign_data</span><span class="p">);</span>
<span class="k">return</span> <span class="n">query_string</span>
<span class="k">def</span> <span class="nf">get_users</span><span class="p">(</span><span class="n">channel</span><span class="p">):</span>
<span class="n">partial_path</span> <span class="o">=</span> <span class="s">'/apps/{0}/channels/{1}/users'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">app_id</span><span class="p">,</span> <span class="n">channel</span><span class="p">)</span>
<span class="n">token</span> <span class="o">=</span> <span class="n">Token</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">secret</span><span class="p">)</span>
<span class="n">qs</span> <span class="o">=</span> <span class="n">create_signed_query_string</span><span class="p">(</span><span class="n">token</span><span class="p">,</span> <span class="n">partial_path</span><span class="p">,</span> <span class="s">'GET'</span> <span class="p">{})</span>
<span class="n">full_path</span> <span class="o">=</span> <span class="s">'http://api.pusherapp.com/{0}?{1}'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">partial_path</span><span class="p">,</span> <span class="n">qs</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">full_path</span><span class="p">)</span>
<span class="k">return</span> <span class="n">r</span><span class="o">.</span><span class="n">text</span>
<span class="k">print</span> <span class="n">get_users</span><span class="p">(</span><span class="n">channel</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="conclusion">
<h2>Conclusion</h2>
<p>With the above we are able to not only easily get the users of a Pusher presence
channel in python but to also call any method we want from the Pusher <span class="caps">REST</span> <span class="caps">API</span> by implementing a function
similar to <tt class="docutils literal">get_users</tt>.</p>
</div>
</div>
</article>
<article>
<header>
<h1 class="entry-title">
<a href="http://spapas.github.io/2015/01/27/async-tasks-with-django-rq/">Asynchronous tasks in django with django-rq</a>
</h1>
<p class="meta">
<time datetime="2015-01-27T14:20:00+02:00" pubdate>Τρι 27 Ιανουάριος 2015</time> </p>
</header>
<div class="entry-content"><div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#introduction" id="id1">Introduction</a></li>
<li><a class="reference internal" href="#job-queues-in-python" id="id2">Job queues in python</a></li>
<li><a class="reference internal" href="#django-test-rq" id="id3">django-test-rq</a><ul>
<li><a class="reference internal" href="#models-py" id="id4">models.py</a></li>
<li><a class="reference internal" href="#forms-py" id="id5">forms.py</a></li>
<li><a class="reference internal" href="#views-py" id="id6">views.py</a></li>
<li><a class="reference internal" href="#tasks-py" id="id7">tasks.py</a></li>
<li><a class="reference internal" href="#settings-py" id="id8">settings.py</a></li>
<li><a class="reference internal" href="#running-the-project" id="id9">Running the project</a></li>
</ul>
</li>
<li><a class="reference internal" href="#rqworker-and-rqscheduler" id="id10">rqworker and rqscheduler</a><ul>
<li><a class="reference internal" href="#for-development" id="id11">For development</a></li>
<li><a class="reference internal" href="#for-production" id="id12">For production</a></li>
</ul>
</li>
<li><a class="reference internal" href="#conclusion" id="id13">Conclusion</a></li>
</ul>
</div>
<p><strong>Update 01/09/15</strong>: I’ve written a new post about rq and django with some
<a class="reference external" href="http://spapas.github.io/2015/09/01/django-rq-redux/">more advanced techniques</a> !</p>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id1">Introduction</a></h2>
<p>Job queuing (asynchronous tasks) is a common requirement for non-trivial django projects. Whenever an operation
can take more than half a second it should be put to a job queue in order to be run asynchronously by a
seperate worker. This is really important since the response to a user request needs to be immediate
or else the users will experience laggy behavior and start complaining!
Even for fairly quick tasks (like sending email through an <span class="caps">SMTP</span> server) you need to use an asynchronous task
if you care about your users since
the time required for such a task is not really limited.</p>
<p>Using job queues is involved not only for the developers of the application (who need to create the
asynchronous tasks and give feedback to the users when the’ve finished since they can’t use the normal
<span class="caps">HTTP</span> response) and but also for the administrators, since, in order to support job queues at least two
more componets will be needed:</p>
<ul class="simple">
<li>One job queue that will store the jobs to be executed next in a first in first queue. This could be the normal database of the project however it’s not recommended for performance reasons and most of thetimes it is a specific component called "Message Broker"</li>
<li>One (or more) workers that will monitor the job queue and when there is work to do they will dequeue and execute it</li>
</ul>
<p>These can all run in the same server but if it gets saturated they can easily be seperated (even more work for administrators).</p>
<p>Beyond job queuing, another relative requirement for many projects is to schedule a task to be run in the future
(similar to the <tt class="docutils literal">at</tt> unix command) or at specific time intervals (similar to the <tt class="docutils literal">cron</tt> unix command). For
instance, if a user is registered today we may need to check after one or two days if he’s logged in and used our application -
if he hasn’t then probably he’s having problems and we can call him to help him. Also, we could check every night
to see if any users that have registered to our application don’t have activated their account through email activation
and delete these accounts. Scheduled tasks should be also run by the workers mentioned above.</p>
</div>
<div class="section" id="job-queues-in-python">
<h2><a class="toc-backref" href="#id2">Job queues in python</a></h2>
<p>The most known application for using job queues in python is <a class="reference external" href="http://www.celeryproject.org/">celery</a> which is a really great project that supports
many brokers, integrates nicely
with python/django (but can be used even with other languages) and has
many more features (most of them are only useful on really big, enterprise projects). I’ve already used
it in a previous application, however, because celery is really complex I found it rather difficult to
configure it successfully and I never was perfectly sure that my asynchronous task would actually work or
that I’d used the correct configuration for my needs!</p>
<p>Celery also has <a class="reference external" href="http://celery.readthedocs.org/en/latest/faq.html#does-celery-have-many-dependencies">many dependencies</a> in order to be able to talk with the different broker backends it supports,
improve multithreading support etc. They may be required in enterprise apps but not for most Django web based projects.</p>
<p>So, for small-to-average projects I recommend using a different asynchronous task solution instead of celery, particularly
(as you’ve already guessed from the title of this post) <a class="reference external" href="http://python-rq.org/"><span class="caps">RQ</span></a>. <span class="caps">RQ</span> is simpler than celery, it integrates great with django
using the excellent <a class="reference external" href="https://github.com/ui/django-rq">django-rq</a> package and doesn’t actually have any more dependencies beyond redis support which is
used as a broker (however most modern django projects already use redis for their caching needs as an alternative
to memcached).</p>
<p>It even supports supports job scheduling through the <a class="reference external" href="https://github.com/ui/rq-scheduler">rq-scheduler</a> package (celery also supports
job scheduling through celery beat): Run a different process (scheduler) that polls the job
scheduling queue for any jobs that need to be run because of scheduling and if yes put them to
the normal job queue.</p>
<p>Although <span class="caps">RQ</span> and frieds are really easy to use (and have nice documentation) I wasn’t able to find
a <em>complete</em> example of using it with django, so I’ve implemented one
(found at <a class="reference external" href="https://github.com/spapas/django-test-rq">https://github.com/spapas/django-test-rq</a> — since I’ve updated this project a bit
with new stuff,
please checkout tag django-test-rq-simple <tt class="docutils literal">git checkout <span class="pre">django-test-rq-simple</span></tt>) mainly for my own testing
purposes. To help others that want to also use <span class="caps">RQ</span> in their project but don’t know from where
to start, I’ll present it in the following paragraphs, along with some comments on
how to actually use <span class="caps">RQ</span> in your production environment.</p>
</div>
<div class="section" id="django-test-rq">
<h2><a class="toc-backref" href="#id3">django-test-rq</a></h2>
<p>This is a simple django project that can be used to asynchronously
run and schedule jobs and examine their behavior. The job to be scheduled just downloads a provided
<span class="caps">URL</span> and counts its length. There is only one django application (tasks) that contains two views, one
to display existing tasks and create new ones and one to display some info for the jobs.</p>
<div class="section" id="models-py">
<h3><a class="toc-backref" href="#id4">models.py</a></h3>
<p>Two models (<tt class="docutils literal">Task</tt> and <tt class="docutils literal">ScheduledTask</tt>) for saving individual tasks and
scheduled tasks and one model (<tt class="docutils literal">ScheduledTaskInstance</tt>) to save scheduled
instances of each scheduled task.</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">import</span> <span class="nn">requests</span>
<span class="kn">from</span> <span class="nn">rq</span> <span class="kn">import</span> <span class="n">get_current_job</span>
<span class="k">class</span> <span class="nc">Task</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="c"># A model to save information about an asynchronous task</span>
<span class="n">created_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="n">job_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ScheduledTask</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="c"># A model to save information about a scheduled task</span>
<span class="n">created_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="c"># A scheduled task has a common job id for all its occurences</span>
<span class="n">job_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ScheduledTaskInstance</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="c"># A model to save information about instances of a scheduled task</span>
<span class="n">scheduled_task</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="s">'ScheduledTask'</span><span class="p">)</span>
<span class="n">created_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="forms-py">
<h3><a class="toc-backref" href="#id5">forms.py</a></h3>
<p>A very simple form to create a new task.</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">forms</span>
<span class="k">class</span> <span class="nc">TaskForm</span><span class="p">(</span><span class="n">forms</span><span class="o">.</span><span class="n">Form</span><span class="p">):</span>
<span class="sd">""" A simple form to read a url from the user in order to find out its length</span>
<span class="sd"> and either run it asynchronously or schedule it schedule_times times,</span>
<span class="sd"> every schedule_interval seconds.</span>
<span class="sd"> """</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">label</span><span class="o">=</span><span class="s">'URL'</span><span class="p">,</span> <span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">'Enter a url (starting with http/https) to start a job that will download it and count its words'</span> <span class="p">)</span>
<span class="n">schedule_times</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">'How many times to run this job. Leave empty or 0 to run it only once.'</span><span class="p">)</span>
<span class="n">schedule_interval</span> <span class="o">=</span> <span class="n">forms</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">'How much time (in seconds) between runs of the job. Leave empty to run it only once.'</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">clean</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="n">data</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">TaskForm</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">clean</span><span class="p">()</span>
<span class="n">schedule_times</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'schedule_times'</span><span class="p">)</span>
<span class="n">schedule_interval</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'schedule_interval'</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schedule_times</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">schedule_interval</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">schedule_times</span> <span class="ow">and</span> <span class="n">schedule_interval</span><span class="p">:</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s">'Please fill both schedule_times and schedule_interval to schedule a job or leave them both empty'</span>
<span class="bp">self</span><span class="o">.</span><span class="n">add_error</span><span class="p">(</span><span class="s">'schedule_times'</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
<span class="bp">self</span><span class="o">.</span><span class="n">add_error</span><span class="p">(</span><span class="s">'schedule_interval'</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="views-py">
<h3><a class="toc-backref" href="#id6">views.py</a></h3>
<p>This is actually very simple if you’re familiar with Class Based Views. Two CBVs
are defined, one for the Task form + Task display and another for the Job display.</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">FormView</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">TemplateView</span>
<span class="kn">from</span> <span class="nn">forms</span> <span class="kn">import</span> <span class="n">TaskForm</span>
<span class="kn">from</span> <span class="nn">tasks</span> <span class="kn">import</span> <span class="n">get_url_words</span><span class="p">,</span> <span class="n">scheduled_get_url_words</span>
<span class="kn">from</span> <span class="nn">models</span> <span class="kn">import</span> <span class="n">Task</span><span class="p">,</span><span class="n">ScheduledTask</span>
<span class="kn">from</span> <span class="nn">rq.job</span> <span class="kn">import</span> <span class="n">Job</span>
<span class="kn">import</span> <span class="nn">django_rq</span>
<span class="kn">import</span> <span class="nn">datetime</span>
<span class="k">class</span> <span class="nc">TasksHomeFormView</span><span class="p">(</span><span class="n">FormView</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A class that displays a form to read a url to read its contents and if the job</span>
<span class="sd"> is to be scheduled or not and information about all the tasks and scheduled tasks.</span>
<span class="sd"> When the form is submitted, the task will be either scheduled based on the</span>
<span class="sd"> parameters of the form or will be just executed asynchronously immediately.</span>
<span class="sd"> """</span>
<span class="n">form_class</span> <span class="o">=</span> <span class="n">TaskForm</span>
<span class="n">template_name</span> <span class="o">=</span> <span class="s">'tasks_home.html'</span>
<span class="n">success_url</span> <span class="o">=</span> <span class="s">'/'</span>
<span class="k">def</span> <span class="nf">form_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">):</span>
<span class="n">url</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">cleaned_data</span><span class="p">[</span><span class="s">'url'</span><span class="p">]</span>
<span class="n">schedule_times</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">cleaned_data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'schedule_times'</span><span class="p">)</span>
<span class="n">schedule_interval</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">cleaned_data</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">'schedule_interval'</span><span class="p">)</span>
<span class="k">if</span> <span class="n">schedule_times</span> <span class="ow">and</span> <span class="n">schedule_interval</span><span class="p">:</span>
<span class="c"># Schedule the job with the form parameters</span>
<span class="n">scheduler</span> <span class="o">=</span> <span class="n">django_rq</span><span class="o">.</span><span class="n">get_scheduler</span><span class="p">(</span><span class="s">'default'</span><span class="p">)</span>
<span class="n">job</span> <span class="o">=</span> <span class="n">scheduler</span><span class="o">.</span><span class="n">schedule</span><span class="p">(</span>
<span class="n">scheduled_time</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(),</span>
<span class="n">func</span><span class="o">=</span><span class="n">scheduled_get_url_words</span><span class="p">,</span>
<span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="n">url</span><span class="p">],</span>
<span class="n">interval</span><span class="o">=</span><span class="n">schedule_interval</span><span class="p">,</span>
<span class="n">repeat</span><span class="o">=</span><span class="n">schedule_times</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="c"># Just execute the job asynchronously</span>
<span class="n">get_url_words</span><span class="o">.</span><span class="n">delay</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">TasksHomeFormView</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">form_valid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">get_context_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">TasksHomeFormView</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_context_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="n">ctx</span><span class="p">[</span><span class="s">'tasks'</span><span class="p">]</span> <span class="o">=</span> <span class="n">Task</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">'-created_on'</span><span class="p">)</span>
<span class="n">ctx</span><span class="p">[</span><span class="s">'scheduled_tasks'</span><span class="p">]</span> <span class="o">=</span> <span class="n">ScheduledTask</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">'-created_on'</span><span class="p">)</span>
<span class="k">return</span> <span class="n">ctx</span>
<span class="k">class</span> <span class="nc">JobTemplateView</span><span class="p">(</span><span class="n">TemplateView</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> A simple template view that gets a job id as a kwarg parameter</span>
<span class="sd"> and tries to fetch that job from RQ. It will then print all attributes</span>
<span class="sd"> of that object using __dict__.</span>
<span class="sd"> """</span>
<span class="n">template_name</span> <span class="o">=</span> <span class="s">'job.html'</span>
<span class="k">def</span> <span class="nf">get_context_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">JobTemplateView</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_context_data</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="n">redis_conn</span> <span class="o">=</span> <span class="n">django_rq</span><span class="o">.</span><span class="n">get_connection</span><span class="p">(</span><span class="s">'default'</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">job</span> <span class="o">=</span> <span class="n">Job</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">[</span><span class="s">'job'</span><span class="p">],</span> <span class="n">connection</span><span class="o">=</span><span class="n">redis_conn</span><span class="p">)</span>
<span class="n">job</span> <span class="o">=</span> <span class="n">job</span><span class="o">.</span><span class="n">__dict__</span>
<span class="k">except</span><span class="p">:</span>
<span class="n">job</span> <span class="o">=</span> <span class="bp">None</span>
<span class="n">ctx</span><span class="p">[</span><span class="s">'job'</span><span class="p">]</span> <span class="o">=</span> <span class="n">job</span>
<span class="k">return</span> <span class="n">ctx</span>
</pre></div>
</div>
<div class="section" id="tasks-py">
<h3><a class="toc-backref" href="#id7">tasks.py</a></h3>
<p>Here two jobs are defined: One to be used for simple asynchronous tasks and the
other to be used for scheduled asynchronous tasks (since for asynchronous tasks
we wanted to group their runs per job id).</p>
<p>The <tt class="docutils literal">@job</tt> decorator will add the <tt class="docutils literal">delay()</tt> method (used in <tt class="docutils literal">views.py</tt>) to
the function. It’s not really required for <tt class="docutils literal">scheduled_get_url_words</tt> since
it’s called through the <tt class="docutils literal">scheduled.schedule</tt>.</p>
<p>When a task is finished, it can return a value (like we do in <tt class="docutils literal">return task.result</tt>)
which will be saved for a limited amount of time (500 seconds by default - could be
even saved for ever) to redis.
This may be useful in some cases, however, I think that for normal web applications it’s
not that useful, and since here we use normal django models
for each task, we can save it to that model’s instance instead.</p>
<div class="highlight"><pre><span class="kn">import</span> <span class="nn">requests</span>
<span class="kn">from</span> <span class="nn">models</span> <span class="kn">import</span> <span class="n">Task</span><span class="p">,</span> <span class="n">ScheduledTask</span><span class="p">,</span> <span class="n">ScheduledTaskInstance</span>
<span class="kn">from</span> <span class="nn">rq</span> <span class="kn">import</span> <span class="n">get_current_job</span>
<span class="kn">from</span> <span class="nn">django_rq</span> <span class="kn">import</span> <span class="n">job</span>
<span class="nd">@job</span>
<span class="k">def</span> <span class="nf">get_url_words</span><span class="p">(</span><span class="n">url</span><span class="p">):</span>
<span class="c"># This creates a Task instance to save the job instance and job result</span>
<span class="n">job</span> <span class="o">=</span> <span class="n">get_current_job</span><span class="p">()</span>
<span class="n">task</span> <span class="o">=</span> <span class="n">Task</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="n">job_id</span><span class="o">=</span><span class="n">job</span><span class="o">.</span><span class="n">get_id</span><span class="p">(),</span>
<span class="n">name</span><span class="o">=</span><span class="n">url</span>
<span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="n">task</span><span class="o">.</span><span class="n">result</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="n">task</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="k">return</span> <span class="n">task</span><span class="o">.</span><span class="n">result</span>
<span class="nd">@job</span>
<span class="k">def</span> <span class="nf">scheduled_get_url_words</span><span class="p">(</span><span class="n">url</span><span class="p">):</span>
<span class="sd">"""</span>
<span class="sd"> This creates a ScheduledTask instance for each group of</span>
<span class="sd"> scheduled task - each time this scheduled task is run</span>
<span class="sd"> a new instance of ScheduledTaskInstance will be created</span>
<span class="sd"> """</span>
<span class="n">job</span> <span class="o">=</span> <span class="n">get_current_job</span><span class="p">()</span>
<span class="n">task</span><span class="p">,</span> <span class="n">created</span> <span class="o">=</span> <span class="n">ScheduledTask</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span>
<span class="n">job_id</span><span class="o">=</span><span class="n">job</span><span class="o">.</span><span class="n">get_id</span><span class="p">(),</span>
<span class="n">name</span><span class="o">=</span><span class="n">url</span>
<span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">requests</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="n">response_len</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">response</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="n">ScheduledTaskInstance</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">create</span><span class="p">(</span>
<span class="n">scheduled_task</span><span class="o">=</span><span class="n">task</span><span class="p">,</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">response_len</span><span class="p">,</span>
<span class="p">)</span>
<span class="k">return</span> <span class="n">response_len</span>
</pre></div>
</div>
<div class="section" id="settings-py">
<h3><a class="toc-backref" href="#id8">settings.py</a></h3>
<div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="n">BASE_DIR</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">__file__</span><span class="p">))</span>
<span class="n">SECRET_KEY</span> <span class="o">=</span> <span class="s">'123'</span>
<span class="n">DEBUG</span> <span class="o">=</span> <span class="bp">True</span>
<span class="n">TEMPLATE_DEBUG</span> <span class="o">=</span> <span class="bp">True</span>
<span class="n">ALLOWED_HOSTS</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">INSTALLED_APPS</span> <span class="o">=</span> <span class="p">(</span>
<span class="s">'django.contrib.admin'</span><span class="p">,</span>
<span class="s">'django.contrib.auth'</span><span class="p">,</span>
<span class="s">'django.contrib.contenttypes'</span><span class="p">,</span>
<span class="s">'django.contrib.sessions'</span><span class="p">,</span>
<span class="s">'django.contrib.messages'</span><span class="p">,</span>
<span class="s">'django.contrib.staticfiles'</span><span class="p">,</span>
<span class="s">'django_extensions'</span><span class="p">,</span>
<span class="s">'django_rq'</span><span class="p">,</span>
<span class="s">'tasks'</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">MIDDLEWARE_CLASSES</span> <span class="o">=</span> <span class="p">(</span>
<span class="s">'django.contrib.sessions.middleware.SessionMiddleware'</span><span class="p">,</span>
<span class="s">'django.middleware.common.CommonMiddleware'</span><span class="p">,</span>
<span class="s">'django.middleware.csrf.CsrfViewMiddleware'</span><span class="p">,</span>
<span class="s">'django.contrib.auth.middleware.AuthenticationMiddleware'</span><span class="p">,</span>
<span class="s">'django.contrib.auth.middleware.SessionAuthenticationMiddleware'</span><span class="p">,</span>
<span class="s">'django.contrib.messages.middleware.MessageMiddleware'</span><span class="p">,</span>
<span class="s">'django.middleware.clickjacking.XFrameOptionsMiddleware'</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">ROOT_URLCONF</span> <span class="o">=</span> <span class="s">'django_test_rq.urls'</span>
<span class="n">WSGI_APPLICATION</span> <span class="o">=</span> <span class="s">'django_test_rq.wsgi.application'</span>
<span class="n">DATABASES</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'default'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'ENGINE'</span><span class="p">:</span> <span class="s">'django.db.backends.sqlite3'</span><span class="p">,</span>
<span class="s">'NAME'</span><span class="p">:</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">BASE_DIR</span><span class="p">,</span> <span class="s">'db.sqlite3'</span><span class="p">),</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">LANGUAGE_CODE</span> <span class="o">=</span> <span class="s">'en-us'</span>
<span class="n">TIME_ZONE</span> <span class="o">=</span> <span class="s">'UTC'</span>
<span class="n">USE_I18N</span> <span class="o">=</span> <span class="bp">True</span>
<span class="n">USE_L10N</span> <span class="o">=</span> <span class="bp">True</span>
<span class="n">USE_TZ</span> <span class="o">=</span> <span class="bp">True</span>
<span class="n">STATIC_URL</span> <span class="o">=</span> <span class="s">'/static/'</span>
<span class="c"># Use redis for caches</span>
<span class="n">CACHES</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">"default"</span><span class="p">:</span> <span class="p">{</span>
<span class="s">"BACKEND"</span><span class="p">:</span> <span class="s">"django_redis.cache.RedisCache"</span><span class="p">,</span>
<span class="s">"LOCATION"</span><span class="p">:</span> <span class="s">"redis://127.0.0.1:6379/0"</span><span class="p">,</span>
<span class="s">"OPTIONS"</span><span class="p">:</span> <span class="p">{</span>
<span class="s">"CLIENT_CLASS"</span><span class="p">:</span> <span class="s">"django_redis.client.DefaultClient"</span><span class="p">,</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="c"># Use the same redis as with caches for RQ</span>
<span class="n">RQ_QUEUES</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'default'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'USE_REDIS_CACHE'</span><span class="p">:</span> <span class="s">'default'</span><span class="p">,</span>
<span class="p">},</span>
<span class="p">}</span>
<span class="n">SESSION_ENGINE</span> <span class="o">=</span> <span class="s">"django.contrib.sessions.backends.cache"</span>
<span class="n">SESSION_CACHE_ALIAS</span> <span class="o">=</span> <span class="s">"default"</span>
<span class="n">RQ_SHOW_ADMIN_LINK</span> <span class="o">=</span> <span class="bp">True</span>
<span class="c"># Add a logger for rq_scheduler in order to display when jobs are queueud</span>
<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
<span class="s">'version'</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
<span class="s">'disable_existing_loggers'</span><span class="p">:</span> <span class="bp">False</span><span class="p">,</span>
<span class="s">'formatters'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'simple'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'format'</span><span class="p">:</span> <span class="s">'</span><span class="si">%(asctime)s</span><span class="s"> </span><span class="si">%(levelname)s</span><span class="s"> </span><span class="si">%(message)s</span><span class="s">'</span>
<span class="p">},</span>
<span class="p">},</span>
<span class="s">'handlers'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'console'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'level'</span><span class="p">:</span> <span class="s">'DEBUG'</span><span class="p">,</span>
<span class="s">'class'</span><span class="p">:</span> <span class="s">'logging.StreamHandler'</span><span class="p">,</span>
<span class="s">'formatter'</span><span class="p">:</span> <span class="s">'simple'</span>
<span class="p">},</span>
<span class="p">},</span>
<span class="s">'loggers'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'django.request'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'handlers'</span><span class="p">:</span> <span class="p">[</span><span class="s">'console'</span><span class="p">],</span>
<span class="s">'level'</span><span class="p">:</span> <span class="s">'DEBUG'</span><span class="p">,</span>
<span class="s">'propagate'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="p">},</span>
<span class="s">'rq_scheduler'</span><span class="p">:</span> <span class="p">{</span>
<span class="s">'handlers'</span><span class="p">:</span> <span class="p">[</span><span class="s">'console'</span><span class="p">],</span>
<span class="s">'level'</span><span class="p">:</span> <span class="s">'DEBUG'</span><span class="p">,</span>
<span class="s">'propagate'</span><span class="p">:</span> <span class="bp">True</span><span class="p">,</span>
<span class="p">},</span>
<span class="p">},</span>
<span class="p">}</span>
</pre></div>
<p>By default, rq_scheduler won’t log anything so we won’t be able to see
any output when new instances of each scheduled task are queued for execution.
That’s why we’ve overriden the <span class="caps">LOGGING</span> setting in order to actually log
rq_scheduler output to the console.</p>
</div>
<div class="section" id="running-the-project">
<h3><a class="toc-backref" href="#id9">Running the project</a></h3>
<p>I recommend using <a class="reference external" href="https://www.vagrantup.com/">Vagrant</a> to start a stock ubuntu/trusty32 box. After that, install redis, virtualenv and virtualenvwrapper
and create/activate a virtualenv named <tt class="docutils literal">rq</tt>. You can go to the home directory of <tt class="docutils literal"><span class="pre">django-test-rq</span></tt>
and install requirements through <tt class="docutils literal">pip install requirements.txt</tt> and create the database tables with
<tt class="docutils literal">python manage.py migrate</tt>. Finally you may run the project with <tt class="docutils literal">python manage.py runserver_plus</tt>.</p>
</div>
</div>
<div class="section" id="rqworker-and-rqscheduler">
<h2><a class="toc-backref" href="#id10">rqworker and rqscheduler</a></h2>
<p>Before scheduling any tasks we need to run two more processes:</p>
<ul class="simple">
<li>rqworker: This is a worker that dequeues jobs from the queue and executes them. We could run more than one onstance of this job if we need it.</li>
<li>rqscheduler: This is a process that runs every one minute and checks if there are scheduled jobs that have to be executed. If yes, it will add them to the queue in order to be executed by a worker.</li>
</ul>
<div class="section" id="for-development">
<h3><a class="toc-backref" href="#id11">For development</a></h3>
<p>If you want to run rqworker and rqscheduler for your development environment you can just do it with
running <tt class="docutils literal">python manage.py rqworker</tt> and <tt class="docutils literal">python mange.py rqscheduler</tt> through screen/tmux. If everything
is allright you should see tasks being added to the queue and scheduled (you may need to refresh the
homepage before seeing everything since a task may be executed after the response is created).</p>
<p>Also, keep in mind that rqscheduler runs once every minute by default so you may need to wait up to
minute to see a <tt class="docutils literal">ScheduledTask</tt> instance. Also, this means that you can’t run more than one scheduled
task instance per minute.</p>
</div>
<div class="section" id="for-production">
<h3><a class="toc-backref" href="#id12">For production</a></h3>
<p>Trying to create daemons through screen is not
sufficient for a production envornment since we’d like to actually have logging, monitoring and of course
automatically start rqworker and rqscheduler when the server boots.</p>
<p>For this, I recommend using the <a class="reference external" href="http://supervisord.org/">supervisord</a> tool which
can be used to monitor and control a number of processes. There are other similar tools, however I’ve
found supervisord the easier to use.</p>
<p>In order to monitor/control a process through supervisord you need to add a <tt class="docutils literal">[program:progrname]</tt> section in
supervisord’s configuration and pass a number of parameters. The <tt class="docutils literal">progname</tt> is the name of the monitoring
process. Here’s how rqworker can be configured using supervisord:</p>
<pre class="code literal-block">
[program:rqworker]
command=python manage.py rqworker
directory=/vagrant/progr/py/rq/django-test-rq
environment=PATH="/home/vagrant/.virtualenvs/rq/bin"
user=vagrant
</pre>
<p>The options used will chdir to <tt class="docutils literal">directory</tt> and execute <tt class="docutils literal">command</tt> as <tt class="docutils literal">user</tt>. The <tt class="docutils literal">environment</tt>
option can be used to set envirotnment variables - here we set <tt class="docutils literal"><span class="caps">PATH</span></tt> in order to use a specific
virtual environment. This will allow you to monitor rqworker through supervisord and log its
output to a file in <tt class="docutils literal">/var/log/supervisor</tt> (by default). A similar entry needs to be added for
rqscheduler of course. If everything has been configured correctly, when you reload the supervisord
settings you can run <tt class="docutils literal">sudo /usr/bin/supervisorctl</tt> and should see something like</p>
<pre class="code literal-block">
rqscheduler RUNNING pid 1561, uptime 0:00:03
rqworker RUNNING pid 1562, uptime 0:00:03
</pre>
<p>Also, tho log files should contain some debug info.</p>
</div>
</div>
<div class="section" id="conclusion">
<h2><a class="toc-backref" href="#id13">Conclusion</a></h2>
<p>Although using job queues makes it more difficult for the developer and adds at least one
(and probably more) points of failure to a project (the workers, the broker etc) their
usage, even for very simple projects is unavoidable.</p>
<p>Unless a complex, enterprise solution like celery is really required for a project
I recommend using the much simpler and easier to configure <span class="caps">RQ</span> for all your
asynchronous and scheduled task needs. Using <span class="caps">RQ</span> (and the relative projects django-rq
and rq-scheduler) we can easily add production ready queueued and scheduled jobs to
any django project.</p>
<p>In this article we presented a small introduction to <span class="caps">RQ</span> and its friends and saw how
to configure django to use it in a production ready environment using a small
django project (<a class="reference external" href="https://github.com/spapas/django-test-rq">https://github.com/spapas/django-test-rq</a>) which was implemented as a companion
to help readers quickly test the concepts presented here.</p>
</div>
</div>
</article>
<article>
<header>
<h1 class="entry-title">
<a href="http://spapas.github.io/2015/01/21/django-model-auditing/">Django model auditing</a>
</h1>
<p class="meta">
<time datetime="2015-01-21T14:20:00+02:00" pubdate>Τετ 21 Ιανουάριος 2015</time> </p>
</header>
<div class="entry-content"><div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#introduction" id="id5">Introduction</a></li>
<li><a class="reference internal" href="#adding-simple-auditing-functionality-ourselves" id="id6">Adding simple auditing functionality ourselves</a></li>
<li><a class="reference internal" href="#example" id="id7">Example</a><ul>
<li><a class="reference internal" href="#models-py" id="id8">models.py</a></li>
<li><a class="reference internal" href="#forms-py" id="id9">forms.py</a></li>
<li><a class="reference internal" href="#views-py" id="id10">views.py</a></li>
<li><a class="reference internal" href="#urls-py" id="id11">urls.py</a></li>
<li><a class="reference internal" href="#templates" id="id12">templates</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-django-simple-history" id="id13">Using django-simple-history</a><ul>
<li><a class="reference internal" href="#installation" id="id14">Installation</a></li>
<li><a class="reference internal" href="#id1" id="id15">Example</a></li>
<li><a class="reference internal" href="#usage" id="id16">Usage</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-django-reversion" id="id17">Using django-reversion</a><ul>
<li><a class="reference internal" href="#id2" id="id18">Installation</a></li>
<li><a class="reference internal" href="#id3" id="id19">Example</a></li>
<li><a class="reference internal" href="#id4" id="id20">Usage</a></li>
<li><a class="reference internal" href="#comparing-versions-with-django-reversion-compare" id="id21">Comparing versions with django-reversion-compare</a></li>
</ul>
</li>
<li><a class="reference internal" href="#conclusion" id="id22">Conclusion</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id5">Introduction</a></h2>
<p>An auditing trail is a common requirement in most non-trivial applications. Organizations
need to know <em>who</em> did the change, <em>when</em> it was done and <em>what</em> was actually changed.
In this post we will see three
different solution in order to add this functionality in Django: doing it ourselves,
using django-simple-history and using django-reversion.</p>
<p><em>Update 24/09/2015:</em> Added a paragraph describing the django-reversion-compare which is
a great addon for django-reversion that makes finding differences between versions a breeze!</p>
</div>
<div class="section" id="adding-simple-auditing-functionality-ourselves">
<h2><a class="toc-backref" href="#id6">Adding simple auditing functionality ourselves</a></h2>
<p>A simple way to actually do auditing is to keep four extra fields in our models:
<tt class="docutils literal">created_by</tt>, <tt class="docutils literal">created_on</tt>, <tt class="docutils literal">modified_by</tt> and <tt class="docutils literal">modified_on</tt>. The first two
will be filled when the model instance is created while the latter two will be
changed whenever the model instance is saved. So we only have <em>who</em> and <em>whe</em>.
Sometimes, these are enough so let’s see how easy it is to implement it in django.</p>
<p>We’ll need an abstract model that could be used as a base class for models that need auditing:</p>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="k">class</span> <span class="nc">Auditable</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
<span class="n">created_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now_add</span> <span class="o">=</span> <span class="bp">True</span><span class="p">)</span>
<span class="n">created_by</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">'created_by'</span><span class="p">)</span>
<span class="n">modified_on</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">auto_now</span> <span class="o">=</span> <span class="bp">True</span><span class="p">)</span>
<span class="n">modified_by</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">settings</span><span class="o">.</span><span class="n">AUTH_USER_MODEL</span><span class="p">,</span> <span class="n">related_name</span><span class="o">=</span><span class="s">'modified_by'</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
<span class="n">abstract</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
<p>Models inheriting from <tt class="docutils literal">Auditable</tt> will contain their datetime of creation and modification
which will be automatically filled using the very usefull <tt class="docutils literal">auto_now_add_</tt> (which will
set the current datetime when the model instance is created) and <tt class="docutils literal">auto_now_</tt> (which will
set the current datetime when the model instance is modified).</p>
<p>Such models will also have two foreign keys to <tt class="docutils literal">User</tt>, one for the user
that created the and one of the user that modified them. The problem with these two fields
is that they cannot be filled automatically (like the datetimes) because the user that
actually did create/change the objects must be provided!</p>
<p>Since I am really fond of CBVs I will present a simple mixin that can be used with CreateView
and UpdateView and does exactly that:</p>
<div class="highlight"><pre><span class="k">class</span> <span class="nc">AuditableMixin</span><span class="p">(</span><span class="nb">object</span><span class="p">,):</span>
<span class="k">def</span> <span class="nf">form_valid</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">form</span><span class="p">,</span> <span class="p">):</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">form</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">created_by</span><span class="p">:</span>
<span class="n">form</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">created_by</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span>
<span class="n">form</span><span class="o">.</span><span class="n">instance</span><span class="o">.</span><span class="n">modified_by</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">user</span>
<span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">AuditableMixin</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">form_valid</span><span class="p">(</span><span class="n">form</span><span class="p">)</span>
</pre></div>
<p>The above mixin overrides the <tt class="docutils literal">form_valid</tt> method of <tt class="docutils literal">CreateView</tt> and <tt class="docutils literal">UpdateView</tt>:
First it checks if the object is created (if it is created it won’t be saved in the
database yet thus it won’t have an id) in order to set the <tt class="docutils literal">created_by</tt> attribute to
the current user. After that it will set the <tt class="docutils literal">modified_by</tt> attribute of the object to
the current user. Finally, it will call the next <tt class="docutils literal">form_valid</tt> method to do whatever
is required (save the model instance and redirect to <tt class="docutils literal">success_url</tt> by default).</p>
<p>The views using <tt class="docutils literal">AuditableMixin</tt> should allow only logged in users (or else an
exception will be thrown). Also, don’t forget to exclude the <tt class="docutils literal">created_by</tt> and <tt class="docutils literal">modified_by</tt>
fields from your model form (<tt class="docutils literal">created_on</tt> and <tt class="docutils literal">modified_on</tt> will automatically be excluded).</p>
</div>
<div class="section" id="example">
<h2><a class="toc-backref" href="#id7">Example</a></h2>
<p>Let’s see a simple example of creating a small django application using the previously defined abstract model and mixin:</p>
<div class="section" id="models-py">
<h3><a class="toc-backref" href="#id8">models.py</a></h3>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf</span> <span class="kn">import</span> <span class="n">settings</span>
<span class="kn">from</span> <span class="nn">django.core.urlresolvers</span> <span class="kn">import</span> <span class="n">reverse</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>
<span class="kn">from</span> <span class="nn">auditable.models</span> <span class="kn">import</span> <span class="n">Auditable</span>
<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">Auditable</span><span class="p">):</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">128</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="k">return</span> <span class="n">reverse</span><span class="p">(</span><span class="s">"book_list"</span><span class="p">)</span>
</pre></div>
<p>In the above we suppose that the <tt class="docutils literal">Auditable</tt> abstract model is imported from the
<tt class="docutils literal">auditable.models</tt> module and that a view named <tt class="docutils literal">book_list</tt> that shows all books exists.</p>
</div>
<div class="section" id="forms-py">
<h3><a class="toc-backref" href="#id9">forms.py</a></h3>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.forms</span> <span class="kn">import</span> <span class="n">ModelForm</span>
<span class="k">class</span> <span class="nc">BookForm</span><span class="p">(</span><span class="n">ModelForm</span><span class="p">):</span>
<span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>
<span class="n">fields</span> <span class="o">=</span> <span class="p">[</span><span class="s">'name'</span><span class="p">,</span> <span class="s">'author'</span><span class="p">]</span>
</pre></div>
<p>Show only <tt class="docutils literal">name</tt> and <tt class="docutils literal">author</tt> fields (and not the auditable fields) in the <tt class="docutils literal">Book ModelForm</tt>.</p>
</div>
<div class="section" id="views-py">
<h3><a class="toc-backref" href="#id10">views.py</a></h3>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.views.generic.edit</span> <span class="kn">import</span> <span class="n">CreateView</span><span class="p">,</span> <span class="n">UpdateView</span>
<span class="kn">from</span> <span class="nn">django.views.generic</span> <span class="kn">import</span> <span class="n">ListView</span>
<span class="kn">from</span> <span class="nn">auditable.views</span> <span class="kn">import</span> <span class="n">AuditableMixin</span>
<span class="kn">from</span> <span class="nn">models</span> <span class="kn">import</span> <span class="n">Book</span>
<span class="kn">from</span> <span class="nn">forms</span> <span class="kn">import</span> <span class="n">BookForm</span>
<span class="k">class</span> <span class="nc">BookCreateView</span><span class="p">(</span><span class="n">AuditableMixin</span><span class="p">,</span> <span class="n">CreateView</span><span class="p">):</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>
<span class="n">form_class</span> <span class="o">=</span> <span class="n">BookForm</span>
<span class="k">class</span> <span class="nc">BookUpdateView</span><span class="p">(</span><span class="n">AuditableMixin</span><span class="p">,</span> <span class="n">UpdateView</span><span class="p">):</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>
<span class="n">form_class</span> <span class="o">=</span> <span class="n">BookForm</span>
<span class="k">class</span> <span class="nc">BookListView</span><span class="p">(</span><span class="n">ListView</span><span class="p">):</span>
<span class="n">model</span> <span class="o">=</span> <span class="n">Book</span>
</pre></div>
<p>We import the <tt class="docutils literal">AuditableMixin</tt> from <tt class="docutils literal">auditable.views</tt> and make our Create and Update views
inherit from this mixin also in addition to <tt class="docutils literal">CreateView</tt> and <tt class="docutils literal">UpdateView</tt>. Pay attention that our
mixin is placed <em>before</em> CreateView in order to call <tt class="docutils literal">form_valid</tt> in the proper order: When multiple
inheritance is used like this python will check each class from left to right to find the proper method
and call it. For example, in our <tt class="docutils literal">BookCreateView</tt>, when the <tt class="docutils literal">form_valid</tt> method is called, python
will first check if <tt class="docutils literal">BookCreateView</tt> has a <tt class="docutils literal">form_valid</tt> method. Since it does not, it will check
if <tt class="docutils literal">AuditableMixin</tt> has a <tt class="docutils literal">form_valid</tt> method and call it. Now, we are calling the <tt class="docutils literal"><span class="pre">super(...).form_valid()</span></tt> in the
<tt class="docutils literal">AuditableMixin</tt> <tt class="docutils literal">form_valid</tt>, so the <tt class="docutils literal">form_valid</tt> of <tt class="docutils literal">CreateView</tt> will <em>also</em> be called.</p>
<p>A simple <tt class="docutils literal">ListView</tt> is also added to just show the info on all books.</p>
</div>
<div class="section" id="urls-py">
<h3><a class="toc-backref" href="#id11">urls.py</a></h3>
<div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.conf.urls</span> <span class="kn">import</span> <span class="n">patterns</span><span class="p">,</span> <span class="n">include</span><span class="p">,</span> <span class="n">url</span>
<span class="kn">from</span> <span class="nn">views</span> <span class="kn">import</span> <span class="n">BookCreateView</span><span class="p">,</span> <span class="n">BookUpdateView</span><span class="p">,</span> <span class="n">BookListView</span>
<span class="n">urlpatterns</span> <span class="o">=</span> <span class="n">patterns</span><span class="p">(</span><span class="s">''</span><span class="p">,</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^accounts/login/$'</span><span class="p">,</span> <span class="s">'django.contrib.auth.views.login'</span><span class="p">,</span> <span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^accounts/logout/$'</span><span class="p">,</span> <span class="s">'django.contrib.auth.views.logout'</span><span class="p">,</span> <span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^create/$'</span><span class="p">,</span> <span class="n">BookCreateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s">'create_book'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^update/(?P<pk>\d+)/$'</span><span class="p">,</span> <span class="n">BookUpdateView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s">'update_book'</span><span class="p">),</span>
<span class="n">url</span><span class="p">(</span><span class="s">r'^$'</span><span class="p">,</span> <span class="n">BookListView</span><span class="o">.</span><span class="n">as_view</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="s">'book_list'</span><span class="p">),</span>
<span class="p">)</span>
</pre></div>
<p>Just add the previously defined Create/Update/List views along with a login/logout views.</p>
</div>
<div class="section" id="templates">
<h3><a class="toc-backref" href="#id12">templates</a></h3>
<p>You’ll need four templates:</p>
<ul class="simple">
<li>books/book_list.html: Show the list of books</li>
<li>books/book_form.html: Show the book editing form</li>
<li>registration/login.html: Login form</li>
<li>registration/logout.html: Logout message</li>
</ul>
</div>
</div>
<div class="section" id="using-django-simple-history">
<h2><a class="toc-backref" href="#id13">Using django-simple-history</a></h2>
<p><a class="reference external" href="https://github.com/treyhunner/django-simple-history">django-simple-history</a> can be used to not only store the user and date of each modification
but a different version for each modification. To do that, for every model that is registered
to be used with django-simple-history, it wil create a second table in
the database hosting all versions (historical records) of that model. As we can understand this is really powerfull
since we can see exactly what was changed and also do normal <span class="caps">SQL</span> queries on that!</p>
<div class="section" id="installation">
<h3><a class="toc-backref" href="#id14">Installation</a></h3>
<p>To use django-simple-history in a project, after we do a <tt class="docutils literal">pip install <span class="pre">django-simple-history</span></tt>,
we just need to add it to <tt class="docutils literal">INSTALLED_APPS</tt> and
add the <tt class="docutils literal">simple_history.middleware.HistoryRequestMiddleware</tt> to the <tt class="docutils literal">MIDDLEWARE_CLASSES</tt> list.</p>
<p>Finally, to keep the historical records for a model, just add an instace of <tt class="docutils literal">HistoricalRecords</tt> to this model.</p>
</div>
<div class="section" id="id1">
<h3><a class="toc-backref" href="#id15">Example</a></h3>
<p>For example, our previously defined <tt class="docutils literal">Book</tt> model will be modified like this:</p>
<div class="highlight"><pre>class SHBook(models.Model):
name = models.CharField(max_length=128)
author = models.CharField(max_length=128)
def get_absolute_url(self):
return reverse("shbook_list")
history = HistoricalRecords()
</pre></div>
<p>When we run <tt class="docutils literal">python manage.py makemigrations</tt> and <tt class="docutils literal">migrate</tt> this, we’ll see that beyond the table for SHBook, a table for HistoricalSHBook will be created:</p>
<pre class="code literal-block">
Migrations for 'sample':
0002_historicalshbook_shbook.py:
- Create model HistoricalSHBook
- Create model SHBook
</pre>
<p>Let’s see the schema of historicalshbook:</p>
<pre class="code literal-block">
CREATE TABLE "sample_historicalshbook" (
"id" integer NOT NULL,
"name" varchar(128) NOT NULL,
"author" varchar(128) NOT NULL,
"history_id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"history_date" datetime NOT NULL,
"history_type" varchar(1) NOT NULL,
"history_user_id" integer NULL REFERENCES "auth_user" ("id")
);
</pre>
<p>So we see that it has the <em>same</em> fields as with <tt class="docutils literal">SHBook</tt> (<tt class="docutils literal">id, name, author</tt>) with the addition of
the primary key (<tt class="docutils literal">history_id</tt>) of this historical record, the date and user that did the change
(<tt class="docutils literal">history_date</tt>, <tt class="docutils literal">history_user_id</tt>) and the type of the record (created / update / delete).</p>
<p>So, just by adding a <tt class="docutils literal">HistoricalRecords()</tt> attribute to our model definition we’ll get complete auditing
for the instance of that model</p>
</div>
<div class="section" id="usage">
<h3><a class="toc-backref" href="#id16">Usage</a></h3>
<p>To find out information about the historical records we’ll just use the <tt class="docutils literal">HistoricalRecords()</tt> attribute
of that model:</p>
<p>For example, running <tt class="docutils literal">SHBook.history.filter(id=1)</tt> will return all historical records of the book with
<tt class="docutils literal">id = 1</tt>. For each one of them we have can use the following:</p>
<ul class="simple">
<li>get the user that made the change through the <tt class="docutils literal">history_user</tt> attribute</li>
<li>get the date of the change through the <tt class="docutils literal">history_date</tt> attribute</li>
<li>get the type of the change through the <tt class="docutils literal">history_type</tt> attribute (and the corresponding <tt class="docutils literal">get_history_type_dispaly</tt>)</li>
<li>get a model instance as it was then through the <tt class="docutils literal">history_object</tt> attribute (in order to <tt class="docutils literal">save()</tt> it and revert to this version)</li>
</ul>
</div>
</div>
<div class="section" id="using-django-reversion">
<h2><a class="toc-backref" href="#id17">Using django-reversion</a></h2>
<p><a class="reference external" href="https://github.com/etianen/django-reversion">django-reversion</a> offers more or less the same functionality of django-simple-history by following a different philosophy:
Instead of creating an extra table holding the history records for each model, it insteads converts all the fields of each model
to json and stores that <span class="caps">JSON</span> in the database in a text field.</p>
<p>This has the advantage that no extra tables are created to the database but the disadvantage that you can’t easily query
your historical records. So you may choose one or the other depending on your actual requirements.</p>
<div class="section" id="id2">
<h3><a class="toc-backref" href="#id18">Installation</a></h3>
<p>To use django-reversion in a project, after we do a <tt class="docutils literal">pip install <span class="pre">django-reversion</span></tt>,
we just need to add it to <tt class="docutils literal">INSTALLED_APPS</tt> and
add the <tt class="docutils literal">reversion.middleware.RevisionMiddleware</tt> to the <tt class="docutils literal">MIDDLEWARE_CLASSES</tt> list.</p>
<p>In order to save the revisions of a model, you need to register this model to django-reversion. This can be
done either through the django-admin, by inheriting the admin class of that model from <tt class="docutils literal">reversion.VersionAdmin</tt>
or, if you don’t want to use the admin by <tt class="docutils literal">reversion.register</tt> decorator.</p>
</div>
<div class="section" id="id3">
<h3><a class="toc-backref" href="#id19">Example</a></h3>
<p>To use django-reversion to keep track of changes to <tt class="docutils literal">Book</tt> we can modify it like this:</p>
<div class="highlight"><pre>@reversion.register
class RBook(models.Model):
name = models.CharField(max_length=128)
author = models.CharField(max_length=128)
def get_absolute_url(self):
return reverse("rbook_list")
</pre></div>
<p>django-reversion uses two tables in the database to keep track of revisions: <tt class="docutils literal">revision</tt> and <tt class="docutils literal">version</tt>. Let’s
take a look at their schemata:</p>
<pre class="code literal-block">
.schema reversion_revision
CREATE TABLE "reversion_revision" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"manager_slug" varchar(200) NOT NULL,
"date_created" datetime NOT NULL,
"comment" text NOT NULL,
"user_id" integer NULL REFERENCES "auth_user" ("id")
);
.schema reversion_version
CREATE TABLE "reversion_version" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"object_id" text NOT NULL,
"object_id_int" integer NULL,
"format" varchar(255) NOT NULL,
"serialized_data" text NOT NULL,
"object_repr" text NOT NULL,
"content_type_id" integer NOT NULL REFERENCES "django_content_type" ("id"),
"revision_id" integer NOT NULL REFERENCES "reversion_revision" ("id")
);