Repository navigation
Expand file tree
/
Copy pathatom.xml
More file actions
1164 lines (1122 loc) · 64.4 KB
/
Copy pathatom.xml
File metadata and controls
1164 lines (1122 loc) · 64.4 KB
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
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<id>https://harveywxia.github.io</id>
<title>harvey的网络日志</title>
<updated>2021-09-30T09:40:09.330Z</updated>
<generator>https://github.com/jpmonette/feed</generator>
<link rel="alternate" href="https://harveywxia.github.io"/>
<link rel="self" href="https://harveywxia.github.io/atom.xml"/>
<subtitle>温故而知新</subtitle>
<logo>https://harveywxia.github.io/images/avatar.png</logo>
<icon>https://harveywxia.github.io/favicon.ico</icon>
<rights>All rights reserved 2021, harvey的网络日志</rights>
<entry>
<title type="html"><![CDATA[SpaCy基于规则的匹配--TokenMatcher]]></title>
<id>https://harveywxia.github.io/post/spacy-ji-yu-gui-ze-de-pi-pei-tokenmatcher/</id>
<link href="https://harveywxia.github.io/post/spacy-ji-yu-gui-ze-de-pi-pei-tokenmatcher/">
</link>
<updated>2021-09-26T02:53:02.000Z</updated>
<content type="html"><![CDATA[<h4 id="基于规则的匹配">基于规则的匹配</h4>
<p>查找短语和单词,并匹配实体<br>
在原始文本上使用正则表达式匹配,spaCy的基于规则的匹配器引擎和组件不仅可以找到所需的单词和短语,还可以让您访问文档中的词及其相互关系。这意味着您可以轻松访问和分析周围的词,将跨度合并为单个词或加入到<code>doc.ents</code>中的命名实体中。</p>
<blockquote>
<p><strong>我应该使用规则还是训练一模型模型?</strong><br>
对于复杂的任务,通常最好训练一个基于统计的命名实体识别模型。但是,统计模型需要训练数据,因此在许多情况下,基于规则的方法更实用。在项目初始阶段尤其如此:你可以使用基于规则的方法作为数据收集过程的一部分,以帮助您“引导”统计模型。</p>
</blockquote>
<blockquote>
<p>如果您有一些示例并且希望您的系统能够基于这些示例进行泛化(generalize),那么就应该训练模型。如果在当前上下文有线索,它会更加有效。例如,如果您尝试检测人名或公司名称,您的应用程序可能会受益于统计命名实体识别模型。</p>
</blockquote>
<blockquote>
<p>如果你想在数据中查找有限数量的示例,那么基于规则的系统就是一个很好的选择,或者你可以找到一个词规则或者正则表达式来准确的表达一个模式<br>
。例如,你可以通过基于规则的方法很好地处理国家名称、<code>IP</code>地址或<code>URL</code>等。</p>
</blockquote>
<blockquote>
<p>您还可以将这两种方法结合使用,可以使用规则改进统计模型,以处理非常具体的情况并提高准确性。有关详细信息,请参阅<a href="https://spacy.io/usage/rule-based-matching#entityruler">基于规则的实体识别部分</a>。</p>
</blockquote>
<blockquote>
<p><strong>什么时候应该使用词匹配器(Matcher)和短语匹配器?</strong><br>
如果你已经拥有一个大型术语列表或一个由单个或多个token语组成的地名录,此时你想找到一个确切的实例,那么<code>PhraseMacher</code>就非常有用。<br>
从<code>spaCy v2.1.0</code>开始,您还可以通过<code>LOWER</code>属性进行快速且不区分大小写的匹配。</p>
</blockquote>
<blockquote>
<p>Matcher没有<code>PhraseMatcher</code>那么快,因为他会比较所有token的属性。但是,它允许你使用模型预测的词汇属性和语言特征为正在寻找的tokens编写一个非常抽象的表示。例如,你可以查找一个跟在“love”或“like”动词后,或可选限定符或者一个不少于10个字符的token后的名词,</p>
</blockquote>
<h5 id="token-based匹配"><code>Token-based</code>匹配</h5>
<p>spaCy自带规则匹配引擎<code>Matcher</code>, 对tokens的操作类似于正则表达式。规则可以引用token注释(例如标记text或tag_,或者如IS_PUNCT的标志)。规则匹配器还允许您传入自定义回调以处理匹配项 - 例如,可以合并实体和应用自定义标签。您还可以将模式与实体<code>ID</code>相关联,以允许进行一些基本的实体链接或消歧。要匹配大型术语列表,您可以使用 <code>PhraseMatcher</code>,它接受<code>Doc</code>对象作为匹配模式。</p>
<h6 id="添加模式">添加模式</h6>
<p>假设我们想让 spaCy 找到三个token的组合:</p>
<ol>
<li>小写形式与“hello”匹配的token,例如“Hello”或“HELLO”。</li>
<li><code>is_punct</code>标记设置为True的标记,即任何标点符号。</li>
<li>小写形式与“world”匹配的标记,例如“World”或“WORLD”。</li>
</ol>
<pre><code>[{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
</code></pre>
<blockquote>
<p><strong>!!!重要的提示</strong><br>
在编写模式时,记住每个字典代表一个token。如果 spaCy 的分词处理与模式中定义的token不匹配,则该模式不会产生任何结果。在开发复杂模式时,请确保根据 spaCy 的标记化检查示例:</p>
<pre><code>doc = nlp("A complex-example,!")
print([token.text for token in doc])
</code></pre>
</blockquote>
<p>首先,我们用一个词汇来初始化Matcher。匹配器必须始终与其操作的文档共享相同的词汇。我们现在可以调用<code>matcher.add()</code>并传入一个<code>ID</code>和一个模式列表作为参数。<br>
<code>spaCy v 3.0 · Python 3 基于 Binder</code></p>
<pre><code class="language-python">import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
# Add match ID "HelloWorld" with no callback and one pattern
pattern = [{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}]
# 将会匹配到“hello”+“标点”+“world”
matcher.add("HelloWorld", [pattern])
doc = nlp("Hello, world! Hello world!")
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id] # Get string representation
span = doc[start:end] # The matched span
print(match_id, string_id, start, end, span.text)
</code></pre>
<p>结果:<br>
<code>15578876784678163569 HelloWorld 0 3 Hello, world</code></p>
<p>匹配器返回一个(match_id, start, end)元组的列表——在本例中就是[('15578876784678163569', 0, 3)],它映射到我们原始文档的<code>doc[0:3]</code>。该<code>match_id</code>是字符串ID的“HelloWorld”的散列值的。要获取字符串值,你可以在StringStore中查询。</p>
<pre><code class="language-python">for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id] # 'HelloWorld'
span = doc[start:end] # The matched span
</code></pre>
<p>或者,我们还可以选择添加多个模式,例如,还可以匹配“hello”和“world”之间没有标点符号的序列:</p>
<pre><code class="language-python">patterns = [
[{"LOWER": "hello"}, {"IS_PUNCT": True}, {"LOWER": "world"}],
[{"LOWER": "hello"}, {"LOWER": "world"}]
]
matcher.add("HelloWorld", patterns)
</code></pre>
<p>默认情况下,匹配器将只返回匹配项而不执行任何其他操作,例如合并实体或分配标签。这完全取决于您,你可以通过向add()函数传入不同的回调函数作为on_match参数来单独定义每个模式。这很有用,因为它允许您编写完全自定义和模式特定的逻辑。例如,您可能希望将一些模式合并为一个token,同时为其他模式类型添加实体标签。这个时候你不必为每个进程创建不同的匹配器。</p>
<h6 id="可用的token属性">可用的token属性</h6>
<p>可用的Token模式键对应于许多 Token 属性. 基于规则的匹配支持的属性有:</p>
<table>
<thead>
<tr>
<th>ATTRIBUTE</th>
<th>DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr>
<td>ORTH</td>
<td>准确的Token逐字文本. <strong>TYPE</strong>:str</td>
</tr>
<tr>
<td>TEXT</td>
<td>准确的Token逐字文本. <strong>TYPE</strong>:str</td>
</tr>
<tr>
<td>LOWER</td>
<td>Token文本的小写形式.<strong>TYPE</strong>:str</td>
</tr>
<tr>
<td>LENGTH</td>
<td>Token文本的长度.<strong>TYPE</strong>:int</td>
</tr>
<tr>
<td>IS_ALPHA, IS_ASCII, IS_DIGIT</td>
<td>Token文本由字母字符、ASCII 字符、数字组成.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>IS_LOWER, IS_UPPER, IS_TITLE</td>
<td>Token文本是小写、大写、标题.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>IS_PUNCT, IS_SPACE, IS_STOP</td>
<td>Token文本是标点符号、空格、停止词.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>IS_SENT_START</td>
<td>Token是句子的开始.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>LIKE_NUM, LIKE_URL, LIKE_EMAIL</td>
<td>Token文本类似于数字、URL、电子邮件.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>SPACY</td>
<td>Token有一个结尾空格.<strong>TYPE</strong>:bool</td>
</tr>
<tr>
<td>POS, TAG, MORPH, DEP, LEMMA, SHAPE</td>
<td>令牌的简单和扩展词性标签、形态分析、依赖标签、词根、形状(shape)。请注意,这些属性的值区分大小写。有关可用词性标签和依赖项标签的列表,请参阅<a href="https://spacy.io/api/annotation">注释规范</a>。 <strong>TYPE</strong>:str</td>
</tr>
<tr>
<td>ENT_TYPE</td>
<td>Token的实体标签。 <strong>TYPE</strong>:str</td>
</tr>
<tr>
<td>_</td>
<td><a href="https://spacy.io/usage/processing-pipelines#custom-components-attributes">自定义扩展属性</a>的属性. <strong>TYPE</strong>:Dict[str, Any]</td>
</tr>
<tr>
<td>OP</td>
<td>运算符和量词,限定Token模式的匹配次数。<strong>TYPE</strong>:str</td>
</tr>
</tbody>
</table>
<blockquote>
<p><strong>属性名称区分大小写吗?</strong><br>
不区分。spaCy会进行名称规范化处理,<code>{"LOWER": "text"}</code>和<code>{"lower": "text"}</code>会得到相同的结果。使用大写版本主要是一种约定,以明确这些属性是“特殊的”并且不完全映射到像Token.lower和Token.lower_这样的标记属性 。</p>
</blockquote>
<blockquote>
<p><strong>为什么不支持所有Token属性?</strong><br>
<code>spaCy</code>无法提供对所有属性的访问,因为Matcher循环遍历<code>Cython</code>数据,而不是<code>Python</code>对象。在匹配器内部,我们正在处理一个<code>TokenC struct</code> – 我们没有<code>Token</code>实例. 这意味着所有引用计算属性的属性都无法访问。</p>
</blockquote>
<p>大写的属性名称类似于<code>LOWER</code>或<code>IS_PUNCT</code>引用自<code>spacy.attrs</code>枚举表。它们被传递到一个本质上是一个大<code>case/switch</code>语句的函数中,以确定要返回的结构字段。相同的属性标识符用于<code>Doc.to_array</code>,以及代码中需要描述此类字段的其他一些地方。</p>
<blockquote>
<p>提示:试用交互式匹配器<br>
<a href="https://explosion.ai/demos/matcher">匹配器演示</a><br>
该交互式匹配器通过创建基于规则的匹配起并在你的文本上运行他们来测试你的的Matcher。每个Token可以设置多个属性,如文本值、词性标记或布尔标志。基于token的视图可以让你看到spaCy是如何处理您的文本的,以及为什么可以成功匹配,或者为什么无法匹配。</p>
</blockquote>
<h6 id="扩展模式语法和属性">扩展模式语法和属性</h6>
<p>Token模式也可以映射到属性字典,而不仅仅是映射到单个值。例如,指定词根的值应该是值列表的一部分,或设置最小字符长度。可用的属性如下表:</p>
<pre><code class="language-python">例子
# Matches "love cats" or "likes flowers"
pattern1 = [{"LEMMA": {"IN": ["like", "love"]}},
{"POS": "NOUN"}]
# Matches tokens of length >= 10
pattern2 = [{"LENGTH": {">=": 10}}]
# Match based on morph attributes
pattern3 = [{"MORPH": {"IS_SUBSET": ["Number=Sing", "Gender=Neut"]}}]
# "", "Number=Sing" and "Number=Sing|Gender=Neut" will match as subsets
# "Number=Plur|Gender=Neut" will not match
# "Number=Sing|Gender=Neut|Polite=Infm" will not match because it's a superset
</code></pre>
<table>
<thead>
<tr>
<th>属性</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>IN</td>
<td>属性值是列表的成员。<strong>TYPE</strong>:Any</td>
</tr>
<tr>
<td>NOT_IN</td>
<td>属性值不是列表的成员。<strong>TYPE</strong>:Any</td>
</tr>
<tr>
<td>IS_SUBSET</td>
<td>属性值(用于<code>MORPH</code>或自定义列表属性)是列表的子集。<strong>TYPE</strong>:Any</td>
</tr>
<tr>
<td>IS_SUPERSET</td>
<td>属性值(用于<code>MORPH</code>或自定义列表属性)是列表的超集。<strong>TYPE</strong>:Any</td>
</tr>
<tr>
<td>INTERSECTS</td>
<td>属性值(用于<code>MORPH</code>或自定义列表属性)与列表具有非空交集。</td>
</tr>
</tbody>
</table>
<p>Any<br>
==, >=, <=, >, <| 属性值等于、大于或等于、小于或等于、大于或小于。<strong>TYPE</strong>:Union[int, float]</p>
<h6 id="常用表达式">常用表达式</h6>
<p>在某些情况下,仅匹配token和token属性是不够的——例如,你可能希望匹配一个单词的不同拼写,而想为每个拼写添加新模式。</p>
<pre><code>pattern = [{"TEXT": {"REGEX": "^[Uu](\.?|nited)$"}},
{"TEXT": {"REGEX": "^[Ss](\.?|tates)$"}},
{"LOWER": "president"}]
</code></pre>
<p>该<code>REGEX</code>操作允许你为任何属性定义规则,包括自定义属性。它始终需要应用于像TEXT,LOWER或TAG 之类的属性:</p>
<pre><code class="language-python"># Match different spellings of token texts
pattern = [{"TEXT": {"REGEX": "deff?in[ia]tely"}}]
# Match tokens with fine-grained POS tags starting with 'V'
pattern = [{"TAG": {"REGEX": "^V"}}]
# Match custom attribute values with regular expressions
pattern = [{"_": {"country": {"REGEX": "^[Uu](nited|\.?) ?[Ss](tates|\.?)$"}}}]
</code></pre>
<blockquote>
<p><strong>!!!重要的提示</strong><br>
使用<code>REGEX</code>运算符时,请记住它对单个标记token而不是整个文本进行操作。每个表达式都将匹配一个token。如果您需要对整个文本进行匹配,请参阅有关对<a href="https://spacy.io/usage/rule-based-matching#regex-text">整个文本进行正则表达式匹配的详细信息</a> 。</p>
</blockquote>
<h6 id="全文匹配正则表达式">全文匹配正则表达式</h6>
<p>如果您的表达式适用于多个标记,一个简单的解决方案是匹配doc.textwithre.finditer并使用 Doc.char_spanSpan从匹配的字符索引创建 a 的方法。如果匹配的字符没有映射到一个或多个有效Token,则<code>Doc.char_span</code>返回<code>None</code>。</p>
<blockquote>
<p><strong>什么是有效的令牌序列?</strong><br>
在该示例中,表达式也将匹配"US"在"USA"。但是, "USA"是单个标记,而<code>Span</code>对象是Token序列。所以 "US"不能是它自己的span,因为它没有在token边界上结束。</p>
</blockquote>
<pre><code class="language-python">import spacy
import re
nlp = spacy.load("en_core_web_sm")
doc = nlp("The United States of America (USA) are commonly known as the United States (U.S. or US) or America.")
expression = r"[Uu](nited|\.?) ?[Ss](tates|\.?)"
for match in re.finditer(expression, doc.text):
start, end = match.span()
span = doc.char_span(start, end)
# This is a Span object or None if match doesn't map to valid token sequence
if span is not None:
print("Found match:", span.text)
</code></pre>
<p>结果</p>
<pre><code>Found match: United States
Found match: United States
Found match: U.S.
Found match: US
</code></pre>
<p><strong>如何将match扩展为有效的令牌序列?</strong><br>
在某些情况下,您可能希望将匹配扩展到最近的token边界,你就需要为 "USA"创建一个span,即使只子串"US"会被匹配。您可以使用文档中tokens的字符偏移量(Token.idx](https://spacy.io/api/token#attributes))来计算它,可作为 .。这样你就可以个创建一个列表包含有效token的开始和结束边界,并给你留下一个基础的算法问题:给定一个数字,找到下一个最小数(token开始)或下一个最大数(token结束)。这将是最接近有效token的边界。</p>
<p>有很多实现方法,最直接的方法是在Doc中创建一个基于字符的字典表,索引到所在的token中。它易于编写且不易出错,并为您提供恒定的查找时间:您只需为每个Doc创建一次词典。</p>
<pre><code>chars_to_tokens = {}
for token in doc:
for i in range(token.idx, token.idx + len(token.text)):
chars_to_tokens[i] = token.i
</code></pre>
<p>然后,您可以在给定位置查找字符,并获取该字符所属的相应token的索引。你的span就是doc[token_start:token_end]。 如果字符不在<code>dict</code>中,则意味着它是(white)空格token被拆分的。不过,这希望不应该发生,因为这意味着您的正则表达式正在生成包含前导或后续空格的匹配项。</p>
<pre><code class="language-python">span = doc.char_span(start, end)
if span is not None:
print("Found match:", span.text)
else:
start_token = chars_to_tokens.get(start)
end_token = chars_to_tokens.get(end)
if start_token is not None and end_token is not None:
span = doc[start_token:end_token + 1]
print("Found closest match:", span.text)
</code></pre>
<h6 id="运算符和量词">运算符和量词</h6>
<p>匹配器还允许您使用指定为'OP'键的量词。量词让您定义要匹配的token序列,例如一个或多个标点符号,或指定可选token。请注意,不能使用嵌套或作用域量词——你可以使用<code>on_match</code>回调来实现。</p>
<table>
<thead>
<tr>
<th>OP运算符</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>!</td>
<td>否定模式,要求它精确匹配 0 次。</td>
</tr>
<tr>
<td>?</td>
<td>使模式可选,允许它匹配 0 次或 1 次</td>
</tr>
</tbody>
</table>
<p>+|要求模式匹配 1 次或多次。<br>
*| 允许模式匹配零次或多次。</p>
<pre><code class="language-python">pattern = [{"LOWER": "hello"},
{"IS_PUNCT": True, "OP": "?"}]
</code></pre>
]]></content>
</entry>
<entry>
<title type="html"><![CDATA[Github搭建个人主页]]></title>
<id>https://harveywxia.github.io/post/github-da-jian-ge-ren-zhu-ye/</id>
<link href="https://harveywxia.github.io/post/github-da-jian-ge-ren-zhu-ye/">
</link>
<updated>2021-08-27T06:27:39.000Z</updated>
<content type="html"><![CDATA[<h2 id="概述">概述</h2>
<p>GitHub Pages可以用来托管个人静态网站,便于用来实现博客。</p>
<h2 id="准备工作">准备工作</h2>
<ul>
<li>Gthub账号</li>
<li>域名(可选)</li>
</ul>
<h2 id="github-pages">Github Pages</h2>
<p>新建一个仓库,命名格式如下:</p>
<pre><code>{用户明}.github.io
</code></pre>
<p>需要选择public(公开)<br>
进入到该仓库的setting菜单(在star下面)中。可以选择并开启。<br>
此时在浏览器中即可访问页面,但是如果想更好的管理,可以使用Gridea。</p>
<h2 id="gridea">Gridea</h2>
<p>Gridea是一个静态博客写作客户端,所有文件都在本地,没有数据库,实现简单,支持Markdown。<br>
官网下载Gridea,安装并进入设置页面<br>
<img src="https://harveywxia.github.io/post-images/1630046301998.png" alt="" loading="lazy"></p>
<p>域名与仓库名一样,分支填master,email自己填,这里说一下Token.打开设置中的开发者设置:<br>
右上角头像-->Settings -->Developer settings -->Personal access tokens-->Generate token 勾选repo然后复制token即可。</p>
<h2 id="参考资料">参考资料</h2>
<ol>
<li><a href="https://www.cnblogs.com/6b7b5fc3/p/12716218.html">Github Pages+Gridea搭建个人博客</a></li>
<li><a href="https://www.jianshu.com/p/1520e4872a2c">「Gridea」给初接触者的一些使用技巧</a></li>
</ol>
]]></content>
</entry>
<entry>
<title type="html"><![CDATA[Redmine配置]]></title>
<id>https://harveywxia.github.io/post/redmine-pei-zhi/</id>
<link href="https://harveywxia.github.io/post/redmine-pei-zhi/">
</link>
<updated>2020-05-23T13:13:39.000Z</updated>
<content type="html"><![CDATA[<h3 id="问题状态">问题状态</h3>
<p>问题状态标签:新建问题、新建、进行中、已解决、反馈、已关闭、已拒绝、挂起。</p>
<ul>
<li><a href="https://www.cnblogs.com/biaopei/p/8891004.html">redmine添加自定义问题状态</a></li>
</ul>
<h3 id="跟踪标签">跟踪标签</h3>
<p>跟踪标签:里程碑、任务、需求用例、功能、缺陷<br>
项目中各跟踪标签的结构关系<br>
<img src="https://harveywxia.github.io/post-images/1590239926975.jpg" alt="" loading="lazy"><br>
说明:<br>
1. 5个里程碑:需求分析、概要设计、功能开发、系统测试、系统部署<br>
2. 在“需求分析”、“概要设计”、“系统测试”、“部署上线” 这几个里程碑中主要是以“任务”的形式指派给项目成员<br>
3. “功能开发”这个里程碑中有涉及到“需求用例”“功能”“任务”“缺陷”<br>
4. 若功能划分的不够细,则可将其以任务的形式再次划分。</p>
]]></content>
</entry>
<entry>
<title type="html"><![CDATA[CentOS7安装redmine]]></title>
<id>https://harveywxia.github.io/post/centos7-an-zhuang-redmine/</id>
<link href="https://harveywxia.github.io/post/centos7-an-zhuang-redmine/">
</link>
<updated>2020-05-23T11:55:35.000Z</updated>
<content type="html"><![CDATA[<h2 id="简介">简介</h2>
<p>Redmine是用Ruby开发的基于web的项目管理软件,是用ROR框架开发的一套跨平台项目管理系统,通过“项目(Project)”的形式把成员、任务(问题)、文档、讨论以及各种形式的资源组织在一起,大家参与更新任务、文档等内容来推动项目的进度,同时系统利用时间线索和各种动态的报表形式来自动给成员汇报项目进度。</p>
<h2 id="安装流程">安装流程</h2>
<h3 id="docker环境安装">docker环境安装</h3>
<h4 id="卸载旧版本">卸载旧版本</h4>
<p>较旧的 Docker 版本称为 docker 或 docker-engine 。如果已安装这些程序,请卸载它们以及相关的依赖项。</p>
<pre><code class="language-sh">$ sudo yum remove docker \
docker-client \
docker-client-latest \
docker-common \
docker-latest \
docker-latest-logrotate \
docker-logrotate \
docker-engine
</code></pre>
<h4 id="安装docker">安装docker</h4>
<p><strong>依赖环境</strong><br>
yum-utils 提供了 yum-config-manager ,并且 device mapper 存储驱动程序需要 device-mapper-persistent-data 和 lvm2。</p>
<pre><code class="language-sh">$ sudo yum install -y yum-utils \
device-mapper-persistent-data \
lvm2
</code></pre>
<p><strong>安装 Docker Engine-Community</strong><br>
安装最新版本的 Docker Engine-Community 和 containerd.</p>
<pre><code class="language-sh">$ sudo yum install docker-ce docker-ce-cli containerd.io
</code></pre>
<p><strong>启动 Docker</strong></p>
<pre><code class="language-sh">$ sudo systemctl start docker
</code></pre>
<p><strong>测试</strong><br>
通过运行 hello-world 映像来验证是否正确安装了 Docker Engine-Community 。</p>
<pre><code class="language-sh">$ sudo docker run hello-world
</code></pre>
<p>运行以上命令会打印出hello-world。</p>
<h4 id="安装docker-compose">安装docker-compose</h4>
<p>这里选择使用pip安装,pip的安装过程这里不展开。<br>
使用pip安装时建议使用<code>virtulenv</code>,运行以下命令安装:</p>
<pre><code class="language-sh">pip install docker-compose
</code></pre>
<p>如果你不使用virtulenv,则需要运行以下命令,完成安装。</p>
<pre><code class="language-sh">sudo pip install docker-compose
</code></pre>
<p><strong>测试</strong></p>
<pre><code class="language-sh">docker-compose -version
</code></pre>
<p>会打印出相关版本信息。<br>
<strong>参考</strong></p>
<ul>
<li><a href="https://docs.docker.com/compose/install/">Install Docker Compose</a></li>
</ul>
<h3 id="安装redmine">安装redmine</h3>
<pre><code class="language-yaml">version: '3'
services:
redmine:
image: redmine:4.1.1-alpine
restart: always
ports:
- '8080:3000'
environment:
REDMINE_DB_MYSQL: mysql
REDMINE_DB_PASSWORD: redminemysql
REDMINE_SECRET_KEY_BASE: supersecretkey
volumes:
- '/usr/harvey/docker/redmine/redmine_dir:/usr/src/redmine/files'
mysql:
image: mysql:8.0.20
restart: always
environment:
MYSQL_ROOT_PASSWORD: redminemysql
MYSQL_DATABASE: redmine
volumes:
- '/usr/harvey/docker/redmine/mysql__dir:/var/lib/mysql'
</code></pre>
<p><strong>参考</strong></p>
<ul>
<li><a href="https://hub.docker.com/_/redmine">dockerhub-redmine</a></li>
</ul>
<h2 id="测试">测试</h2>
<p>浏览器中输入以下网址,<br>
http://localhost:8080/login<br>
进入登录界面,默认用户名/密码:admin/admin</p>
<p>开始你的redmine之旅吧。</p>
]]></content>
</entry>
<entry>
<title type="html"><![CDATA[Django rest framework 使用笔记 ]]></title>
<id>https://harveywxia.github.io/post/django-rest-framework-shi-yong-bi-ji/</id>
<link href="https://harveywxia.github.io/post/django-rest-framework-shi-yong-bi-ji/">
</link>
<updated>2020-04-25T09:55:35.000Z</updated>
<content type="html"><![CDATA[<h2 id="models层">models层</h2>
<h3 id="models-field">models field</h3>
<p>在model中添加字段的格式一般为: field_name = field_type(**field_options)</p>
<h4 id="field-options所有字段共用">field options(所有字段共用)</h4>
<ol>
<li>null 默认为False,True则表示可以为null。(空字符串在数据库中可能被存储为'')。</li>
<li>blank 默认为False,True表示可以为空。</li>
<li>choice 可选的,限制了该选项的字段值必须是所指定的choice中的一个。</li>
</ol>
<pre><code class="language-python">from django.db import models
class Student(models.Model):
FRESHMAN = 'FR'
SOPHOMORE = 'SO'
JUNIOR = 'JR'
SENIOR = 'SR'
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, 'Freshman'), #第一个参数是真正的model参数,#第二个参数则是方便人们理解阅读
(SOPHOMORE, 'Sophomore'),
(JUNIOR, 'Junior'),
(SENIOR, 'Senior'),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR)
</code></pre>
<ol start="4">
<li><code>db_column</code>: 数据库<code>column</code>名称。默认为本字段的名称;</li>
<li><code>db_index</code>: 如果为<code>True</code>的话,该字段的数据库索引将会被创建;</li>
<li><code>default</code>: 设置该字段的默认值,可以是值也可以是对象;</li>
<li><code>editable</code>: 默认为<code>True</code>,若为<code>False</code>,则不会在<code>admin</code>界面显示;</li>
<li><code>primary_key</code>: 若设置为<code>True</code>,则表示将该字段设置为主键。一般情况下<code>django</code>默认会设置一个自增长的id主键;</li>
<li><code>unique</code>: 若设置为<code>True</code>,该字段值不可重复.</li>
</ol>
<p><strong><code>field type</code>(字段类型)</strong></p>
<h4 id="models基础字段">models基础字段</h4>
<p><code>AutoField()</code><br>
根据已有<code>id</code>自增长的整形唯一字段,一般每个<code>model</code>类不需设置该字段,因为<code>django</code>会为每个<code>model</code>自动设置。<br>
<code>django</code>默认会为每个<code>model</code>类添加如下语句:</p>
<pre><code>id = models.AutoField(primary_key=True)
</code></pre>
<p>当其他字段添加了<code>primary_key</code>属性,则不会创建<code>id</code>字段了,每个<code>model</code>类仅能有一个主键.</p>
<p><code>BooleanField()</code><br>
布尔型字段,默认的表单窗口部件是<code>CheckBoxInput</code></p>
<p><code>CharField()</code><br>
字符型字段,默认的表单窗口部件是<code>TextInput</code>。该字段类型有一个必需参数:<br>
<code>max_length</code> 在数据库水平限定了字符串最大长度</p>
<p><code>DateField()</code><br>
日期字段,字段的值是<code>python</code>中<code>datetime.date</code>的实例,默认的表单窗口是<code>TextInput</code>有几个可选的参数:</p>
<p><code>auto_now=True/False</code>: 当设置为True时,每当该对象使用save()时,该字段的值就会被更新。<br>
<code>auto_now_add=True/False</code>: 当设置为True时,该字段的值为该对象被创建时的日期</p>
<p><code>DateTimeField()</code><br>
日期和时间字段,值为<code>datetime.datetime</code>实例。默认的表单窗口以及可选参数同上。</p>
<p><code>DecimalField()</code><br>
混合精度的小数型数字字段。有两个必需的参数:<br>
<code>max_digits=ingt_number</code>:限定数字的最大位数(包含小数位)<br>
<code>decimal_places=int_number</code>:存储数字的小数位</p>
<pre><code>#to store numbers up to 999 with a resolution of 2 decimal places, you’d use
models.DecimalField(..., max_digits=5, decimal_places=2)
</code></pre>
<p><code>EmailField(max_length=254, **options)</code><br>
邮件字段,使用<code>EmailValidator</code>进行验证</p>
<p><code>FileField(upload_to=None, max_length=100, **options)</code><br>
文件上传字段。这个字段不能设置<code>primary_key</code>和<code>unique</code>选项.在数据库中存储类型是<code>varchar</code>,默认最大长度为100.<br>
有两个可选参数:<br>
<code>upload_to</code>: 如果使用默认的FileSystomStorage,文件将会存储到settings文件中配置的MEDIA_ROOT路径中。upload_to的值也可以为可调用对象,通过调用这个对象可以获得上传路径。<br>
instance=: 定义了FileField的模型实例<br>
filename='': 文件名称。</p>
<pre><code class="language-python">class MyModel01(models.Model):
# file will be uploaded to MEDIA_ROOT/uploads
upload = models.FileField(upload_to='uploads/')
# or...
# file will be saved to MEDIA_ROOT/uploads/2015/01/30
upload = models.FileField(upload_to='uploads/%Y/%m/%d/')
#upload_to=可调用对象
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return 'user_{0}/{1}'.format(instance.user.id, filename)
class MyModel02(models.Model):
upload = models.FileField(upload_to=user_directory_path)
</code></pre>
<p>storage 用来设定文件存储仓库</p>
<p><code>FilePathField(path=None, match=None, recursive=False, max_length=100, **options)</code><br>
这个字段的值被限制在系统上某个目录中的所有文件名集合中。有三个参数:</p>
<p>path='': 该参数必需。上行所说的'某个目录’的绝对路径。Example: "/home/images".<br>
match='pattern': 可选参数。格式是正则表达式。用来拣选符合匹配正则表达式的文件<br>
recursive=True/False: 可选参数,默认为False。设定是否递归该目录下所有子目录的所有文件。</p>
<pre><code class="language-python">FilePathField(path="/home/images", match="foo.*", recursive=True)
</code></pre>
<p><code>FloatField()</code><br>
浮点字段,默认的表单窗口部件是<code>NumberInput</code>。和<code>DecimalField</code>经常混淆不清,<code>FloatField</code>在内部使用<code>Python</code>中的<code>float</code>对象,而<code>DecimalField</code>在内部使用<code>Python</code>中的<code>decimal</code>对象。</p>
<p><code>ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)</code></p>
<p>图像字段。继承了<code>FileField</code>的所有属性和方法。而且还能自动验证上传的对象是否为合法的图像。</p>
<p><code>IntegerField()</code><br>
整型字段。</p>
<p><code>GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)</code><br>
ip地址字段<br>
<code>protocol='both/ipv4/ipv6'</code>: 默认为both<br>
<code>unpack_ipv4</code>: 用处不大。</p>
<p><code>NullBooleanField()</code><br>
类似于<code>BooleanField</code>,不同的是其允许值为<code>null</code></p>
<p><code>TextField()</code><br>
与<code>CharField</code>类似,但一般用来存储体积较大的文本。</p>
<p>TimeField(auto_now=False, auto_now_add=False, **options)`<br>
时间字段,其值为datetime.time实例</p>
<p>URLField(max_length=200, **options)<code>URL字段, 类似于</code>CharField`的子类,默认最大长度为200.</p>
<p>UUIDField(**options)<code>通用唯一标识字段,当不想用</code>django<code>默认设置的</code>AutoField`字段时,可以用该字段代替。</p>
<h4 id="关系字段">关系字段</h4>
<p><strong>1. 一对一</strong>: 现在有很多一对一辅导班,也就是上课时,一个老师对应一个学生,一个学生对应一个老师<br>
<strong>2. 多对一</strong>: 很多偏远山区的学校可能整个学校只有一个老师,这一个老师对应多个学生,所有的学生对应这一个老师<br>
<strong>3. 多对多</strong>: 而我们则很幸福,学校里有许多老师,一个老师教习一科,学生有多个老师,老师有多个学生。</p>
<h5 id="foreignkeyothermodel-on_delete-options">ForeignKey(othermodel, on_delete, **options)</h5>
<p>用于多对一或者一对多或者外键字段:<br>
<code>othermodel</code>: 所关联的模型,'多' model使用外键关联 '一'model。<br>
当所关联的模型为他自己时,使用'self';<br>
当引用的模型为其他app中的模型时,要加上app名称标签: 'app_name.model_name';<br>
数据库会自动在外键字段上创建索引,可以使用de_index=False关闭该功能。<br>
<code>on_delete</code>: 当删除 "一" 模型对象时,django会根据该参数的值对与该对象相关联的其他对象(也就是 '多’)进行操作。<br>
<em>在django1.9以及之前的版本中,on_delete作为一个关键字参数。而在1.10则可以作为第二个参数</em><br>
<code>models.CASCADE</code>: 默认为models.CASCADE 级联删除。当删除'一'时,'多’会被删除。比如:</p>
<pre><code class="language-python"># mysite项目下名为polls的app中的models.py
class follower(models.Model):
name = models.CharField(max_length=200)
menpai = models.ForeignKey('menpai', on_delete=models.CASCADE) #定义了models.CASCADE属性
def __str__(self):
return self.name
class menpai(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
#运行 python3 manager.py shell进入交互页面
>>> from polls.models import follower,menpai
>>> m1=menpai(name='huashanpai')
>>> m1.save()
>>> m2=menpai(name='riyuejiao')
>>> m2.save()
>>> f1=follower(name='linghuchong',menpai=m1)
>>> f1.save()
>>> f2=follower(name='renwoxing',menpai=m2)
>>> f2.save()
>>> f1.menpai
<menpai: huashanpai>
>>> m1.delete()
(2, {'polls.menpai': 1, 'polls.follower': 1}) # 删除华山派时,将令狐冲也删除了
</code></pre>
<p><code>modles.PROTECT</code> : 当删除一个具有外键关系的对象时,会引发一个异常,阻止删除该对象<br>
<code>models.SET_NULL</code>: 设置删除对象所关联的外键字段为null。但字段的null属性必需为True<br>
<code>models.SET_DEFAULT</code> : 设置删除对象所关联的外键字段为默认的值。<br>
<code>models.SET(value)</code>:设置删除对象所关联的对象的外键字段为value,value也可以是一个可调用函数。</p>
<pre><code class="language-python">from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
def get_sentinel_user():
return get_user_model().objects.get_or_create(username='deleted')[0]
class MyModel(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET(get_sentinel_user),
)
</code></pre>
<p><code>models.DO_NOTHING</code>: 不做任何操作<br>
<code>limit_choices_to</code>: 限制该字段为选项形。格式:<code>limit_choices_to={'is_staff': True}</code>。值也可以为可调用函数。</p>
<pre><code class="language-python">def limit_pub_date_choices():
return {'pub_date__lte': datetime.date.utcnow()}
limit_choices_to = limit_pub_date_choices
</code></pre>
<p><code>related_name</code> 设置从关联对象到自身的关系的名称,若值为'+' 则关联对象与自身无逆向关系。详解请看官方文档。举例:<br>
<code>related_name</code>的作用是在反向引用的时候,就是通过User去找<code>Employee</code>的时候,用<code>User.user_employee</code>,引文关键词叫:<code>reverse accessor</code>。</p>
<pre><code class="language-python">class Employee(generic.BO):
user = models.OneToOneField(User,verbose_name=_("登录账户"),blank=True,null=True,on_delete=models.CASCADE,related_name='user_employee')
</code></pre>
<p><code>to_field</code> 设置所关联对象的关联字段。默认为关联对象的主键字段。</p>
<p><a href="https://blog.csdn.net/djskl/article/details/42041767">OneToOneField和ForeignKey有什么区别</a></p>
<h5 id="manytomanyfieldothermodel-options">ManyToManyField(othermodel, **options)</h5>
<p>多对多字段。</p>
<p><code>othermodel</code>: 所关联的model名称;<br>
<code>db_table</code>: 多对多关系会在两个模型所对应的表中间创建一个'中间表’ ,将多对多转换为两个多对一,该选项为这个中间表设置名称。一般来说django会默认为中间表创建名称,但人们读起来可能搞不清楚究竟中间表关联到了哪里;<br>
<code>related_name</code>: 同多对一字段中的related_name;<br>
<code>limite_choices_to</code>: 同....;<br>
<code>symmetrical</code>: 当多对多关联对象为自身时可能会用到的参数。默认为True。a,b同属于person模型,person中的friends字段与自身设置了多对多关系,当该值设置为True时,django假定关系为对称,即:a是b的朋友,那么b也是a的朋友。设置为False时,django会强制为逆向关系创建描述信息;<br>
<code>though</code>: 不想让django自动创建中间表,手动创建中间表所对应的model,通过though指定对应的model名称;<br>
<code>though_field</code>: 当though参数被使用时,该参数才会有效。指定使用哪些中间模型字段来确立两个模型的多对多关系;</p>
<h5 id="onetoonefieldothermodel-on_delete-parent_linkfalse-options">OneToOneField(othermodel, on_delete, parent_link=False, **options)</h5>
<p>一对一字段。<br>
othermodel: .......<br>
on_delete:........<br>
related_name:...........<br>
<strong>参考资料</strong></p>
<ol>
<li><a href="https://stackoverflow.com/questions/27668064/fail-to-post-onetoonefield-with-django-rest">Fail to POST OneToOneField with Django REST</a></li>
<li><a href="https://docs.djangoproject.com/en/2.1/ref/models/fields/">参考</a></li>
</ol>
<p><strong>关联</strong><br>
<strong>关联未定义的Model</strong><br>
如果你要与某个尚未定义的model建立关联,就使用model的名称,而不是使用model对象本身。</p>
<pre><code class="language-python">class Book(models.Model):
pub = models.ForeignKey('Publisher')
</code></pre>
<p><strong>关联自身</strong><br>
可以与自身建立多对一或者一对一关系。</p>
<pre><code class="language-python">class People(models.Model):
name=models.CharField(max_length=20)
leader=models.ForeignKey('self',blank=True,null=True)
class Person(models.Model):
friends = models.ManyToManyField("self")
//通过shell添加关系
>>>p1.friends.add(p2,p3)
</code></pre>
<p>默认情况下,这种关联关系是对称的,如果<code>person1</code>是<code>person2</code>的朋友,那么<code>person2</code>也是<code>person1</code>的朋友,要查找<code>person2</code>的所有朋友可以直接使用<code>person2.friends.all()</code>。<br>
如果要取消这种对称关系,可以将<code>symmetrical</code>设置为False:</p>
<pre><code class="language-python">class Person2(models.Model):
friends=models.ManyToManyField("self",symmetrical=False)
</code></pre>
<p>这样查询p3的朋友,就需要<code>p3.person_set.all()</code>了<br>
<strong>反向名称related_name</strong><br>
反向名称用来从被关联字段指向关联字段。</p>
<pre><code class="language-python">class Book(models.Model):
name=models.CharField(max_length=20)
pub=models.ForeignKey(Publisher,related_name='pub')
authors=models.ManyToManyField(Author,related_name='author')
</code></pre>
<p>这样用Publisher或者Author反向查询Book时可以用related_name了:<code>publisher1.pub.all()</code>或者<code>author1.author.all()</code>。<br>
如果不想设置反向关心,则设置<code>related_name</code>为<code>'+'</code>或者以<code>'+'</code>结束。<br>
<code>user = models.ForeignKey(User, related_name='+')</code><br>
如果有多个<code>ManyToManyField</code>指向同一个Model,这样反向查询FOO_set的时候就无法弄清是哪个ManyToManyField字段了,所以可以禁止反向关系:</p>
<pre><code class="language-python">users = models.ManyToManyField(User, related_name='u+')
referents = models.ManyToManyField(User, related_name='ref+')
</code></pre>
<p><a href="https://blog.csdn.net/Crow_n/article/details/58135127?utm_source=blogxgwz7">参考</a></p>
<h2 id="认证和权限">认证和权限</h2>
<p><code>settings.py</code>设置默认的认证方式和权限。</p>
<pre><code class="language-python">REST_FRAMEWORK = {
# 全局,默认认证
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
# 'rest_framework.authentication.TokenAuthentication',
),
# 全局,默认权限
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}
</code></pre>
<h3 id="django-rest-auth">django-rest-auth</h3>
<p><code>django-rest-auth</code>用户管理app,<a href="https://django-rest-auth.readthedocs.io/en/latest/api_endpoints.html">网址</a></p>
<h4 id="用户管理">用户管理</h4>
<h5 id="登陆">登陆</h5>
<pre><code>/rest-auth/login/ (POST)
username
email
password
Returns Token key
</code></pre>
<h5 id="登出">登出</h5>
<pre><code>/rest-auth/logout/ (POST)
</code></pre>
<h5 id="重置密码">重置密码</h5>
<pre><code>/rest-auth/password/reset/ (POST)
email
</code></pre>
<h5 id="确认密码">确认密码</h5>
<pre><code>/rest-auth/password/reset/confirm/ (POST)
uid
token
new_password1
new_password2
</code></pre>
<p><strong>Note</strong>:<code>uid</code>和<code>token</code>是请求重置密码接口<code>/rest-auth/password/reset/</code>返回的</p>
<h5 id="修改密码">修改密码</h5>
<pre><code>/rest-auth/password/change/ (POST)
new_password1
new_password2
old_password
</code></pre>
<h5 id="查询用户信息">查询用户信息</h5>
<pre><code>/rest-auth/user/ (GET, PUT, PATCH)
username
first_name
last_name
Returns pk, username, email, first_name, last_name
</code></pre>
<h5 id="注册">注册</h5>
<pre><code>/rest-auth/registration/ (POST)
username
password1
password2
email
</code></pre>
<h5 id="确认">确认</h5>
<pre><code>/rest-auth/registration/verify-email/ (POST)
key
</code></pre>
<h3 id="自定义用户认证">自定义用户认证</h3>
<p><strong>BaseAuthentication</strong>类:<br>
<code>django rest-framework</code> 通过<code>BaseAuthentication</code> 实现认证功能,无论是自定义的认证类还是<code>rest-framework</code>自带的认证类都应该继承<code>BaseAuthentication</code>.<code>BaseAuthentication</code> 中有两个方法<code>authenticate</code>和<code>authenticate_header</code>,其中<code>authenticate</code>方法必须实现 如果用户需要自定义认证方法则继承<code>BaseAuthentication</code>重写<code>authenticate</code>方法即可.</p>
<ol>
<li>新建<code>UserToken</code><br>
修改<code>models.py</code>文件,增减<code>UserToken</code>类,其中<code>UserInfo</code>也可使用系统的User类,具体如下:</li>
</ol>
<pre><code class="language-python">from django.db import models
class UserInfo(models.Model):
user_type_choices = (
(1, '普通用户'),
(2, 'VPI'),
(3, 'SVPI'),
)
user_type = models.IntegerField(choices=user_type_choices)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=64)
class UserToken(models.Model):
user = models.OneToOneField('UserInfo', models.CASCADE)
token = models.CharField(max_length=64)
</code></pre>
<ol start="2">
<li>构建认证代码<br>
打开<code>APP_DIR/utils/auth.py</code>(若无,则新建该文件),将认证代码放入其中。</li>
</ol>
<pre><code class="language-python">from rest_framework import exceptions
from rest_framework.authentication import BaseAuthentication
from app01 import models
# 实现自定义的认证类
class Authtication(BaseAuthentication):
def authenticate(self, request):
# 这儿的 request 对象不是 django 原生的 request 而是 rest_framework 内部进行封装过的 request
# 使用 request._request 调用 django 原生的 request 对象
token = request._request.GET.get('token')
# 检查用户的 token 是否合法
token_obj = models.UserToken.objects.filter(token=token).first()
if not token_obj:
# rest_framework 会在内部捕捉这个异常并返回给用户认证失败的信息
raise exceptions.AuthenticationFailed('用户认证失败')
# 在 rest_framework 内部会将这两个字段赋值给request以供后续调用
return (token_obj.user, token_obj)
</code></pre>
<ol start="3">
<li>修改<code>views.py</code>文件</li>
</ol>
<pre><code class="language-python">from django.http import JsonResponse
from rest_framework.views import APIView
from app01.utils.auth import Authtication
import hashlib
import time
# 生成 token 字符串
def md5(user):
ctime = str(time.time())
m = hashlib.md5(bytes(user, encoding='utf-8'))
m.update(bytes(ctime, encoding='utf-8'))
return m.hexdigest()
# 用户登录
class AuthView(APIView):
def post(self, request):
ret = {'code':1000, 'msg':None}
try:
user = request._request.POST.get('username')
pwd = request._request.POST.get('password')
obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
if not obj:
ret['code'] = 1001
ret['msg'] = "用户名或密码错误"
# 为登录用户创建token
token = md5(user)
#存在更新 不存在创建
models.UserToken.objects.update_or_create(user=obj, defaults={'token':token})
ret['token'] = token
except:
ret['code'] = 1002
ret['msg'] = '请求异常'
return JsonResponse(ret)
# 业务代码
class Order(APIView):
# 注册自定义的认证类, 可以有多个, 从左到右进行认证匹配
authentication_classes = [Authtication,]
def get(self, request):
# request.user 这个值等于 Authtication 返回的元组的第一个值
# request.auth 这个值等于 Authtication 返回的元组的第二个值
ret = {'code':1000, 'msg':None, 'data':None}
ret['data'] = '欢迎使用本系统'
return JsonResponse(ret)
</code></pre>
<ol start="4">
<li><code>rest_framework</code>内置的认证类:</li>
</ol>
<pre><code class="language-python">BasicAuthentication # 基于浏览器实现的 Basic 认证, ftp 使用网页登录时使用的就是 Basic 认证
SessionAuthentication # 基于 django 的 user.is_active 进行认证
TokenAuthentication # 简单的基于 token 的认证
RemoteUserAuthentication # 简单的远程用户认证实现
</code></pre>
<p>可参考文档:<br>
<a href="https://blog.csdn.net/zzg_550413470/article/details/52239867">Django 认证系统</a></p>
<ol start="5">
<li>配置全局生效的认证类和匿名用户:<br>
自定义的认证类如果每次都在指定的类中使用<code>authentication_classes</code>指定,就有可能出现大量的重复代码。我们可以通过全局设置让指定的认证类对继承自<code>APIView</code>的所有类生效,修改<code>settings.py</code>文件。</li>
</ol>
<pre><code class="language-python">REST_FRAMEWORK = {
# 设置全局生效的认证类(可以有多个)
# app01 为 django app 的名称
# utils 为 app 目录下面的 utils 目录(这个目录必须包含 __init__.py 文件)
# auth 为 utils 目录下面的 auth.py 文件
# Authtication 为 auth.py 文件里面的 Authtication 类
# 这儿的设置其实就是使用 from ... import ... 的路径
'DEFAULT_AUTHENTICATION_CLASSES': ["app01.utils.auth.Authtication",],
#匿名用户配置
'UNAUTHENTICATED_USER': None, # 设置匿名用户的用户名, 默认为 AnonymousUser, 使用 request.user 查看
'UNAUTHENTICATED_TOKEN': None, # 设置匿名用户的 token, 默认为 None, 使用 request.auth 查看
}
</code></pre>
<ol start="6">
<li>指定<code>View</code>类不使用全局的认证类:<br>
在不使用全局认证类的<code>View</code>类中添加<code>authentication_classes = []</code>或者``authentication_classes = ['xxxx']`</li>
</ol>
<pre><code class="language-python"># authentication_classes = [] 表示不使用认证
# authentication_classes = ['xxxx'], xxxx 表示当前类需要使用的认证类用于替换全局类
</code></pre>
<p><a href="http://blog.51cto.com/hongchen99/2306783">参考链接</a></p>
<h2 id="错误">错误</h2>
<ol>
<li>Django Rest Framework - “detail”: “Not found.”`<br>
遇到的情况是url被其他路由拦截。</li>
<li><code>Django:CSRF Failed: CSRF token missing or incorrect</code><br>
登陆成功后一直返回<code>Django:CSRF Failed: CSRF token missing or incorrect</code>其实不是<code>跨域问题</code>,而是Django自带的<em>用户验证机制</em>导致,为此我们需要在请求头重添加<code>X-CSRFToken</code>,步骤如下:将Postman返回的cookie中的csrftoken值复制到请求头中,</li>
</ol>
<table>
<thead>
<tr>
<th>KEY</th>
<th>VALUE</th>
</tr>
</thead>
<tbody>
<tr>
<td>X-CSRFToken</td>
<td>cookie中的token值</td>
</tr>
</tbody>
</table>
<p>之后提交请求即可。</p>
<ol>
<li><a href="https://docs.djangoproject.com/en/2.1/ref/csrf/">官网链接</a></li>
<li><a href="http://python.jobbole.com/89305/?utm_source=blog.jobbole.com&utm_medium=relatedPosts">简化django的八个python包</a></li>
<li><a href="https://blog.csdn.net/Odyssues_lee/article/details/80948818">参考资料</a></li>
</ol>
<h2 id="数据查询">数据查询</h2>
<h3 id="django-queryset">django queryset</h3>
<p>实现基本的增删改查等。</p>
<ol>
<li><a href="https://feifeiyum.github.io/2017/03/28/python-django-queryset/">Django QuerySet 方法梳理</a></li>
<li><a href="https://feifeiyum.github.io/2017/04/10/python-django-querysetapi/">常用 Django QuerySet Api</a></li>
</ol>
<h3 id="django_filter">django_filter</h3>
<p>实现定制化的查询功能,可对不同字段进行精确和模糊查询。</p>
<ol>
<li><a href="https://pypi.org/project/django-filter/">pypy官网</a></li>
<li><a href="https://django-filter.readthedocs.io/en/master/guide/rest_framework.html">官方文档</a></li>
<li><a href="https://www.jianshu.com/p/3a6ab28b3925">用django-filter实现高级搜索</a></li>
</ol>
<h3 id="外键-serializer">外键 serializer</h3>
<p>自动序列化外键时会遇到一些问题。<br>
<strong>参考文献</strong></p>
<ol>
<li><a href="https://stackoverflow.com/questions/28706072/drf-3-creating-many-to-many-update-create-serializer-with-though-table#">DRF 3 - Creating Many-to-Many update/create serializer with though table<br>
</a></li>
<li><a href="https://stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers">DRF: Simple foreign key assignment with nested serializers?</a></li>
<li><a href="https://stackoverflow.com/questions/50015204/direct-assignment-to-the-forward-side-of-a-many-to-many-set-is-prohibited-use-e">manytomany 保存方式</a></li>
</ol>
<pre><code class="language-python"># 直接保存多对多关系
def create(self, validated_data):
if validated_data.get('help_poor'):
help_poor_datas = validated_data.pop('help_poor')
activity_arrangement = ActivityArrangement.objects.create(**validated_data)
for help_poor_data in help_poor_datas:
help_poor = HelpPoor.objects.create(**help_poor_data)
activity_arrangement.help_poor.add(help_poor)
else:
activity_arrangement = ActivityArrangement.objects.create(**validated_data)
return activity_arrangement
</code></pre>
<h2 id="数据库">数据库</h2>
<h3 id="数据库连接">数据库连接</h3>
<h4 id="django连接mongodb数据库">django连接mongodb数据库</h4>
<p><strong>参考文献</strong></p>
<ol>
<li><a href="https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html">Django MongoDB Engine</a></li>
<li><a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-enterprise-on-os-x/">mongo数据库官方文档</a></li>
</ol>
<h4 id="model-migrate-问题">model migrate 问题</h4>
<h5 id="django-migrate-error-table-xxx-already-exists">django migrate error: table 'xxx' already exists</h5>
<p>多为移库后,库表与migration文件不符造成,可以使用以下命令解决。</p>
<pre><code class="language-bash">python manage.py migrate --fake <appname>
</code></pre>
<p><strong>参考文献</strong></p>
<ol>
<li><a href="https://blog.csdn.net/zhiruchen/article/details/51243067">参考</a></li>
<li><a href="http://stackoverflow.com/questions/25924858/django-1-7-migrate-gets-error-table-already-exists">stack over flow</a></li>
</ol>
<h3 id="数据库迁移">数据库迁移</h3>
<h4 id="slqlite3迁移mysql">slqlite3迁移mysql</h4>
<p>数据库的迁移方法针对不同数据库,如 SQLite3, MySQL, PostgreSQL 之间数据迁移方案,以及数据在不同机器上迁移方案</p>