-
Notifications
You must be signed in to change notification settings - Fork 0
/
index19.html
764 lines (755 loc) · 76.7 KB
/
index19.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
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<title>IMDagger: Дневник</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Блог IMDagger: IT и жизнь" />
<meta name="keywords" content="python,lisp,scheme,racket,emacs,blender,программирование,моделирование,lua,c++,c,js,java,git,bazaar" />
<meta name="author" content="Alex Moiseenko (IMDagger)" />
<meta name="robots" content="noindex"/>
<!-- Open Graph -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" />
<link rel="shortcut icon" href="http://imdagger.github.io/favicon.ico" />
<link rel="stylesheet" href="/theme/css/html4css1.css" />
<link rel="stylesheet" href="/theme/css/style.css" />
<link rel="stylesheet" href="/theme/css/pygment.css" />
<link rel="stylesheet" href="/theme/css/math.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML,http://imdagger.github.io/theme/js/math.js"></script>
<script src="http://s3.amazonaws.com/nwapi/nwmatcher/nwmatcher-1.2.5-min.js"></script>
<!--[if (gte IE 6)&(lte IE 8)]>
<script type="text/javascript" src="/theme/js/selectivizr-min.js"></script>
<noscript><link rel="stylesheet" href="[fallback css]" /></noscript>
<![endif]-->
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link href="http://imdagger.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="IMDagger Atom-лента" />
</head>
<body>
<div class="row page-head">
<div class="row page-head-status page-head-status-top"><div class="col-sm-12 b-status mine"><p><i></i><a href="#" title="настроение" class="b-consistent-link"><b>Продать кому-то что-то всегда на деле сложнее, чем кажется</b></a></p></div></div>
<div class="col-sm-2 page-left">
<a href="#">
<img src="http://upics.yandex.ru/22199227/normal" ilo-full-src="http://upics.yandex.ru/22199227/normal">
</a>
</div>
<div class="col-sm-10 all-posts">
<div class="title-container">
<h1><b><a href="http://imdagger.github.io" class="fn nickname">IMDagger</a></b></h1>
</div>
<div class="title-menu">
<ul class="nav nav-tabs" role="tablist">
<li class="active">
<a href="#">Дневник</a>
</li>
<li><a href="http://fotki.yandex.ru/users/imdagger">Фотки</a></li>
<li><a href="http://imdagger.github.io/pages/o-sebe.html">О себе</a></li>
<li><a href="http://imdagger.github.io/pages/rss-lenta.html">RSS-лента</a></li>
</ul>
</div>
</div>
</div>
<div class="row page-body">
<div class="col-sm-2 page-left">
<div class="row widget widget-photo">
<a href="posts/2011/08/07/aga-popalsia/" class="b-user-photo__link"><img class="b-user-photo__img" src=" http://img-fotki.yandex.ru/get/5409/22199227.a/0_625fc_e780ccc7_L
?log_nocount=64720402854"></a>
</div><div class="row widget">
<div class="widget-content b-user-info">
<div class="widget__body">
<div class="widget-user-info__age">
<i class="widget-user-info__sex widget-user-info__sex_type_"></i> 27 лет
</div>
<div class="widget-user-info__place">
<a href="#">Гомель</a>, <a href="#">Беларусь</a> </div>
<ul class="contacts">
<li class="contact contact-type-email"><i></i><a href="mailto:[email protected]">[email protected]</a></li>
<li class="contact contact-type-ya-online"><i></i>[email protected]</li>
<li class="contact contact-type-icq"><i></i>350395088</li>
</ul>
</div>
</div>
</div>
<div class="row widget">
<div class="widget-content">
<div class="widget__title">
<div class="widget__title-link">Метрика</div>
</div>
<div class="widget__body">
<div class="widget-line">
<!-- noindex -->
<!-- googleoff: index -->
<div class="widget-entry">
<!-- Yandex.Metrika informer --><a href="https://metrika.yandex.ru/stat/?id=25746494&from=informer" target="_blank" rel="nofollow"><img src="//bs.yandex.ru/informer/25746494/3_1_FFFFFFFF_EFEFEFFF_0_pageviews" style="width:88px; height:31px; border:0;" alt="Яндекс.Метрика" title="Яндекс.Метрика: данные за сегодня (просмотры, визиты и уникальные посетители)" onclick="try{Ya.Metrika.informer({i:this,id:25746494,lang:'ru'});return false}catch(e){}"/></a><!-- /Yandex.Metrika informer --><!-- Yandex.Metrika counter --><script type="text/javascript">(function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter25746494 = new Ya.Metrika({id:25746494, clickmap:true, trackLinks:true, accurateTrackBounce:true}); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = (d.location.protocol == "https:" ? "https:" : "http:") + "//mc.yandex.ru/metrika/watch.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks");</script><noscript><div><img src="//mc.yandex.ru/watch/25746494" style="position:absolute; left:-9999px;" alt="" /></div></noscript><!-- /Yandex.Metrika counter -->
<!-- googleon: index -->
<!-- /noindex -->
</div>
</div>
</div>
</div>
</div><div class="row widget">
<div class="widget-content">
<div class="widget__title">
<div class="widget__title-link">Популярное в дневнике</div>
</div>
<div class="widget__body">
<div class="widget-line">
<div class="widget-entry">
<div class="widget-day__title">25 июня</div>
<div class="widget-entry clearfix">
<div class="widget-entry__item">
<div class="widget-entry__title">
<a href="#" class="h-link"> Висцеральная теория сна выглядит стр…</a>
</div>
<div class="widget-entry__info">2 ответа</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div></div>
<div class="col-sm-10 all-posts">
<div class="row b-post-filter">
<span class="pull-right">
записи по
<div class="btn-group">
<span type="button" class="pseudo-link" data-toggle="dropdown">месяцам</span>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a rel="nofollow" href="#" class="h-link">Нулябрь</a><li>
<li><a rel="nofollow" href="#" class="h-link">Первябрь</a><li>
</ul>
</div> ·
<div class="btn-group">
<span type="button" class="pseudo-link" data-toggle="dropdown">меткам</span>
<ul class="dropdown-menu dropdown-menu-right" role="menu"> <li> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/emacs.html" class="h-link">emacs</a> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/javascript.html" class="h-link">javascript</a> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/icfpc.html" class="h-link">icfpc</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/blender.html" class="h-link">blender</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/ia.html" class="h-link">Я</a> </li> <li> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/google.html" class="h-link">google</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/zhizn.html" class="h-link">жизнь</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/oshibka.html" class="h-link">ошибка</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/rabota.html" class="h-link">работа</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/python.html" class="h-link">python</a> </li> <li> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/java.html" class="h-link">java</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/bredni.html" class="h-link">бредни</a> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/racket.html" class="h-link">racket</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/programmirovanie.html" class="h-link">программирование</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/bge.html" class="h-link">bge</a> </li> <li> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/eda.html" class="h-link">еда</a> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/linux.html" class="h-link">linux</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/nabrosok.html" class="h-link">набросок</a> <a rel="nofollow" class="tag-1" href="http://imdagger.github.io/tag/radost.html" class="h-link">радость</a> <a rel="nofollow" class="tag-2" href="http://imdagger.github.io/tag/iandeks.html" class="h-link">Яндекс</a> </li> </ul>
</div> ·
<div class="btn-group">
<span type="button" class="pseudo-link" data-toggle="dropdown">типам</span>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a rel="nofollow" href="http://imdagger.github.io/category/description.html" class="h-link">обращение</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/friend.html" class="h-link">дружба</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/join.html" class="h-link">клубы</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/link.html" class="h-link">ссылки</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/mood.html" class="h-link">настроение</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/photo.html" class="h-link">фото</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/text.html" class="h-link">текст</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/video.html" class="h-link">видео</a><li>
<li><a rel="nofollow" href="http://imdagger.github.io/category/wishlist.html" class="h-link"></a><li>
</ul>
</div>
</span>
</div>
<div class="row b-post">
<div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/27/djkombu-i-mysql/" title="изменено 27 февраля 2013 года в 01:56">
27 февраля 2013 года, 01:53
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/celery.html">Celery</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/zadacha.html">задача</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/djkombu.html">djkombu</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/zavisaet.html">зависает</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/mysql.html">MySQL</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/ne-rabotaet.html">не работает</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/broker.html">брокер</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/27/djkombu-i-mysql/">djkombu и MySQL</a> </div>
<div class="row post-body">
<div class="b-text">
<p>Чтобы Celery нормально обрабатывал задачи из MySQL (да я знаю, что
лучше использовать другой брокер для этой задачи и держать, например, их
хотя бы в Redis) пришлось добавить пару строчек для инициализации MySQL:</p>
<div class="highlight"><pre><span class="pgcss-n">DATABASES</span> <span class="pgcss-o">=</span> <span class="pgcss-p">{</span>
<span class="pgcss-s">'default'</span><span class="pgcss-p">:</span> <span class="pgcss-p">{</span>
<span class="pgcss-err">…</span>
<span class="pgcss-s">'OPTIONS'</span><span class="pgcss-p">:</span> <span class="pgcss-p">{</span>
<span class="pgcss-s">'init_command'</span><span class="pgcss-p">:</span> <span class="pgcss-s">'SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;'</span><span class="pgcss-p">,</span> <span class="pgcss-c"># for the Celery</span>
<span class="pgcss-p">},</span>
<span class="pgcss-p">}</span>
<span class="pgcss-p">}</span>
</pre></div>
<p>После этого он стал получать задачи как положено, а не только после
каждого перезапуска worker’а.</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-link">
<div class="panel-heading b-post-type b-post-type-link">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
поделился ссылкой <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/27/pip-i-ustanovka-iz-git-repozitoriia/" >
27 февраля 2013 года, 01:48
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/pip.html">pip</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/reviziia.html">ревизия</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/ustanovka.html">установка</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/git.html">git</a></span></div>
</noindex>
<div class="post-title">
<a class="h-link" href="http://yuji.wordpress.com/2011/04/11/pip-install-specific-commit-from-git-repository/">
<img class="b-ico" src="http://favicon.yandex.ru/favicon/yuji.wordpress.com?default=yaru-external">Pip и установка из git-репозитория</a>
</div>
<div class="row post-body">
<div class="b-text">
<p>Утилита pip позволяет легко установить конкретную ревизию из
git-репозитория, достаточно добавить к ссылке @sha1-номер-коммита:</p>
<div class="highlight"><pre><span class="pgcss-go">pip install git+git:/jtauber/django-mailer.git@840d25bb9db9fbc80</span>
</pre></div>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-mood">
<div class="panel-heading b-post-type b-post-type-mood">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
поделился настроением <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/27/urn:ya.ru:post/22199227/1744/" >
27 февраля 2013 года, 01:45
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
</noindex>
<div class="post-title">
</div>
<div class="row post-body">
<div class="b-text">
<p>нездоровится что-то :/</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/22/razbienie-teksta-na-slova/" >
22 февраля 2013 года, 03:59
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/programmirovanie.html">программирование</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/tekst.html">текст</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/slovo.html">слово</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/razbienie.html">разбиение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/russkii.html">русский</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/unicode.html">unicode</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/regex.html">regex</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/shingly.html">шинглы</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/22/razbienie-teksta-na-slova/">Разбиение текста на слова</a> </div>
<div class="row post-body">
<div class="b-text">
<p>Сначала я реализовал черновой вариант с использованием стандартной
библиотеки unicodedata и прохода по символам текста:</p>
<div class="highlight"><pre><span class="pgcss-kn">import</span> <span class="pgcss-nn">unicodedata</span>
<span class="pgcss-o">...</span>
<span class="pgcss-k">def</span> <span class="pgcss-nf">clean_and_split</span><span class="pgcss-p">(</span><span class="pgcss-bp">self</span><span class="pgcss-p">,</span> <span class="pgcss-n">stop_words</span><span class="pgcss-p">):</span>
<span class="pgcss-n">words</span> <span class="pgcss-o">=</span> <span class="pgcss-p">[</span><span class="pgcss-s">u''</span><span class="pgcss-p">]</span>
<span class="pgcss-k">for</span> <span class="pgcss-n">letter</span> <span class="pgcss-ow">in</span> <span class="pgcss-bp">self</span><span class="pgcss-o">.</span><span class="pgcss-n">text</span><span class="pgcss-o">.</span><span class="pgcss-n">lower</span><span class="pgcss-p">():</span>
<span class="pgcss-n">cname</span> <span class="pgcss-o">=</span> <span class="pgcss-n">unicodedata</span><span class="pgcss-o">.</span><span class="pgcss-n">category</span><span class="pgcss-p">(</span><span class="pgcss-n">letter</span><span class="pgcss-p">)[</span><span class="pgcss-mi">0</span><span class="pgcss-p">]</span>
<span class="pgcss-k">if</span> <span class="pgcss-n">cname</span> <span class="pgcss-ow">in</span> <span class="pgcss-p">(</span><span class="pgcss-s">'Z'</span><span class="pgcss-p">,</span> <span class="pgcss-s">'C'</span><span class="pgcss-p">,</span> <span class="pgcss-s">'P'</span><span class="pgcss-p">)</span> <span class="pgcss-ow">and</span> <span class="pgcss-n">letter</span> <span class="pgcss-o">!=</span> <span class="pgcss-s">'-'</span><span class="pgcss-p">:</span>
<span class="pgcss-k">if</span> <span class="pgcss-nb">len</span><span class="pgcss-p">(</span><span class="pgcss-n">words</span><span class="pgcss-p">[</span><span class="pgcss-o">-</span><span class="pgcss-mi">1</span><span class="pgcss-p">])</span> <span class="pgcss-o">></span> <span class="pgcss-mi">0</span><span class="pgcss-p">:</span>
<span class="pgcss-n">words</span><span class="pgcss-o">.</span><span class="pgcss-n">append</span><span class="pgcss-p">(</span><span class="pgcss-s">u''</span><span class="pgcss-p">)</span>
<span class="pgcss-k">elif</span> <span class="pgcss-n">cname</span> <span class="pgcss-o">==</span> <span class="pgcss-s">'L'</span><span class="pgcss-p">:</span>
<span class="pgcss-c"># don't distinguish letter E and E-with-dots</span>
<span class="pgcss-k">if</span> <span class="pgcss-n">letter</span> <span class="pgcss-o">==</span> <span class="pgcss-s">u'ё'</span><span class="pgcss-p">:</span>
<span class="pgcss-n">letter</span> <span class="pgcss-o">=</span> <span class="pgcss-s">u'е'</span>
<span class="pgcss-n">words</span><span class="pgcss-p">[</span><span class="pgcss-o">-</span><span class="pgcss-mi">1</span><span class="pgcss-p">]</span> <span class="pgcss-o">+=</span> <span class="pgcss-n">letter</span>
</pre></div>
<p>Но профайлер показывал, что это вторая функция по ресурсам после
базы данных в коде. Поэтому пришлось подумать и переделать это всё в
более короткий алгоритм. Я чувствовал, что всё это стоит записать
каким-нибудь регулярным выражением, т.к. регулярные выражения
преобразуются в конечный автомат, который будет работать быстро.
Оказалось, что стандартная библиотека <strong>re</strong> дружит с Unicode, но
немного не тем боком, что мне нужно. Т.к. я хочу выделить в тексте
только слова из букв (с запасом того, что мне может потребоваться
расширить это условие), выбросив все знаки препинания, цифры и т.д.
Оказалось, что библиотека regex из PyPi как раз то, что нужно:</p>
<div class="highlight"><pre><span class="pgcss-kn">import</span> <span class="pgcss-nn">regex</span>
<span class="pgcss-o">...</span>
<span class="pgcss-c"># minimal word length is 3 (last letter of word can't be dash)</span>
<span class="pgcss-n">SPLITTER</span> <span class="pgcss-o">=</span> <span class="pgcss-n">regex</span><span class="pgcss-o">.</span><span class="pgcss-n">compile</span><span class="pgcss-p">(</span><span class="pgcss-s">ur'[\p{L}-]{2,}[\p{L}]'</span><span class="pgcss-p">)</span>
<span class="pgcss-o">...</span>
<span class="pgcss-k">def</span> <span class="pgcss-nf">clean_and_split</span><span class="pgcss-p">(</span><span class="pgcss-bp">self</span><span class="pgcss-p">,</span> <span class="pgcss-n">stop_words</span><span class="pgcss-p">):</span>
<span class="pgcss-c"># тут ещё не хватает проверки stop_words, но добавить её не сложно</span>
<span class="pgcss-k">return</span> <span class="pgcss-n">SPLITTER</span><span class="pgcss-o">.</span><span class="pgcss-n">findall</span><span class="pgcss-p">(</span><span class="pgcss-bp">self</span><span class="pgcss-o">.</span><span class="pgcss-n">text</span><span class="pgcss-o">.</span><span class="pgcss-n">lower</span><span class="pgcss-p">()</span><span class="pgcss-o">.</span><span class="pgcss-n">replace</span><span class="pgcss-p">(</span><span class="pgcss-s">u'ё'</span><span class="pgcss-p">,</span> <span class="pgcss-s">u'е'</span><span class="pgcss-p">))</span>
</pre></div>
<p>Главное не забыть указать префиксы строки <strong>ur</strong> для регулярного
выражения. Т.е. важно не забыть прописать перфикс юникода, иначе \p{…}
не будет работать как следует. В результате этот участок кода ускорился
от 8 до 10 раз.</p>
<p>Потом мне ещё потребовалось узнать в каких позициях стояли слова, но
это было уже без особых проблем, достаточно использовать finditer метод
объекта скомпилированного регулярного выражения:</p>
<div class="highlight"><pre><span class="pgcss-o">...</span>
<span class="pgcss-k">for</span> <span class="pgcss-n">match</span> <span class="pgcss-ow">in</span> <span class="pgcss-n">SPLITTER</span><span class="pgcss-o">.</span><span class="pgcss-n">finditer</span><span class="pgcss-p">(</span><span class="pgcss-n">some_text</span><span class="pgcss-p">):</span>
<span class="pgcss-k">print</span> <span class="pgcss-n">match</span><span class="pgcss-o">.</span><span class="pgcss-n">group</span><span class="pgcss-p">(),</span> <span class="pgcss-n">match</span><span class="pgcss-o">.</span><span class="pgcss-n">start</span><span class="pgcss-p">()</span>
</pre></div>
<p>Вообще это всё нужно, чтобы разделить текст, выбросить лишние слова
и затем можно уже строить шинглы по нему.</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/17/steam-i-linux/" >
17 февраля 2013 года, 03:13
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/primus.html">primus</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/steam.html">steam</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/linux.html">linux</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/optimus.html">optimus</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/radost.html">радость</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/igry.html">игры</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/17/steam-i-linux/">Steam и Linux</a> </div>
<div class="row post-body">
<div class="b-text">
<p> Пришлось для сабжа даже WebMoney завести, т.к. мой PayPal прописан
на другую страну, а Visa Virtuon почему-то отказывался Steam принимать.
Обзавёлся я World of Goo и Counter-Strike: Source, последний правда с
моим пингом немного подлагивал на том сервере куда я подключился и
настройки графики ещё пришлось чуть снизить, т.к. мой Ion всё же не
такой монстр (это же нетбук для работы, а не шпилить днями). Завелось
всё замечательно, спасибо Valve. Убрал Ironhide и поставил Bumblebee +
primus. Из-за Ironhide я думал, что Steam-у нужно положить симлинк на
32-битную графическую библиотеку GL, но оказалось, что он только мешал +
Steam думал, что у меня OpenGL только 1.4 и карточка Intel. А уже после
старта “primusrun steam” и обновления дравера NVidia до 304, у Steam
сомнения отпали и он признал мою вторую видеокарту.</p>
<p> Особо я не играю, но World of Goo игра клёвая и мне хотелось
поддержать их, а CS это всё же какая-никакая дань моим воспоминаниям из
прошлого. Заодно и самой Valve помог, тем что повёлся установить их
систему цифровой дистрибуции.</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/09/strannoe-povedenie-lxmlhtml/" title="изменено 9 февраля 2013 года в 01:58">
9 февраля 2013 года, 01:57
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/strannoe-povedenie.html">странное поведение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/html.html">HTML</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/povedenie.html">поведение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/otklonenie.html">отклонение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/lxml.html">lxml</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/09/strannoe-povedenie-lxmlhtml/">Странное поведение lxml.html</a> </div>
<div class="row post-body">
<div class="b-text">
<p>Столкнулся с тем, что не очень валидные с точки зрения стандарта и
логики кусочек HTML обрабатывается неоднозначно при помощи lxml.html.
Браузеры без проблем его переваривают, BeautifulSoup тоже, и некоторые
другие парсеры:</p>
<div class="highlight"><pre><span class="pgcss-gp">>>> </span><span class="pgcss-kn">import</span> <span class="pgcss-nn">lxml.html</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-kn">import</span> <span class="pgcss-nn">lxml.html.soupparser</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">tostring</span><span class="pgcss-p">(</span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">fromstring</span><span class="pgcss-p">(</span><span class="pgcss-s">'<html><head></head><body><a href="link">'</span> \
<span class="pgcss-go"> '<table><tr><td>Cell</td></tr></table></a></body></html>'))</span>
<span class="pgcss-go">'<html><head></head><body><a href="link"></a><table><tr><td>Cell</td></tr></table></body></html>'</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">tostring</span><span class="pgcss-p">(</span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">soupparser</span><span class="pgcss-o">.</span><span class="pgcss-n">fromstring</span><span class="pgcss-p">(</span><span class="pgcss-s">'<html><head></head><body>'</span> \
<span class="pgcss-go"> '<a href="link"><table><tr><td>Cell</td></tr></table></a></body></html>'))</span>
<span class="pgcss-go">'<html><head></head><body><a href="link"><table><tr><td>Cell</td></tr></table></a></body></html>'</span>
</pre></div>
<p>Сразу видно, что lxml.html отделил <table> от <a>, оно то конечно и
правильно, если бы я не столкнулся с такой разметкой на одном реальном
сайте + для других похожих ситуаций оно себя тоже ведёт немного странно.
Всё бы ничего, в DTD же прописано, что в <a> не стоит пихать <table>, но
туда и <div> пихать не стоит, но:</p>
<div class="highlight"><pre><span class="pgcss-gp">>>> </span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">tostring</span><span class="pgcss-p">(</span><span class="pgcss-n">lxml</span><span class="pgcss-o">.</span><span class="pgcss-n">html</span><span class="pgcss-o">.</span><span class="pgcss-n">fromstring</span><span class="pgcss-p">(</span><span class="pgcss-s">'<html><head></head><body>'</span> \
<span class="pgcss-go"> '<a href="link"><div>Text</div></a></body></html>'))</span>
<span class="pgcss-go">'<html><head></head><body><a href="link"><div>Text</div></a></body></html>'</span>
</pre></div>
<p>Всё же что-то не так, т.к. библиотеке нужно определиться: либо всё
выносить из тега ссылки, что не является разрешённым, либо обрабатывать
случай <code class="code">
<table></code>
. Но не вести себя по разному.</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/05/beskonechnaia-blokirovka/" title="изменено 5 февраля 2013 года в 23:43">
5 февраля 2013 года, 23:41
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/pul.html">пул</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/neiavnyi.html">неявный</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/pool.html">pool</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/blokirovka.html">блокировка</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/gevent.html">gevent</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/05/beskonechnaia-blokirovka/">Бесконечная блокировка</a> </div>
<div class="row post-body">
<div class="b-text">
<p>Как получить ситуацию, что gevent выдаст исключение о бесконечно
блокирующейся операции? Сделать бесконечный цикл? Нет. Достаточно, чтобы
операция сама себя ожидала, но как это сделать неявным образом, чтобы
пример не был высосан из пальца и был похож на настоящую ситуацию.
Достаточно просто.</p>
<p>Допустим есть потребность выполнять какую-то операцию (например
краулинг и парсинг страниц) в ограниченном количестве параллельных
потоком. Мы берём для этого пул с ограниченным размером. Затем для
каждой страницы мы хотим порождать отдельный поток (т.к. микропотоки
достаточно дешёвые), мы пишем что-то типа такого:</p>
<div class="highlight"><pre><span class="pgcss-gp">>>> </span><span class="pgcss-n">p</span> <span class="pgcss-o">=</span> <span class="pgcss-n">gevent</span><span class="pgcss-o">.</span><span class="pgcss-n">pool</span><span class="pgcss-o">.</span><span class="pgcss-n">Pool</span><span class="pgcss-p">(</span><span class="pgcss-mi">10</span><span class="pgcss-p">)</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-k">for</span> <span class="pgcss-n">_</span> <span class="pgcss-ow">in</span> <span class="pgcss-nb">xrange</span><span class="pgcss-p">(</span><span class="pgcss-mi">5</span><span class="pgcss-p">):</span>
<span class="pgcss-gp">... </span> <span class="pgcss-n">p</span><span class="pgcss-o">.</span><span class="pgcss-n">spawn</span><span class="pgcss-p">(</span><span class="pgcss-n">task</span><span class="pgcss-p">,</span> <span class="pgcss-o">...</span><span class="pgcss-p">)</span>
<span class="pgcss-gp">... </span><span class="pgcss-n">p</span><span class="pgcss-o">.</span><span class="pgcss-n">join</span><span class="pgcss-p">()</span>
</pre></div>
<p>Затем реализуем задачу task, в ней будут выполняться какие-то
операции над полученными данными, например, извлекаться новые ссылки, и
будет происходить порождение новых микропотоков. Но мы же хотим, чтобы
конкуренция не разрасталась, поэтому решаем складывать задачи единый
пул.</p>
<div class="highlight"><pre><span class="pgcss-gp">>>> </span><span class="pgcss-k">def</span> <span class="pgcss-nf">sub_task</span><span class="pgcss-p">(</span><span class="pgcss-n">i</span><span class="pgcss-p">,</span> <span class="pgcss-n">p</span><span class="pgcss-p">):</span>
<span class="pgcss-go"> p.spawn(lambda: i)</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-k">def</span> <span class="pgcss-nf">task</span><span class="pgcss-p">(</span><span class="pgcss-n">i</span><span class="pgcss-p">,</span> <span class="pgcss-n">p</span><span class="pgcss-p">):</span>
<span class="pgcss-gp">... </span> <span class="pgcss-k">for</span> <span class="pgcss-n">_</span> <span class="pgcss-ow">in</span> <span class="pgcss-nb">xrange</span><span class="pgcss-p">(</span><span class="pgcss-mi">4</span><span class="pgcss-p">):</span>
<span class="pgcss-gp">... </span> <span class="pgcss-n">p</span><span class="pgcss-o">.</span><span class="pgcss-n">spawn</span><span class="pgcss-p">(</span><span class="pgcss-n">sub_task</span><span class="pgcss-p">,</span> <span class="pgcss-n">i</span> <span class="pgcss-o">+</span> <span class="pgcss-mi">1</span><span class="pgcss-p">,</span> <span class="pgcss-n">p</span><span class="pgcss-p">)</span>
<span class="pgcss-gp">...</span>
</pre></div>
<p>Таким образом каждый task создаёт ещё по 4 sub_task. Когда
структура программы не такая простая и голая, а напичкана различной
дополнительной логикой, то кажется, что всё хорошо. Но увы программа
начинает себя странно вести от раза к разу. И поведение меняется от
количества операция и размера пула.</p>
<p>В версии gevent 0.13.8 всё просто замолкает, зависает и крутится в
цикле. Но благо 1.0dev умеет определять эту проблемную точку и выдавать
исключение:</p>
<div class="highlight"><pre><span class="pgcss-gt">Traceback (most recent call last):</span>
<span class="pgcss-gr"> File "test.py", line 14, in</span>
<span class="pgcss-gr"> p.join()</span>
<span class="pgcss-gr"> File "/home/imdagger/Projects/bj-project/virtualenv/pg/local/lib/python2.7/site-packages/gevent/pool.py", line 100, in join</span>
<span class="pgcss-gr"> self._empty_event.wait(timeout=timeout)</span>
<span class="pgcss-gr"> File "/home/imdagger/Projects/bj-project/virtualenv/pg/local/lib/python2.7/site-packages/gevent/event.py", line 77, in wait</span>
<span class="pgcss-gr"> result = self.hub.switch()</span>
<span class="pgcss-gr"> File "/home/imdagger/Projects/bj-project/virtualenv/pg/local/lib/python2.7/site-packages/gevent/hub.py", line 331, in switch</span>
<span class="pgcss-gr"> return greenlet.switch(self)</span>
<span class="pgcss-gr">gevent.hub.LoopExit</span>: <span class="pgcss-n">This operation would block forever</span>
</pre></div>
<p>А всё потому, что некоторая задача task нуждается в добавлении в пул
подзадачи sub_task, которая тоже нуждается в пуле, а сам пул нуждается
в завершении задачи task, т.к. он достиг размера 10 и переполнен. и с
другими задачами аналогично, т.е. пул переполнен и ждёт освобождения, а
задачи, чтобы завершится пытаются в него затолкнуть ещё больше подзадач.</p>
<p>Поэтому для выхода из такой ситуации лучше обойтись либо только task
без вызова ещё одной поздадачи со spawn, а лучше вообще закидывать
подзадачи в очередь, а другой поток (или несколько), будут забирать их,
обрабатывать данные и укладывать в пул.</p>
</div>
</div>
<div class="row comments-row">
<span><a class="pseudo-link b-candy b-comment-shortcut"><i class="b-ico"></i>ответить</a></span>
</div>
</div>
</div>
</div><div class="panel panel-text">
<div class="panel-heading b-post-type b-post-type-text">
<b class="b-user">
<a class="b-user__link" href="http://imdagger.github.io/author/imdagger.html"><b class="b-user__first-letter">I</b>MDagger</a>
</b>
написал <span class="pull-right b-date">
<a class="h-link" href="http://imdagger.github.io/posts/2013/02/01/strannosti-mongoengine/" title="изменено 1 февраля 2013 года в 00:27">
1 февраля 2013 года, 00:26
</a>
</span>
</div>
<div class="panel-body">
<div class="col-sm-1 b-post__layout-left">
<a href="http://imdagger.github.io/author/imdagger.html"><img src="http://upics.yandex.ru/22199227/middle"></a>
</div>
<div class="col-sm-11 b-right-col">
<noindex>
<div class="row tags-row">
<span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/oshibka.html">ошибка</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/uroven.html">уровень</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/slovar.html">словарь</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/strannoe-povedenie.html">странное поведение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/mongoengine.html">MongoEngine</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/dokument.html">документ</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/vlozhennyi.html">вложенный</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/povedenie.html">поведение</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/pole.html">поле</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/python.html">python</a></span>, <span class="tag"><a rel="nofollow" class="h-link" href="http://imdagger.github.io/tag/programmirovanie.html">программирование</a></span></div>
</noindex>
<div class="post-title">
<a class="no-link" href="http://imdagger.github.io/posts/2013/02/01/strannosti-mongoengine/">Странности MongoEngine</a> </div>
<div class="row post-body">
<div class="b-text">
<p>Странно, но в Mongoengine MapField внутри другого MapField ведёт
себя немного неожиданно. Не знаю, так задумано или это ошибка (спрошу у
них попозже), но если сделать вот так:</p>
<div class="highlight"><pre><span class="pgcss-k">class</span> <span class="pgcss-nc">SomeModel</span><span class="pgcss-p">(</span><span class="pgcss-n">EmbeddedDocument</span><span class="pgcss-p">):</span>
<span class="pgcss-n">num</span> <span class="pgcss-o">=</span> <span class="pgcss-n">IntField</span><span class="pgcss-p">()</span>
<span class="pgcss-k">class</span> <span class="pgcss-nc">SomeModel</span><span class="pgcss-p">(</span><span class="pgcss-n">Document</span><span class="pgcss-p">):</span>
<span class="pgcss-n">my_field</span> <span class="pgcss-o">=</span> <span class="pgcss-n">MapField</span><span class="pgcss-p">(</span><span class="pgcss-n">MapField</span><span class="pgcss-p">(</span><span class="pgcss-n">EmbeddedDocumentField</span><span class="pgcss-p">(</span><span class="pgcss-n">SomeSubModel</span><span class="pgcss-p">)))</span>
</pre></div>
<p>То всё будет работать, но как только мы захотим получить документ и
произвести правку в поле num начнётся самое интересное:</p>
<div class="highlight"><pre><span class="pgcss-gp">>>> </span><span class="pgcss-n">some_obj</span> <span class="pgcss-o">=</span> <span class="pgcss-n">SomeModel</span><span class="pgcss-o">.</span><span class="pgcss-n">object</span><span class="pgcss-p">[</span><span class="pgcss-mi">1</span><span class="pgcss-p">]</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-k">print</span> <span class="pgcss-n">some_obj</span><span class="pgcss-o">.</span><span class="pgcss-n">my_field</span><span class="pgcss-p">[</span><span class="pgcss-s">'key1'</span><span class="pgcss-p">][</span><span class="pgcss-s">'key2'</span><span class="pgcss-p">]</span><span class="pgcss-o">.</span><span class="pgcss-n">num</span>
<span class="pgcss-go">9</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-n">some_obj</span><span class="pgcss-o">.</span><span class="pgcss-n">my_field</span><span class="pgcss-p">[</span><span class="pgcss-s">'key1'</span><span class="pgcss-p">][</span><span class="pgcss-s">'key2'</span><span class="pgcss-p">]</span><span class="pgcss-o">.</span><span class="pgcss-n">num</span> <span class="pgcss-o">=</span> <span class="pgcss-mi">10</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-n">some_obj</span><span class="pgcss-o">.</span><span class="pgcss-n">save</span><span class="pgcss-p">()</span>
<span class="pgcss-go"># и снова</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-n">some_obj</span> <span class="pgcss-o">=</span> <span class="pgcss-n">SomeModel</span><span class="pgcss-o">.</span><span class="pgcss-n">object</span><span class="pgcss-p">[</span><span class="pgcss-mi">1</span><span class="pgcss-p">]</span>
<span class="pgcss-gp">>>> </span><span class="pgcss-k">print</span> <span class="pgcss-n">some_obj</span><span class="pgcss-o">.</span><span class="pgcss-n">my_field</span><span class="pgcss-p">[</span><span class="pgcss-s">'key1'</span><span class="pgcss-p">][</span><span class="pgcss-s">'key2'</span><span class="pgcss-p">]</span><span class="pgcss-o">.</span><span class="pgcss-n">num</span>
<span class="pgcss-go">9</span>
</pre></div>
<p>И он ни в какую не хочет сохранять. Хотя можно провернуть трюк с
update, но это только для такой простой модели, а если там ещё уровень
вложенности, то уже и update не помогает. А всё почему?</p>
<p>А потому, что это заложено в поведение <code class="code">