-
Notifications
You must be signed in to change notification settings - Fork 2
/
index2.html
2101 lines (2028 loc) · 124 KB
/
index2.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/09/01/django-rq-redux/">django-rq redux: advanced techniques and tools</a>
</h1>
<p class="meta">
<time datetime="2015-09-01T14:20:00+03:00" pubdate>Τρι 01 Σεπτέμβριος 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="#displaying-your-task-progress" id="id2">Displaying your task progress</a></li>
<li><a class="reference internal" href="#displaying-your-queue-statistics" id="id3">Displaying your queue statistics</a></li>
<li><a class="reference internal" href="#making-sure-that-workers-for-your-queue-are-actually-running" id="id4">Making sure that workers for your queue are actually running</a></li>
<li><a class="reference internal" href="#checking-how-many-jobs-are-in-the-queue" id="id5">Checking how many jobs are in the queue</a></li>
<li><a class="reference internal" href="#better-exception-handling" id="id6">Better exception handling</a></li>
<li><a class="reference internal" href="#multiple-django-apps-single-redis-db" id="id7">Multiple django-apps, single redis db</a></li>
<li><a class="reference internal" href="#low-level-debugging" id="id8">Low level debugging</a></li>
<li><a class="reference internal" href="#conclusion" id="id9">Conclusion</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id1">Introduction</a></h2>
<p>In the <a class="reference external" href="http://spapas.github.io/2015/01/27/async-tasks-with-django-rq/">previous django-rq article</a>
we presented a quick introduction to asynchronous job queues and created a
small (but complete) project that used rq and django-rq to implement asynchronous
job queues in a django project.</p>
<p>In this article, we will present some more advanced techniques and tools
for improving the capabilities of our asynchronous tasks and
integrate them to the <a class="reference external" href="https://github.com/spapas/django-test-rq">https://github.com/spapas/django-test-rq</a> project (please
checkout tag django-rq-redux
<tt class="docutils literal">git checkout <span class="pre">django-rq-redux</span></tt>)</p>
</div>
<div class="section" id="displaying-your-task-progress">
<h2><a class="toc-backref" href="#id2">Displaying your task progress</a></h2>
<p>Sometimes, especially for long-running tasks it is useful to let
the user (task initiator) know what is the status of each task he’s started. For this,
I recommend creating a task-description model that will hold the required information for this
task with more or less the following fields (please also check <tt class="docutils literal">LongTask</tt> model of django-test-rq):</p>
<pre class="code literal-block">
class LongTask(models.Model):
created_on = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=128, help_text='Enter a unique name for the task',)
progress = models.PositiveIntegerField(default=0)
result = models.CharField(max_length=128, blank=True, null=True)
</pre>
<p>Now, when the view that starts the task is <tt class="docutils literal"><span class="caps">POST</span></tt> ed, you’ll first create
the <tt class="docutils literal">LongTask</tt> model instance with a result of <tt class="docutils literal">'<span class="caps">QUEUED</span>'</tt> and a progress
of 0 (and a name that identifies your task) and then you’ll start the real task
asynchronously by passing the LongTask instance, something like this (also check
<tt class="docutils literal">LongTaskCreateView</tt>):</p>
<pre class="code literal-block">
long_task = LongTask.objects.create(...)
long_runnig_task.delay(long_task)
</pre>
<p>In your asynchronous job, the first thing you’ll need to do is to set its result
to ‘<span class="caps">STARTED</span>’ and save it so that the user will immediately see when he’s job is
actually started. Also, if you can estimate its progress, you can update its
progress value with the current value so that the user will know how close he
is to finishing. Finally, when the job finished (or if it throws an expectable
exception) you’ll update its status accordingly. Here’s an example of my
long_running_task that just waits for the specifid amount of seconds:</p>
<pre class="code literal-block">
@job('django-test-rq-low')
def long_runnig_task(task):
job = get_current_job()
task.job_id = job.get_id()
task.result = 'STARTED'
duration_in_second_persentages = task.duration*1.0 / 100
for i in range(100):
task.progress = i
task.save()
print task.progress
time.sleep(duration_in_second_persentages)
task.result = 'FINISHED'
task.save()
return task.result
</pre>
<p>To have proper feedback I propose to have your task-description model instance
created by the view that starts the asynchronous task and <em>not</em> by the
actual task! This is important since the worker may be full so the asynchronous
task will need a lot of time until is actually started (or maybe there are no
running workers - more on this later) and the user will not be able to see
his task instance anywhere (unless of course you provide him access to the actual task
queue but I don’t recommend this).</p>
</div>
<div class="section" id="displaying-your-queue-statistics">
<h2><a class="toc-backref" href="#id3">Displaying your queue statistics</a></h2>
<p>django-rq has a really nice dashboard with a lot of queue statistics (
instructions here
<a class="reference external" href="https://github.com/ui/django-rq#queue-statistics">https://github.com/ui/django-rq#queue-statistics</a> and also on django-test-rq
project) which I recommend to always enable.</p>
<p>Also, there’s the individual use <a class="reference external" href="https://github.com/brutasse/django-rq-dashboard">django-rq-dashboard</a> project that could
be installed to display some more statistics, however the only extra
statistic that you can see throuh django-rq-dashboard is the status of
your scheduled jobs so I don’t recommend installing it if you don’t
use scheduling.</p>
</div>
<div class="section" id="making-sure-that-workers-for-your-queue-are-actually-running">
<h2><a class="toc-backref" href="#id4">Making sure that workers for your queue are actually running</a></h2>
<p>Using the django-rq dashboard you can make sure that all queues
have at least one worker. However, sometimes workers fail, or
maybe you’ve forgotten to start your workers or not configured
your application correctly (this happens to me all the time for
test/uat projects). So, for tasks that you want to display feedback
to the user, you can easily add a check to make sure that there are
active workers using the following code:</p>
<pre class="code literal-block">
from rq import Worker
import django_rq
redis_conn = django_rq.get_connection('default')
if len([
x for x in Worker.all(connection=redis_conn)
if 'django-test-rq-low' in x.queue_names()
]) == 0:
# Error -- no workers
</pre>
<p>With <tt class="docutils literal">Worker.all()</tt> you get all workers for a connection and the <tt class="docutils literal">queue_names()</tt>
method returns the names that each worker serves. So we check that we have at least one
worker for that queue.</p>
<p>This check can be added when the job is started and display a feedback error
to the user (check example in django-test-rq).</p>
<p>For quick tasks (for example sending emails etc) you should not display anything
to the user even if no workers are running (since the task <em>will</em> be queued and
will be executed eventually when the workers are started) but instead send an email to the administrators
so that they will start the workers.</p>
</div>
<div class="section" id="checking-how-many-jobs-are-in-the-queue">
<h2><a class="toc-backref" href="#id5">Checking how many jobs are in the queue</a></h2>
<p>To find out programatically how many jobs are actually in the queue (and display a message
if the queue has too many jobs etc) you’ll need to use the <tt class="docutils literal">Queue</tt> class, something like this:</p>
<pre class="code literal-block">
from rq import Queue
redis_conn = django_rq.get_connection('default')
queue = Queue('django-test-rq-default', connection=redis_conn)
print queue.name
print len(queue.jobs)
</pre>
</div>
<div class="section" id="better-exception-handling">
<h2><a class="toc-backref" href="#id6">Better exception handling</a></h2>
<p>When a job fails, rq will put it in a failed jobs queue and finish with it. You (as administrator)
won’t get any feedback and the user (unless he has access to that failed jobs queue) won’t be
able to do anything aboutt this job.</p>
<p>In almost all cases you can’t rely only on this behavior but instead you have to
<a class="reference external" href="http://python-rq.org/docs/exceptions/">install a custom exception handler</a>. Using the custom exception handler you can
do whatever you want for each failed job. For instance, you can create a new instance
of a <tt class="docutils literal">FailedTask</tt> model which will have information about the failure and the
original task allow the user (or administrator) to restart the failed task after
he’s fixed the error conditions.</p>
<p>Or, if you want to be informed when a job is failed, you can just send an email
to <tt class="docutils literal"><span class="caps">ADMINS</span></tt> and fall back to the default behavior to enqueue the failed task the
failed jobs queue (since job exception handlers can be chained).</p>
<p>A simple management command that starts a worker for a specific queue and installs
a custom exception handler follows:</p>
<pre class="code literal-block">
from django.conf import settings
from django.core.management.base import BaseCommand
import django_rq
from rq import Queue, Worker
def my_handler(job, *exc_info):
print "FAILURE"
print job
print exc_info
class Command(BaseCommand):
def handle(self, *args, **options):
redis_conn = django_rq.get_connection('default')
q = Queue(settings.DJANGO_TEST_RQ_LOW_QUEUE, connection=redis_conn)
worker = Worker([q], exc_handler=my_handler, connection=redis_conn)
worker.work()
</pre>
<p>This handler is for demonstration purposes since it just prints a message to the console
(so please do not use it)!</p>
</div>
<div class="section" id="multiple-django-apps-single-redis-db">
<h2><a class="toc-backref" href="#id7">Multiple django-apps, single redis db</a></h2>
<p>One thing to keep in mind is that the only thing that seperates the queues are
their name. If you have many django applications that define a "default" (or "low", "hight" etc)
and they all use the <em>same</em> redis database to store their queue, the workers
of each application won’t know which jobs belong to them and they’ll end up
dequeuing the wrong job types. This will lead to an exception or, if you
are really unlucky to a very nasty bug!</p>
<p>To avoid this, you can either use a different redis database (not database server)
for each of your apps or add a prefix with the name of your app to your queue names:</p>
<p>Each redis database server can host a number of databases that are identified
by a number (that’s what the /0 you see in <tt class="docutils literal"><span class="pre">redis://127.0.0.1:6379/0</span></tt> means)
and each one of them has a totally different keyspace. So, if you use /0 in an
application and /1 in another application, you’ll have no problems. This solution
has the disadvantage that you need to be really careful to use different database
numbers for your projects and also the number of possible databases that redis
can use is limited by a configuration file (so if you reach the maximum you’ll
need to also increase that number)!</p>
<p>Instead of this, you can avoid using the ‘default’ queue, and use queues that
contain your application name in their name, for example, for the sample project
you could create something like ‘django-test-rq-default’, ‘django-test-rq-low’,
‘django-test-rq-high’ etc. You need to configure the extra queues by adding them
to the <tt class="docutils literal">RQ_QUEUES</tt> dictionary (check settings.py of django-test-rq) and then
put the jobs to these queues using for example the job decorator
(<tt class="docutils literal"><span class="pre">@job('django-test-rq-default')</span></tt>)
and run your workers so that they will retrieve jobs from these queues
(<tt class="docutils literal">python manage.py rqworker <span class="pre">django-test-rq-default</span></tt>) and not the
default one (which may contain jobs of other applications).</p>
<p>If you use the default queue, and because you’ll need to use its name to
many places, I recommend to add a (f.i) <tt class="docutils literal">QUEUE_NAME = <span class="pre">'django-test-rq-default'</span></tt>
setting and use this instead of just a string to be totally <span class="caps">DRY</span>.</p>
<p><strong>Update 13/09/2015</strong>: Please notice that using a <em>single</em> redis database server
(either with multiple numeric databases or in the same database using a keyword
in keys to differentiate the apps) <a class="reference external" href="https://redislabs.com/blog/benchmark-shared-vs-dedicated-redis-instances#.VfUl0xHtmko">is not recommended</a> as commenter
Itamar Haber pointed out to me!</p>
<p>This is because for speed reasons redis uses a single thread to handle all requests
(regardless if they are in the same or different numerical databases), so all
resources may be used by a single, redis hungry, application and leave all others to starve!</p>
<p>Therefore, the recommended solution is to have a <em>different redis</em> server for each different
application. This does not mean that you need to have different servers, just to run
different instances of redis binding to different <span class="caps">IP</span> ports. Redis uses very little
resourecs when it is idle (<a class="reference external" href="http://redis.io/topics/faq">empty instance uses ~ 1 <span class="caps">MB</span> <span class="caps">RAM</span></a>) so you can run a lot
of instances in a single server.</p>
<p>Long story short, my proposal is to have a redis.conf <em>inside</em> your application root tree
(next to manage.py and requirements.txt) which has the redis options for each
application. The options in redis.conf that need to be changed per application
is the port that this redis instance will bind (this port also needs to be passed to
django settings.py) and the pid filename if you daemonize redis — I recommend using
a tool like <a class="reference external" href="http://supervisord.org/">supervisord</a> instead so that you won’t need any daemonizing and pid files for
each per-app-redis-instance!</p>
</div>
<div class="section" id="low-level-debugging">
<h2><a class="toc-backref" href="#id8">Low level debugging</a></h2>
<p>In this section I’ll present some commands that you can issue to your redis
server using a simple telnet connection to get various info about your queues. You
probably will never need to issue these commands to actually debug, but they
will answer some of your (scientific) questions! In the following, <tt class="docutils literal">></tt> is
things I type, <tt class="docutils literal">#</tt> are comments, <tt class="docutils literal"><span class="pre">[...]</span></tt> is more output and everything else is the output I get:</p>
<pre class="code literal-block">
> telnet 127.0.0.1 6379
# You won't see anything at first but you'll be connected and you can try typing things
> INFO
$1020
redis_version:2.4.10
redis_git_sha1:00000000
# [...]
db0:keys=83,expires=2
db1:keys=26,expires=1 # My redis server has two databases
# Now you'll see what you type!
> SELECT 1
+ OK # Now queries will be issued to database 1
> SELECT 0
+ OK # Now queries will be issued to database 0
KEYS rq* # List all rq related queues
*25
$43
rq:job:1d7afa32-3f90-4502-912f-d58eaa049fb1
$43
rq:queue:django-test-rq-low
$43
[...]
> SMEMBERS rq:workers # See workers
*1
$26
rq:worker:SERAFEIM-PC.6892
> LRANGE rq:queue:django-test-rq-low 0 100 # Check queued jobs
*2
$36
def896f4-84cb-4833-be6a-54d917f05271
$36
53cb1367-2fb5-46b3-99b2-7680397203b9
> HGETALL rq:job:def896f4-84cb-4833-be6a-54d917f05271 # Get info about this job
*16
$6
status
$6
queued
$11
description
$57
tasks.tasks.long_runnig_task(<LongTask: LongTask object>)
$10
created_at
$20
2015-09-01T09:04:38Z
$7
timeout
$3
180
$6
origin
$18
django-test-rq-low
$11
enqueued_at
$20
2015-09-01T09:04:38Z
$4
data
$409
[...] # data is the pickled parameters passed to the job !
> HGET rq:job:def896f4-84cb-4833-be6a-54d917f05271 status # Get only status
$6
queued
</pre>
<p>For more info on querying redis you can check the <a class="reference external" href="http://redis.io/documentation">redis documentation</a> and especially
<a class="reference external" href="http://redis.io/topics/data-types">http://redis.io/topics/data-types</a> and <a class="reference external" href="http://redis.io/commands">http://redis.io/commands</a>.</p>
</div>
<div class="section" id="conclusion">
<h2><a class="toc-backref" href="#id9">Conclusion</a></h2>
<p>Using some of the above techniques will help you in your asynchronous
task adventures with rq. I’ll try to keep this article updated with
any new techniques or tools I find in the future!</p>
</div>
</div>
</article>
<article>
<header>
<h1 class="entry-title">
<a href="http://spapas.github.io/2015/07/02/comprehensive-react-flux-tutorial-2/">A comprehensive React and Flux tutorial part 2: Flux</a>
</h1>
<p class="meta">
<time datetime="2015-07-02T14:20:00+03:00" pubdate>Πεμ 02 Ιούλιος 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="#flux-components" id="id2">Flux components</a></li>
<li><a class="reference internal" href="#the-react-flux-version" id="id3">The react-flux version</a><ul>
<li><a class="reference internal" href="#main-js" id="id4">main.js</a></li>
<li><a class="reference internal" href="#constants-js" id="id5">constants.js</a></li>
<li><a class="reference internal" href="#actions-js" id="id6">actions.js</a></li>
<li><a class="reference internal" href="#stores-js" id="id7">stores.js</a></li>
<li><a class="reference internal" href="#components-js" id="id8">components.js</a></li>
</ul>
</li>
<li><a class="reference internal" href="#explaining-the-data-flow" id="id9">Explaining the data flow</a></li>
<li><a class="reference internal" href="#a-better-code-organization" id="id10">A better code organization</a></li>
<li><a class="reference internal" href="#conclusion" id="id11">Conclusion</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h2><a class="toc-backref" href="#id1">Introduction</a></h2>
<p>In the <a class="reference external" href="http://spapas.github.io/2015/06/05/comprehensive-react-flux-tutorial/">first part of this series</a> we implemented a
not-so-simple one page application with full <span class="caps">CRUD</span> capabilities. In this part, we will
modify that application to make it use the Flux architecture. The full source code can
be found at <a class="reference external" href="https://github.com/spapas/react-tutorial">https://github.com/spapas/react-tutorial</a> (tag name react-flux). In the
In <a class="reference external" href="http://spapas.github.io/2015/09/08/more-complex-react-flux-example/">next part,</a> we will create an even more complex application
using react/flux!</p>
<p>I recommend reading Facebook’s <a class="reference external" href="https://facebook.github.io/flux/docs/overview.html">Flux overview</a> before reading this article — please
read it even if you find some concepts difficult to grasp (I know I found it difficult
the first time I read it), I will try to explain everything here. Also,
because a rather large number of extra components will need to be created, we are
going to split our javascript code to different files using <a class="reference external" href="http://browserify.org/">browserify</a> - you can
learn <a class="reference external" href="http://spapas.github.io/2015/05/27/using-browserify-watchify/">how to use browserify here</a>.</p>
</div>
<div class="section" id="flux-components">
<h2><a class="toc-backref" href="#id2">Flux components</a></h2>
<p>To implement the Flux architecture, an application needs to have at least a store and a dispatcher.</p>
<p>The store is the central place of truth for the application and the dispacher is the central
place of communications. The store should hold the
state (and any models/DAOs) of the application and notify the react components when this state is changed. Also,
the store will be notified by the dispatcher when an action happens (for example a button is clicked)
so that it will change the state. As a flow, we can think of something like this:</p>
<pre class="code literal-block">
a ui action on a component (click, change, etc) ->
^ dispatcher is notified ->
| store is notified (by the dispacher)->
| store state is changed ->
└─ component is notified (by the store) and updated to reflect the change
</pre>
<p>One thing to keep in mind is that although each flux application will have only one dispatcher, it may
have more stores, depending on the application’s architecture and separation of concerns. If there are
more than store, all will be notified by the dispatcher and change their state (if needed of course).
The ui will pass the action type and any optional parameters to the dispatcher and the dispatcher
will notify all stores with these parameters.</p>
<p>An optional component in the Flux architecture is the Action. An action is a store related class that
acts as an intermediate between the ui and the dispatcher. So, when a user clicks a button, an action
will be called that will notify the dispatcher. As we will see we can just call the dispatcher directly
from the components ui, but calling it through the Action makes the calls more consistent and creates
an interface.</p>
</div>
<div class="section" id="the-react-flux-version">
<h2><a class="toc-backref" href="#id3">The react-flux version</a></h2>
<p>Since we are using browserify, we will include a single file in our html file with a <tt class="docutils literal"><script></tt> tag
and everything else will be included through the <tt class="docutils literal">require</tt> function. We have the following packages
as requirements for browserify:</p>
<pre class="code literal-block">
"dependencies": {
"flux": "^2.0.3",
"jquery": "^2.1.4",
"react": "^0.13.3",
"reactify": "^1.1.1"
}
</pre>
<p>Also, in order to be able to use <span class="caps">JSX</span> with browserify, will use the <a class="reference external" href="https://github.com/andreypopp/reactify">reactify</a> transform. To apply it to
your project, change the <tt class="docutils literal">scripts</tt> of your <tt class="docutils literal">package.json</tt> to:</p>
<pre class="code literal-block">
"scripts": {
"watch": "watchify -v -d static/main.js -t reactify -o static/bundle.js",
"build": "browserify static/main.js -t reactify | uglifyjs -mc warnings=false > static/bundle.js"
},
</pre>
<div class="section" id="main-js">
<h3><a class="toc-backref" href="#id4">main.js</a></h3>
<p>The <tt class="docutils literal">main.js</tt> file will
just render the BookPanel component (the <tt class="docutils literal">components.js</tt> file contains the source for all React components) and call
the <tt class="docutils literal">reloadBooks</tt> function from <tt class="docutils literal">stores.js</tt> that will reload all books from the <span class="caps">REST</span> <span class="caps">API</span>:</p>
<pre class="code literal-block">
var React = require('react');
var components = require('./components');
var stores = require('./stores');
React.render(<components.BookPanel url='/api/books/' />, document.getElementById('content'));
stores.reloadBooks();
</pre>
</div>
<div class="section" id="constants-js">
<h3><a class="toc-backref" href="#id5">constants.js</a></h3>
<p>Before going into more complex modules, let’s present the <tt class="docutils literal">constants.js</tt> which just
exports some strings that will be passed to the dispatcher to differentiate between each
ui action:</p>
<pre class="code literal-block">
module.exports = {
BOOK_EDIT: 'BOOK_EDIT',
BOOK_EDIT_CANCEL: 'BOOK_EDIT_CANCEL',
BOOK_SAVE: 'BOOK_SAVE',
BOOK_SEARCH: 'BOOK_SEARCH',
BOOK_DELETE: 'BOOK_DELETE',
};
</pre>
<p>As we can see, these constants are exported as a single object so when we do something like
<tt class="docutils literal">var BookConstants = <span class="pre">require('./constants')</span></tt> we’ll the be able to refer to each constant
through <tt class="docutils literal">BookConstants.CONSTANT_NAME</tt>.</p>
</div>
<div class="section" id="actions-js">
<h3><a class="toc-backref" href="#id6">actions.js</a></h3>
<p>The <tt class="docutils literal">actions.js</tt> creates the dispatcher singleton and a BookActions object that defines the
actions for books.</p>
<pre class="code literal-block">
var BookConstants = require('./constants')
var Dispatcher = require('flux').Dispatcher;
var AppDispatcher = new Dispatcher();
var BookActions = {
search: function(query) {
AppDispatcher.dispatch({
actionType: BookConstants.BOOK_SEARCH,
query: query
});
},
save: function(book) {
AppDispatcher.dispatch({
actionType: BookConstants.BOOK_SAVE,
book: book
});
},
edit: function(book) {
AppDispatcher.dispatch({
actionType: BookConstants.BOOK_EDIT,
book: book
});
},
edit_cancel: function() {
AppDispatcher.dispatch({
actionType: BookConstants.BOOK_EDIT_CANCEL
});
},
delete: function(bookId) {
AppDispatcher.dispatch({
actionType: BookConstants.BOOK_DELETE,
bookId: bookId
});
}
};
module.exports.BookActions = BookActions;
module.exports.AppDispatcher = AppDispatcher;
</pre>
<p>As we can see, the BookActions is just a collection of methods that will
be called from the ui. Instead of calling BookActions.search() we could
just call the dispatch method with the correct parameter object (actionType
and optional parameter), both the BookActions object and the AppDispatcher
singleton are exported.</p>
<p>The dispatcher is imported from the flux requirement: It offers a functionality
to register callbacks for the various actions as we will see in the
next module. This is a rather simple class that we could implement ourselves
(each store passes a callback to the dispatcher that is called on the dispatch
method, passing actionType and any other parameters). The dispatcher also
offers a <tt class="docutils literal">waitFor</tt> method that can be used to ensure that the dispatch callback
for a store will be finished before another store’s dispatch callback (
when the second store uses the state of the first store — for example
when implementing a series of related dropdowns ).</p>
</div>
<div class="section" id="stores-js">
<h3><a class="toc-backref" href="#id7">stores.js</a></h3>
<p>The next module we will discuss is the <tt class="docutils literal">stores.js</tt> that contains the
<tt class="docutils literal">BookStore</tt> object.</p>
<pre class="code literal-block">
var $ = require('jquery');
var EventEmitter = require('events').EventEmitter;
var AppDispatcher = require('./actions').AppDispatcher;
var BookConstants = require('./constants')
var _state = {
books: [],
message:"",
editingBook: null
}
var _props = {
url: '/api/books/'
}
var _search = function(query) {
$.ajax({
url: _props.url+'?search='+query,
dataType: 'json',
cache: false,
success: function(data) {
_state.books = data;
BookStore.emitChange();
},
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
_state.message = err.toString();
BookStore.emitChange();
}
});
};
var _reloadBooks = function() {
_search('');
};
var _deleteBook = function(bookId) {
$.ajax({
url: _props.url+bookId,
method: 'DELETE',
cache: false,
success: function(data) {
_state.message = "Successfully deleted book!"
_clearEditingBook();
_reloadBooks();
},
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
_state.message = err.toString();
BookStore.emitChange();
}
});
};
var _saveBook = function(book) {
if(book.id) {
$.ajax({
url: _props.url+book.id,
dataType: 'json',
method: 'PUT',
data:book,
cache: false,
success: function(data) {
_state.message = "Successfully updated book!"
_clearEditingBook();
_reloadBooks();
},
error: function(xhr, status, err) {
_state.message = err.toString()
BookStore.emitChange();
}
});
} else {
$.ajax({
url: _props.url,
dataType: 'json',
method: 'POST',
data:book,
cache: false,
success: function(data) {
_state.message = "Successfully added book!"
_clearEditingBook();
_reloadBooks();
},
error: function(xhr, status, err) {
_state.message = err.toString()
BookStore.emitChange();
}
});
}
};
var _clearEditingBook = function() {
_state.editingBook = null;
};
var _editBook = function(book) {
_state.editingBook = book;
BookStore.emitChange();
};
var _cancelEditBook = function() {
_clearEditingBook();
BookStore.emitChange();
};
var BookStore = $.extend({}, EventEmitter.prototype, {
getState: function() {
return _state;
},
emitChange: function() {
this.emit('change');
},
addChangeListener: function(callback) {
this.on('change', callback);
},
removeChangeListener: function(callback) {
this.removeListener('change', callback);
}
});
AppDispatcher.register(function(action) {
switch(action.actionType) {
case BookConstants.BOOK_EDIT:
_editBook(action.book);
break;
case BookConstants.BOOK_EDIT_CANCEL:
_cancelEditBook();
break;
case BookConstants.BOOK_SAVE:
_saveBook(action.book);
break;
case BookConstants.BOOK_SEARCH:
_search(action.query);
break;
case BookConstants.BOOK_DELETE:
_deleteBook(action.bookId);
break;
}
return true;
});
module.exports.BookStore = BookStore;
module.exports.reloadBooks = _reloadBooks;
</pre>
<p>The <tt class="docutils literal">stores.js</tt> module exports only the <tt class="docutils literal">BookStore</tt> object and the <tt class="docutils literal">reloadBooks</tt> method (that could also be
called from inside the module since it’s just called when the application is loaded to load the books for the
first time). All other objects/funtions are private to the module.</p>
<p>As we saw, the <tt class="docutils literal">_state</tt> objects keep the global state of the application which are the list of books, the book
that is edited right now and the result message for any update we are doing. The ajax methods are more or less
the same as the ones in the react-only version of the application. However, please notice that when the ajax methods
return and have to set the result, instead of setting the state of a React object they are just calling the
<tt class="docutils literal">emitChange</tt> method of the <tt class="docutils literal">BookStore</tt> that will notify all react objects that "listen" to this store.
This is possible because the ajax (<span class="caps">DAO</span>) methods are in the same module with the store - if we wanted instead
to put them in different modules, we’d just need to add another action (e.g <tt class="docutils literal">ReloadBooks</tt>) that would
be called when the ajax method returns — this action would call the dispatcher which would in turn update the
state of the store.</p>
<p>We can see that we are importing the
AppDispatcher singleton and, depending on the action type we call the correct method that changes the state. So
when a BookActions action is called it will call the corresponding <tt class="docutils literal">AppDispatcher.register</tt> case branch which
will call the corresponding state-changing function.</p>
<p>The BookStore extends the <tt class="docutils literal">EventEmitter</tt> object (so we need to <tt class="docutils literal">require</tt> the <tt class="docutils literal">events</tt> module) in order to
notify the React components when the state of the store is changed. Instead of using <tt class="docutils literal">EventEmitter</tt> we could
just implement the emit change logic ourselves by saving all the listener callbacks to an array and calling them
all when there’s a state change (if we wanted to also add the ‘change’ parameter to group the listener
callbacks we’d just make the complex more complex, something not needed for our case):</p>
<pre class="code literal-block">
var BookStore = {
listeners: [],
getState: function() {
return _state;
},
emitChange: function() {
var i;
for(i=0;i<this.listeners.length;i++) {
this.listeners[i]();
}
},
addChangeListener: function(callback) {
this.listeners.push(callback);
},
removeChangeListener: function(callback) {
this.listeners.splice(this.listeners.indexOf(callback), 1);
}
};
</pre>
</div>
<div class="section" id="components-js">
<h3><a class="toc-backref" href="#id8">components.js</a></h3>
<p>Finally, the <tt class="docutils literal">components.js</tt> module contains all the React components. These are more
or less the same with the react-only version with three differences:</p>
<ul class="simple">
<li>When something happens in the ui, the corresponding <tt class="docutils literal">BookAction</tt> action is called with the needed parameter — no callbacks are passed between the components</li>
<li>The <tt class="docutils literal">BookPanel</tt> component registers with the <tt class="docutils literal">BookStore</tt> in order to be notified when the state changes and just gets its state from the store — these values are propagated to all other components through properties</li>
<li>The <tt class="docutils literal">BookForm</tt> and <tt class="docutils literal">SearcchPanel</tt> now hold their own temporary state instead of using the global state — notice that when a book is edited this book will be propagated to the <tt class="docutils literal">BookForm</tt> through the book property, however <tt class="docutils literal">BookForm</tt> needs to update its state through the <tt class="docutils literal">componentWillReceiveProps</tt> method.</li>
</ul>
<pre class="code literal-block">
var React = require('react');
var BookStore = require('./stores').BookStore;
var BookActions = require('./actions').BookActions;
var BookTableRow = React.createClass({
render: function() {
return (
<tr>
<td>{this.props.book.id}</td>
<td>{this.props.book.title}</td>
<td>{this.props.book.category}</td>
<td><a href='#' onClick={this.onClick}>Edit</a></td>
</tr>
);
},
onClick: function(e) {
e.preventDefault();
BookActions.edit(this.props.book);
}
});
var BookTable = React.createClass({
render: function() {
var rows = [];
this.props.books.forEach(function(book) {
rows.push(<BookTableRow key={book.id} book={book} />);
});
return (
<table>
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Category</th>
<th>Edit</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
});
var BookForm = React.createClass({
getInitialState: function() {
if (this.props.book) {
return this.props.book;
} else {
return {};
}
},
componentWillReceiveProps: function(props) {
if (props.book) {
this.setState(props.book);
} else {
this.replaceState({});
}
},
render: function() {
return(
<form onSubmit={this.onSubmit}>
<label forHtml='title'>Title</label><input ref='title' name='title' type='text' value={this.state.title} onChange={this.onFormChange} />
<label forHtml='category'>Category</label>
<select ref='category' name='category' value={this.state.category} onChange={this.onFormChange} >
<option value='CRIME' >Crime</option>
<option value='HISTORY'>History</option>
<option value='HORROR'>Horror</option>
<option value='SCIFI'>SciFi</option>
</select>
<br />
<input type='submit' value={this.state.id?"Save (id = " +this.state.id+ ")":"Add"} />
{this.state.id?<button onClick={this.onDeleteClick}>Delete</button>:""}
{this.state.id?<button onClick={this.onCancelClick}>Cancel</button>:""}
{this.props.message?<div>{this.props.message}</div>:""}
</form>
);
},
onFormChange: function() {
this.setState({
title: React.findDOMNode(this.refs.title).value,
category: React.findDOMNode(this.refs.category).value
})
},
onSubmit: function(e) {
e.preventDefault();
BookActions.save(this.state)
},
onCancelClick: function(e) {
e.preventDefault();
BookActions.edit_cancel()
},
onDeleteClick: function(e) {
e.preventDefault();
BookActions.delete(this.state.id)
}
});
var SearchPanel = React.createClass({
getInitialState: function() {
return {
search: '',
}
},
render: function() {
return (
<div className="row">
<div className="one-fourth column">
Filter: &nbsp;
<input ref='search' name='search' type='text' value={this.state.search} onChange={this.onSearchChange} />
{this.state.search?<button onClick={this.onClearSearch} >x</button>:''}
</div>
</div>
)
},
onSearchChange: function() {
var query = React.findDOMNode(this.refs.search).value;
if (this.promise) {
clearInterval(this.promise)
}
this.setState({
search: query
});
this.promise = setTimeout(function () {
BookActions.search(query);
}.bind(this), 200);
},
onClearSearch: function() {
this.setState({
search: ''
});
BookActions.search('');
}
});
var BookPanel = React.createClass({
getInitialState: function() {
return BookStore.getState();
},
render: function() {
return(
<div className="row">
<div className="one-half column">
<SearchPanel></SearchPanel>
<BookTable books={this.state.books} />
</div>
<div className="one-half column">
<BookForm
book={this.state.editingBook}
message={this.state.message}
/>
</div>
<br />
</div>
);
},
_onChange: function() {
this.setState( BookStore.getState() );
},
componentWillUnmount: function() {
BookStore.removeChangeListener(this._onChange);
},
componentDidMount: function() {
BookStore.addChangeListener(this._onChange);
}
});
module.exports.BookPanel = BookPanel ;
</pre>
<p>Only the <tt class="docutils literal">BookPanel</tt> is exported — all other react components will be private to the module.</p>
<p>We can see that, beyond BookPanel, the code of all other components
are more or less the same. However, <em>not</em> having to pass callbacks for state upddates
is a huge win for readability and DRYness.</p>
</div>
</div>
<div class="section" id="explaining-the-data-flow">
<h2><a class="toc-backref" href="#id9">Explaining the data flow</a></h2>
<p>I’ve added a bunch of console.log statements to see how the data/actions flow between
all the components when the "Edit" book is clicked. So, when we click "Edit" we see
the following messages to our console:</p>
<pre class="code literal-block">
Inside BookTableRow.onClick
Inside BookActions.edit
Inside AppDispatcher.register
Inside AppDispatcher.register case BookConstants.BOOK_EDIT
Inside _editBook
Inside BookStore.emitChange
Inside BookPanel._onChange
Inside BookForm.componentWillReceiveProps
Inside BookForm.render
</pre>
<p>First of all the <tt class="docutils literal">onClick</tt> method of <tt class="docutils literal">BookTableRow</tt> will be called (which is the onClick property of the
a href link) which will call <tt class="docutils literal">BookActions.edit</tt> and pass it the book of that specific row. The <tt class="docutils literal">edit</tt>
method will create a new dispatcher object by setting the <tt class="docutils literal">actionType</tt> and passing the <tt class="docutils literal">book</tt> and
pass it to <tt class="docutils literal">AppDispatcher.register</tt>. <tt class="docutils literal">register</tt> will go to the <tt class="docutils literal">BookConstants.BOOK_EDIT</tt> case branch
which will call the private <tt class="docutils literal">_editBook</tt> function. <tt class="docutils literal">_editBook</tt> will update the state of the store (by
setting the <tt class="docutils literal">_state.editingBook</tt> property and will call the <tt class="docutils literal">BookStore.emitChange</tt> method
which calls the dispatcher’s emit method, so all listening components will update. We only have one
component that listens to this emit, <tt class="docutils literal">BookPanel</tt> whose <tt class="docutils literal">_onChange</tt> method is called. This method
gets the application state from the <tt class="docutils literal">BookStore</tt> and updates its own state. Now, the state will be
propagated through properties - for example, for <tt class="docutils literal">BookForm</tt>, first its <tt class="docutils literal">componentWillReceiveProps</tt>
method will be called (with the new properties) and finally its <tt class="docutils literal">render</tt> method!</p>
<p>So the full data flow is something like this:</p>
<pre class="code literal-block">
user action/callback etc ->
component calls action ->
dispatcher informes stores ->
stores set their state ->
state holding components are notified and update their state ->
all other components are updated through properties
</pre>
</div>
<div class="section" id="a-better-code-organization">
<h2><a class="toc-backref" href="#id10">A better code organization</a></h2>
<p>As you’ve seen, I’ve only created four javascript modules (components, stores, actions and constants)
and put them all in the same folder. I did this for clarity and to keep everything together since