File: util.html

package info (click to toggle)
python-exchangelib 5.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,364 kB
  • sloc: python: 25,367; sh: 6; makefile: 5
file content (1734 lines) | stat: -rw-r--r-- 76,652 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
<meta name="generator" content="pdoc3 0.11.6">
<title>exchangelib.util API documentation</title>
<meta name="description" content="">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/sanitize.min.css" integrity="sha512-y1dtMcuvtTMJc1yPgEqF0ZjQbhnc/bFhyvIyVNb9Zk5mIGtqVaAB1Ttl28su8AvFMOY0EwRbAe+HCLqj6W7/KA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/13.0.0/typography.min.css" integrity="sha512-Y1DYSb995BAfxobCkKepB1BqJJTPrOp3zPL74AWFugHHmmdcvO+C48WLrUOlhGMc0QG7AE3f7gmvvcrmX2fDoA==" crossorigin>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:1.5em;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:2em 0 .50em 0}h3{font-size:1.4em;margin:1.6em 0 .7em 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .2s ease-in-out}a:visited{color:#503}a:hover{color:#b62}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900;font-weight:bold}pre code{font-size:.8em;line-height:1.4em;padding:1em;display:block}code{background:#f3f3f3;font-family:"DejaVu Sans Mono",monospace;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source > summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible;min-width:max-content}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em 1em;margin:1em 0}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul ul{padding-left:1em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js" integrity="sha512-D9gUyxqja7hBtkWpPWGt9wfbfaMGVt9gnyCvYa+jojwwPHLCzUm5i8rpk7vD7wNee9bA35eYIjobYPaQuKS1MQ==" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => {
hljs.configure({languages: ['bash', 'css', 'diff', 'graphql', 'ini', 'javascript', 'json', 'plaintext', 'python', 'python-repl', 'rust', 'shell', 'sql', 'typescript', 'xml', 'yaml']});
hljs.highlightAll();
/* Collapse source docstrings */
setTimeout(() => {
[...document.querySelectorAll('.hljs.language-python > .hljs-string')]
.filter(el => el.innerHTML.length > 200 && ['"""', "'''"].includes(el.innerHTML.substring(0, 3)))
.forEach(el => {
let d = document.createElement('details');
d.classList.add('hljs-string');
d.innerHTML = '<summary>"""</summary>' + el.innerHTML.substring(3);
el.replaceWith(d);
});
}, 100);
})</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>exchangelib.util</code></h1>
</header>
<section id="section-intro">
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="exchangelib.util.add_xml_child"><code class="name flex">
<span>def <span class="ident">add_xml_child</span></span>(<span>tree, name, value)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def add_xml_child(tree, name, value):
    # We&#39;re calling add_xml_child many places where we don&#39;t have the version handy. Don&#39;t pass EWSElement or list of
    # EWSElement to this function!
    tree.append(set_xml_value(elem=create_element(name), value=value))</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.chunkify"><code class="name flex">
<span>def <span class="ident">chunkify</span></span>(<span>iterable, chunksize)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def chunkify(iterable, chunksize):
    &#34;&#34;&#34;Split an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.

    :param iterable:
    :param chunksize:
    :return:
    &#34;&#34;&#34;
    from .queryset import QuerySet

    if hasattr(iterable, &#34;__getitem__&#34;) and not isinstance(iterable, QuerySet):
        # tuple, list. QuerySet has __getitem__ but that evaluates the entire query greedily. We don&#39;t want that here.
        for i in range(0, len(iterable), chunksize):
            yield iterable[i : i + chunksize]
    else:
        # generator, set, map, QuerySet
        chunk = []
        for i in iterable:
            chunk.append(i)
            if len(chunk) == chunksize:
                yield chunk
                chunk = []
        if chunk:
            yield chunk</code></pre>
</details>
<div class="desc"><p>Split an iterable into chunks of size <code>chunksize</code>. The last chunk may be smaller than <code>chunksize</code>.</p>
<p>:param iterable:
:param chunksize:
:return:</p></div>
</dd>
<dt id="exchangelib.util.create_element"><code class="name flex">
<span>def <span class="ident">create_element</span></span>(<span>name, attrs=None, nsmap=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def create_element(name, attrs=None, nsmap=None):
    if &#34;:&#34; in name:
        ns, name = name.split(&#34;:&#34;)
        name = f&#34;{{{ns_translation[ns]}}}{name}&#34;
    elem = _forgiving_parser.makeelement(name, nsmap=nsmap)
    if attrs:
        # Try hard to keep attribute order, to ensure deterministic output. This simplifies testing.
        # Dicts in Python 3.6+ have stable ordering.
        for k, v in attrs.items():
            if isinstance(v, bool):
                v = &#34;true&#34; if v else &#34;false&#34;
            elif isinstance(v, int):
                v = str(v)
            elem.set(k, v)
    return elem</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.get_domain"><code class="name flex">
<span>def <span class="ident">get_domain</span></span>(<span>email)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_domain(email):
    try:
        return email.split(&#34;@&#34;)[1].lower()
    except (IndexError, AttributeError):
        raise ValueError(f&#34;{email!r} is not a valid email&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.get_redirect_url"><code class="name flex">
<span>def <span class="ident">get_redirect_url</span></span>(<span>response, allow_relative=True, require_relative=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_redirect_url(response, allow_relative=True, require_relative=False):
    # allow_relative=False throws RelativeRedirect error if scheme and hostname are equal to the request
    # require_relative=True throws RelativeRedirect error if scheme and hostname are not equal to the request
    redirect_url = response.headers.get(&#34;location&#34;)
    if not redirect_url:
        raise TransportError(&#34;HTTP redirect but no location header&#34;)
    # At least some servers are kind enough to supply a new location. It may be relative
    redirect_has_ssl, redirect_server, redirect_path = split_url(redirect_url)
    # The response may have been redirected already. Get the original URL
    request_url = response.history[0] if response.history else response.url
    request_has_ssl, request_server, _ = split_url(request_url)
    response_has_ssl, response_server, response_path = split_url(response.url)

    if not redirect_server:
        # Redirect URL is relative. Inherit server and scheme from response URL
        redirect_server = response_server
        redirect_has_ssl = response_has_ssl
    if not redirect_path.startswith(&#34;/&#34;):
        # The path is not top-level. Add response path
        redirect_path = (response_path or &#34;/&#34;) + redirect_path
    redirect_url = f&#34;{&#39;https&#39; if redirect_has_ssl else &#39;http&#39;}://{redirect_server}{redirect_path}&#34;
    if redirect_url == request_url:
        # And some are mean enough to redirect to the same location
        raise TransportError(f&#34;Redirect to same location: {redirect_url}&#34;)
    if not allow_relative and (request_has_ssl == response_has_ssl and request_server == redirect_server):
        raise RelativeRedirect(redirect_url)
    if require_relative and (request_has_ssl != response_has_ssl or request_server != redirect_server):
        raise RelativeRedirect(redirect_url)
    return redirect_url</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.get_xml_attr"><code class="name flex">
<span>def <span class="ident">get_xml_attr</span></span>(<span>tree, name)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_xml_attr(tree, name):
    elem = tree.find(name)
    if elem is None:  # Must compare with None, see XML docs
        return None
    return elem.text or None</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.get_xml_attrs"><code class="name flex">
<span>def <span class="ident">get_xml_attrs</span></span>(<span>tree, name)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def get_xml_attrs(tree, name):
    return [elem.text for elem in tree.findall(name) if elem.text is not None]</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.is_iterable"><code class="name flex">
<span>def <span class="ident">is_iterable</span></span>(<span>value, generators_allowed=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_iterable(value, generators_allowed=False):
    &#34;&#34;&#34;Check if value is a list-like object. Don&#39;t match generators and generator-like objects here by default, because
    callers don&#39;t necessarily guarantee that they only iterate the value once. Take care to not match string types and
    bytes.

    :param value: any type of object
    :param generators_allowed: if True, generators will be treated as iterable (Default value = False)

    :return: True or False
    &#34;&#34;&#34;
    if generators_allowed:
        if not isinstance(value, (bytes, str)) and hasattr(value, &#34;__iter__&#34;):
            return True
    else:
        if isinstance(value, (tuple, list, set)):
            return True
    return False</code></pre>
</details>
<div class="desc"><p>Check if value is a list-like object. Don't match generators and generator-like objects here by default, because
callers don't necessarily guarantee that they only iterate the value once. Take care to not match string types and
bytes.</p>
<p>:param value: any type of object
:param generators_allowed: if True, generators will be treated as iterable (Default value = False)</p>
<p>:return: True or False</p></div>
</dd>
<dt id="exchangelib.util.is_xml"><code class="name flex">
<span>def <span class="ident">is_xml</span></span>(<span>text)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_xml(text):
    &#34;&#34;&#34;Lightweight test if response is an XML doc. It&#39;s better to be fast than correct here.

    :param text: The string to check
    :return:
    &#34;&#34;&#34;
    # BOM_UTF8 is a UTF-8 byte order mark which may precede the XML from an Exchange server
    bom_len = len(BOM_UTF8)
    expected_prefixes = (b&#34;&lt;?xml&#34;, b&#34;&lt;s:Envelope&#34;)
    max_prefix_len = len(expected_prefixes[1])
    if text[:bom_len] == BOM_UTF8:
        prefix = text[bom_len : bom_len + max_prefix_len]
    else:
        prefix = text[:max_prefix_len]
    for expected_prefix in expected_prefixes:
        if prefix[: len(expected_prefix)] == expected_prefix:
            return True
    return False</code></pre>
</details>
<div class="desc"><p>Lightweight test if response is an XML doc. It's better to be fast than correct here.</p>
<p>:param text: The string to check
:return:</p></div>
</dd>
<dt id="exchangelib.util.peek"><code class="name flex">
<span>def <span class="ident">peek</span></span>(<span>iterable)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def peek(iterable):
    &#34;&#34;&#34;Check if an iterable is empty and return status and the rewinded iterable.

    :param iterable:
    :return:
    &#34;&#34;&#34;
    if hasattr(iterable, &#34;__len__&#34;):
        # tuple, list, set
        return not iterable, iterable
    # generator
    try:
        first = next(iterable)
    except StopIteration:
        return True, iterable
    # We can&#39;t rewind a generator. Instead, chain the first element and the rest of the generator
    return False, itertools.chain([first], iterable)</code></pre>
</details>
<div class="desc"><p>Check if an iterable is empty and return status and the rewinded iterable.</p>
<p>:param iterable:
:return:</p></div>
</dd>
<dt id="exchangelib.util.post_ratelimited"><code class="name flex">
<span>def <span class="ident">post_ratelimited</span></span>(<span>protocol, session, url, headers, data, stream=False, timeout=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def post_ratelimited(protocol, session, url, headers, data, stream=False, timeout=None):
    &#34;&#34;&#34;There are two error-handling policies implemented here: a fail-fast policy intended for stand-alone scripts which
    fails on all responses except HTTP 200. The other policy is intended for long-running tasks that need to respect
    rate-limiting errors from the server and paper over outages of up to 1 hour.

    Wrap POST requests in a try-catch loop with a lot of error handling logic and some basic rate-limiting. If a request
    fails, and some conditions are met, the loop waits in increasing intervals, up to 1 hour, before trying again. The
    reason for this is that servers often malfunction for short periods of time, either because of ongoing data
    migrations or other maintenance tasks, misconfigurations or heavy load, or because the connecting user has hit a
    throttling policy limit.

    If the loop exited early, consumers of this package that don&#39;t implement their own rate-limiting code could quickly
    swamp such a server with new requests. That would only make things worse. Instead, it&#39;s better if the request loop
    waits patiently until the server is functioning again.

    If the connecting user has hit a throttling policy, then the server will start to malfunction in many interesting
    ways, but never actually tell the user what is happening. There is no way to distinguish this situation from other
    malfunctions. The only cure is to stop making requests.

    The contract on sessions here is to return the session that ends up being used, or retiring the session if we
    intend to raise an exception. We give up on max_wait timeout, not number of retries.

    An additional resource on handling throttling policies and client back off strategies:
        https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/ews-throttling-in-exchange

    :param protocol:
    :param session:
    :param url:
    :param headers:
    :param data:
    :param stream:  (Default value = False)
    :param timeout:

    :return:
    &#34;&#34;&#34;
    if not timeout:
        timeout = protocol.TIMEOUT
    thread_id = get_ident()
    log_msg = &#34;&#34;&#34;\
Timeout: %(timeout)s
Session: %(session_id)s
Thread: %(thread_id)s
Auth type: %(auth)s
URL: %(url)s
HTTP adapter: %(adapter)s
Streaming: %(stream)s
Response time: %(response_time)s
Status code: %(status_code)s
Request headers: %(request_headers)s
Response headers: %(response_headers)s&#34;&#34;&#34;
    xml_log_msg = &#34;&#34;&#34;\
Request XML: %(xml_request)s
Response XML: %(xml_response)s&#34;&#34;&#34;
    log_vals = dict(
        timeout=timeout,
        session_id=session.session_id,
        thread_id=thread_id,
        auth=session.auth,
        url=url,
        adapter=session.get_adapter(url),
        stream=stream,
        response_time=None,
        status_code=None,
        request_headers=headers,
        response_headers=None,
    )
    xml_log_vals = dict(
        xml_request=data,
        xml_response=None,
    )
    sleep_secs = _back_off_if_needed(protocol.retry_policy.back_off_until)
    if sleep_secs:
        # We may have slept for a long time. Renew the session.
        session = protocol.renew_session(session)
    log.debug(
        &#34;Session %s thread %s timeout %s: POST&#39;ing to %s after %ss sleep&#34;,
        session.session_id,
        thread_id,
        timeout,
        url,
        sleep_secs,
    )
    kwargs = dict(url=url, headers=headers, data=data, allow_redirects=False, timeout=timeout, stream=stream)
    if isinstance(session, OAuth2Session):
        # Fix token refreshing bug. Reported as https://github.com/requests/requests-oauthlib/issues/498
        kwargs.update(session.auto_refresh_kwargs)
    d_start = time.monotonic()
    try:
        r = session.post(**kwargs)
    except TLS_ERRORS as e:
        protocol.retire_session(session)
        # Don&#39;t retry on TLS errors. They will most likely be persistent.
        raise TransportError(str(e))
    except CONNECTION_ERRORS as e:
        protocol.retire_session(session)
        log.debug(&#34;Session %s thread %s: connection error POST&#39;ing to %s&#34;, session.session_id, thread_id, url)
        raise ErrorTimeoutExpired(f&#34;Reraised from {e.__class__.__name__}({e})&#34;)
    except (InvalidClientIdError, TokenExpiredError):
        log.debug(&#34;Session %s thread %s: OAuth token expired; refreshing&#34;, session.session_id, thread_id)
        protocol.release_session(protocol.refresh_credentials(session))
        raise
    except KeyError as e:
        protocol.retire_session(session)
        if e.args[0] != &#34;www-authenticate&#34;:
            raise
        # Server returned an HTTP error code during the NTLM handshake. Re-raise as internal server error
        log.debug(&#34;Session %s thread %s: auth headers missing from %s&#34;, session.session_id, thread_id, url)
        raise ErrorInternalServerTransientError(f&#34;Reraised from {e.__class__.__name__}({e})&#34;)
    except Exception as e:
        # Let higher layers handle this. Add full context for better debugging.
        log.error(&#34;%s: %s\n%s\n%s&#34;, e.__class__.__name__, str(e), log_msg % log_vals, xml_log_msg % xml_log_vals)
        protocol.retire_session(session)
        raise
    log_vals.update(
        session_id=session.session_id,
        url=r.url,
        response_time=time.monotonic() - d_start,
        status_code=r.status_code,
        request_headers=r.request.headers,
        response_headers=r.headers,
    )
    xml_log_vals.update(
        xml_request=data,
        xml_response=&#34;[STREAMING]&#34; if stream else r.content,
    )
    log.debug(log_msg, log_vals)
    xml_log.debug(xml_log_msg, xml_log_vals)

    try:
        protocol.retry_policy.raise_response_errors(r)
    except Exception:
        r.close()  # Release memory
        protocol.retire_session(session)
        raise

    log.debug(&#34;Session %s thread %s: Useful response from %s&#34;, session.session_id, thread_id, url)
    return r, session</code></pre>
</details>
<div class="desc"><p>There are two error-handling policies implemented here: a fail-fast policy intended for stand-alone scripts which
fails on all responses except HTTP 200. The other policy is intended for long-running tasks that need to respect
rate-limiting errors from the server and paper over outages of up to 1 hour.</p>
<p>Wrap POST requests in a try-catch loop with a lot of error handling logic and some basic rate-limiting. If a request
fails, and some conditions are met, the loop waits in increasing intervals, up to 1 hour, before trying again. The
reason for this is that servers often malfunction for short periods of time, either because of ongoing data
migrations or other maintenance tasks, misconfigurations or heavy load, or because the connecting user has hit a
throttling policy limit.</p>
<p>If the loop exited early, consumers of this package that don't implement their own rate-limiting code could quickly
swamp such a server with new requests. That would only make things worse. Instead, it's better if the request loop
waits patiently until the server is functioning again.</p>
<p>If the connecting user has hit a throttling policy, then the server will start to malfunction in many interesting
ways, but never actually tell the user what is happening. There is no way to distinguish this situation from other
malfunctions. The only cure is to stop making requests.</p>
<p>The contract on sessions here is to return the session that ends up being used, or retiring the session if we
intend to raise an exception. We give up on max_wait timeout, not number of retries.</p>
<p>An additional resource on handling throttling policies and client back off strategies:
<a href="https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/ews-throttling-in-exchange">https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/ews-throttling-in-exchange</a></p>
<p>:param protocol:
:param session:
:param url:
:param headers:
:param data:
:param stream:
(Default value = False)
:param timeout:</p>
<p>:return:</p></div>
</dd>
<dt id="exchangelib.util.prepare_input_source"><code class="name flex">
<span>def <span class="ident">prepare_input_source</span></span>(<span>source)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def prepare_input_source(source):
    # Extracted from xml.sax.expatreader.saxutils.prepare_input_source
    f = source
    source = _InputSource()
    source.setByteStream(f)
    return source</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.require_account"><code class="name flex">
<span>def <span class="ident">require_account</span></span>(<span>f)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def require_account(f):
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        if not self.account:
            raise ValueError(f&#34;{self.__class__.__name__} must have an account&#34;)
        return f(self, *args, **kwargs)

    return wrapper</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.require_id"><code class="name flex">
<span>def <span class="ident">require_id</span></span>(<span>f)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def require_id(f):
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        if not self.account:
            raise ValueError(f&#34;{self.__class__.__name__} must have an account&#34;)
        if not self.id:
            raise ValueError(f&#34;{self.__class__.__name__} must have an ID&#34;)
        return f(self, *args, **kwargs)

    return wrapper</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.safe_b64decode"><code class="name flex">
<span>def <span class="ident">safe_b64decode</span></span>(<span>data)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def safe_b64decode(data):
    # Incoming base64-encoded data is not always padded to a multiple of 4. Python&#39;s parser is stricter and requires
    # padding. Add padding if it&#39;s needed.
    overflow = len(data) % 4
    if overflow:
        if isinstance(data, str):
            padding = &#34;=&#34; * (4 - overflow)
        else:
            padding = b&#34;=&#34; * (4 - overflow)
        data += padding
    return b64decode(data)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.safe_xml_value"><code class="name flex">
<span>def <span class="ident">safe_xml_value</span></span>(<span>value, replacement='?')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def safe_xml_value(value, replacement=&#34;?&#34;):
    return _ILLEGAL_XML_CHARS_RE.sub(replacement, value)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.sanitize_xml"><code class="name flex">
<span>def <span class="ident">sanitize_xml</span></span>(<span>data, replacement=b'?')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def sanitize_xml(data, replacement=b&#34;?&#34;):
    if not isinstance(data, bytes):
        # We may get data=&#34;&#34; from some expatreader versions
        return data
    return _ILLEGAL_XML_ESCAPE_CHARS_RE.sub(replacement, data)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.set_xml_value"><code class="name flex">
<span>def <span class="ident">set_xml_value</span></span>(<span>elem, value, version=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def set_xml_value(elem, value, version=None):
    from .ewsdatetime import EWSDate, EWSDateTime
    from .fields import FieldOrder, FieldPath
    from .properties import EWSElement

    if isinstance(value, (str, bool, bytes, int, Decimal, datetime.time, EWSDate, EWSDateTime)):
        elem.text = value_to_xml_text(value)
    elif isinstance(value, _element_class):
        elem.append(value)
    elif isinstance(value, (FieldPath, FieldOrder)):
        elem.append(value.to_xml())
    elif isinstance(value, EWSElement):
        elem.append(value.to_xml(version=version))
    elif is_iterable(value, generators_allowed=True):
        for v in value:
            set_xml_value(elem, v, version=version)
    else:
        raise ValueError(f&#34;Unsupported type {type(value)} for value {value} on elem {elem}&#34;)
    return elem</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.split_url"><code class="name flex">
<span>def <span class="ident">split_url</span></span>(<span>url)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def split_url(url):
    parsed_url = urlparse(url)
    # Use netloc instead of hostname since hostname is None if URL is relative
    return parsed_url.scheme == &#34;https&#34;, parsed_url.netloc.lower(), parsed_url.path</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.to_xml"><code class="name flex">
<span>def <span class="ident">to_xml</span></span>(<span>bytes_content)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_xml(bytes_content):
    &#34;&#34;&#34;Convert bytes or a generator of bytes to an XML tree.&#34;&#34;&#34;
    # Exchange servers may spit out the weirdest XML. lxml is pretty good at recovering from errors
    if isinstance(bytes_content, bytes):
        stream = io.BytesIO(bytes_content)
    else:
        stream = BytesGeneratorIO(bytes_content)
    try:
        res = lxml.etree.parse(stream, parser=_forgiving_parser)  # nosec
    except AssertionError as e:
        raise ParseError(e.args[0], &#34;&lt;not from file&gt;&#34;, -1, 0)
    except lxml.etree.ParseError as e:
        if hasattr(e, &#34;position&#34;):
            e.lineno, e.offset = e.position
        if not e.lineno:
            raise ParseError(str(e), &#34;&lt;not from file&gt;&#34;, e.lineno, e.offset)
        try:
            stream.seek(0)
            offending_line = stream.read().splitlines()[e.lineno - 1]
        except (IndexError, io.UnsupportedOperation):
            raise ParseError(str(e), &#34;&lt;not from file&gt;&#34;, e.lineno, e.offset)
        offending_excerpt = offending_line[max(0, e.offset - 20) : e.offset + 20]
        msg = f&#39;{e}\nOffending text: [...]{offending_excerpt.decode(&#34;utf-8&#34;, errors=&#34;ignore&#34;)}[...]&#39;
        raise ParseError(msg, &#34;&lt;not from file&gt;&#34;, e.lineno, e.offset)
    except TypeError:
        with suppress(IndexError, io.UnsupportedOperation):
            stream.seek(0)
        raise ParseError(f&#34;This is not XML: {stream.read()!r}&#34;, &#34;&lt;not from file&gt;&#34;, -1, 0)

    if res.getroot() is None:
        try:
            stream.seek(0)
            msg = f&#34;No root element found: {stream.read()!r}&#34;
        except (IndexError, io.UnsupportedOperation):
            msg = &#34;No root element found&#34;
        raise ParseError(msg, &#34;&lt;not from file&gt;&#34;, -1, 0)
    return res</code></pre>
</details>
<div class="desc"><p>Convert bytes or a generator of bytes to an XML tree.</p></div>
</dd>
<dt id="exchangelib.util.value_to_xml_text"><code class="name flex">
<span>def <span class="ident">value_to_xml_text</span></span>(<span>value)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def value_to_xml_text(value):
    from .ewsdatetime import EWSDate, EWSDateTime, EWSTimeZone
    from .indexed_properties import SingleFieldIndexedElement
    from .properties import AssociatedCalendarItemId, Attendee, ConversationId, Mailbox

    # We can&#39;t just create a map and look up with type(value) because we want to support subtypes
    if isinstance(value, str):
        return safe_xml_value(value)
    if isinstance(value, bool):
        return &#34;1&#34; if value else &#34;0&#34;
    if isinstance(value, bytes):
        return b64encode(value).decode(&#34;ascii&#34;)
    if isinstance(value, (int, Decimal)):
        return str(value)
    if isinstance(value, datetime.time):
        return value.isoformat()
    if isinstance(value, EWSTimeZone):
        return value.ms_id
    if isinstance(value, (EWSDate, EWSDateTime)):
        return value.ewsformat()
    if isinstance(value, SingleFieldIndexedElement):
        return getattr(value, value.value_field(version=None).name)
    if isinstance(value, Mailbox):
        return value.email_address
    if isinstance(value, Attendee):
        return value.mailbox.email_address
    if isinstance(value, (ConversationId, AssociatedCalendarItemId)):
        return value.id
    raise TypeError(f&#34;Unsupported type: {type(value)} ({value})&#34;)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.xml_text_to_value"><code class="name flex">
<span>def <span class="ident">xml_text_to_value</span></span>(<span>value, value_type)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def xml_text_to_value(value, value_type):
    from .ewsdatetime import EWSDate, EWSDateTime

    if value_type == str:
        return value
    if value_type == bool:
        try:
            return {
                &#34;true&#34;: True,
                &#34;on&#34;: True,
                &#34;false&#34;: False,
                &#34;off&#34;: False,
            }[value.lower()]
        except KeyError:
            return None
    return {
        bytes: safe_b64decode,
        int: int,
        Decimal: Decimal,
        datetime.timedelta: isodate.parse_duration,
        EWSDate: EWSDate.from_string,
        EWSDateTime: EWSDateTime.from_string,
    }[value_type](value)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.xml_to_str"><code class="name flex">
<span>def <span class="ident">xml_to_str</span></span>(<span>tree, encoding=None, xml_declaration=False)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def xml_to_str(tree, encoding=None, xml_declaration=False):
    &#34;&#34;&#34;Serialize an XML tree. Returns unicode if &#39;encoding&#39; is None. Otherwise, we return encoded &#39;bytes&#39;.

    :param tree:
    :param encoding:  (Default value = None)
    :param xml_declaration:  (Default value = False)
    :return:
    &#34;&#34;&#34;
    if xml_declaration and not encoding:
        raise AttributeError(&#34;&#39;xml_declaration&#39; is not supported when &#39;encoding&#39; is None&#34;)
    if encoding:
        return lxml.etree.tostring(tree, encoding=encoding, xml_declaration=True)
    return lxml.etree.tostring(tree, encoding=str, xml_declaration=False)</code></pre>
</details>
<div class="desc"><p>Serialize an XML tree. Returns unicode if 'encoding' is None. Otherwise, we return encoded 'bytes'.</p>
<p>:param tree:
:param encoding:
(Default value = None)
:param xml_declaration:
(Default value = False)
:return:</p></div>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="exchangelib.util.AnonymizingXmlHandler"><code class="flex name class">
<span>class <span class="ident">AnonymizingXmlHandler</span></span>
<span>(</span><span>forbidden_strings, *args, **kwargs)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class AnonymizingXmlHandler(PrettyXmlHandler):
    &#34;&#34;&#34;A steaming log handler that prettifies and anonymizes log statements containing XML when output is a terminal.&#34;&#34;&#34;

    PRIVATE_TAGS = {&#34;RootItemId&#34;, &#34;ItemId&#34;, &#34;Id&#34;, &#34;RootItemChangeKey&#34;, &#34;ChangeKey&#34;}

    def __init__(self, forbidden_strings, *args, **kwargs):
        self.forbidden_strings = forbidden_strings
        super().__init__(*args, **kwargs)

    def parse_bytes(self, xml_bytes):
        root = to_xml(xml_bytes)
        for elem in root.iter():
            # Anonymize element attribute values known to contain private data
            for attr in set(elem.keys()) &amp; self.PRIVATE_TAGS:
                elem.set(attr, &#34;DEADBEEF=&#34;)
            # Anonymize anything requested by the caller
            for s in self.forbidden_strings:
                if elem.text is not None:
                    elem.text = elem.text.replace(s, &#34;[REMOVED]&#34;)
        return root</code></pre>
</details>
<div class="desc"><p>A steaming log handler that prettifies and anonymizes log statements containing XML when output is a terminal.</p>
<p>Initialize the handler.</p>
<p>If stream is not specified, sys.stderr is used.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li><a title="exchangelib.util.PrettyXmlHandler" href="#exchangelib.util.PrettyXmlHandler">PrettyXmlHandler</a></li>
<li>logging.StreamHandler</li>
<li>logging.Handler</li>
<li>logging.Filterer</li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="exchangelib.util.AnonymizingXmlHandler.PRIVATE_TAGS"><code class="name">var <span class="ident">PRIVATE_TAGS</span></code></dt>
<dd>
<div class="desc"><p>The type of the None singleton.</p></div>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.AnonymizingXmlHandler.parse_bytes"><code class="name flex">
<span>def <span class="ident">parse_bytes</span></span>(<span>self, xml_bytes)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def parse_bytes(self, xml_bytes):
    root = to_xml(xml_bytes)
    for elem in root.iter():
        # Anonymize element attribute values known to contain private data
        for attr in set(elem.keys()) &amp; self.PRIVATE_TAGS:
            elem.set(attr, &#34;DEADBEEF=&#34;)
        # Anonymize anything requested by the caller
        for s in self.forbidden_strings:
            if elem.text is not None:
                elem.text = elem.text.replace(s, &#34;[REMOVED]&#34;)
    return root</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
<h3>Inherited members</h3>
<ul class="hlist">
<li><code><b><a title="exchangelib.util.PrettyXmlHandler" href="#exchangelib.util.PrettyXmlHandler">PrettyXmlHandler</a></b></code>:
<ul class="hlist">
<li><code><a title="exchangelib.util.PrettyXmlHandler.emit" href="#exchangelib.util.PrettyXmlHandler.emit">emit</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.highlight_xml" href="#exchangelib.util.PrettyXmlHandler.highlight_xml">highlight_xml</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.is_tty" href="#exchangelib.util.PrettyXmlHandler.is_tty">is_tty</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.prettify_xml" href="#exchangelib.util.PrettyXmlHandler.prettify_xml">prettify_xml</a></code></li>
</ul>
</li>
</ul>
</dd>
<dt id="exchangelib.util.BytesGeneratorIO"><code class="flex name class">
<span>class <span class="ident">BytesGeneratorIO</span></span>
<span>(</span><span>bytes_generator)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class BytesGeneratorIO(io.RawIOBase):
    &#34;&#34;&#34;A BytesIO that can produce bytes from a streaming HTTP request. Expects r.iter_content() as input
    lxml tries to be smart by calling `getvalue` when present, assuming that the entire string is in memory.
    Omitting `getvalue` forces lxml to stream the request through `read` avoiding the memory duplication.
    &#34;&#34;&#34;

    def __init__(self, bytes_generator):
        self._bytes_generator = bytes_generator
        self._next = bytearray()
        self._tell = 0
        super().__init__()

    def readable(self):
        return not self.closed

    def tell(self):
        return self._tell

    def read(self, size=-1):
        # requests `iter_content()` auto-adjusts the number of bytes based on bandwidth.
        # We can&#39;t assume how many bytes next returns so stash any extra in `self._next`.
        if self._next is None:
            return b&#34;&#34;
        if size is None:
            size = -1

        res = self._next
        while size &lt; 0 or len(res) &lt; size:
            try:
                res.extend(next(self._bytes_generator))
            except StopIteration:
                self._next = None
                break

        if size &gt; 0 and self._next is not None:
            self._next = res[size:]
            res = res[:size]

        self._tell += len(res)
        return bytes(res)

    def close(self):
        if not self.closed:
            self._bytes_generator.close()
        super().close()</code></pre>
</details>
<div class="desc"><p>A BytesIO that can produce bytes from a streaming HTTP request. Expects r.iter_content() as input
lxml tries to be smart by calling <code>getvalue</code> when present, assuming that the entire string is in memory.
Omitting <code>getvalue</code> forces lxml to stream the request through <code>read</code> avoiding the memory duplication.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>io.RawIOBase</li>
<li>_io._RawIOBase</li>
<li>io.IOBase</li>
<li>_io._IOBase</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.BytesGeneratorIO.close"><code class="name flex">
<span>def <span class="ident">close</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def close(self):
    if not self.closed:
        self._bytes_generator.close()
    super().close()</code></pre>
</details>
<div class="desc"><p>Flush and close the IO object.</p>
<p>This method has no effect if the file is already closed.</p></div>
</dd>
<dt id="exchangelib.util.BytesGeneratorIO.read"><code class="name flex">
<span>def <span class="ident">read</span></span>(<span>self, size=-1)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def read(self, size=-1):
    # requests `iter_content()` auto-adjusts the number of bytes based on bandwidth.
    # We can&#39;t assume how many bytes next returns so stash any extra in `self._next`.
    if self._next is None:
        return b&#34;&#34;
    if size is None:
        size = -1

    res = self._next
    while size &lt; 0 or len(res) &lt; size:
        try:
            res.extend(next(self._bytes_generator))
        except StopIteration:
            self._next = None
            break

    if size &gt; 0 and self._next is not None:
        self._next = res[size:]
        res = res[:size]

    self._tell += len(res)
    return bytes(res)</code></pre>
</details>
<div class="desc"></div>
</dd>
<dt id="exchangelib.util.BytesGeneratorIO.readable"><code class="name flex">
<span>def <span class="ident">readable</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def readable(self):
    return not self.closed</code></pre>
</details>
<div class="desc"><p>Return whether object was opened for reading.</p>
<p>If False, read() will raise OSError.</p></div>
</dd>
<dt id="exchangelib.util.BytesGeneratorIO.tell"><code class="name flex">
<span>def <span class="ident">tell</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def tell(self):
    return self._tell</code></pre>
</details>
<div class="desc"><p>Return current stream position.</p></div>
</dd>
</dl>
</dd>
<dt id="exchangelib.util.DocumentYielder"><code class="flex name class">
<span>class <span class="ident">DocumentYielder</span></span>
<span>(</span><span>content_iterator, document_tag='Envelope')</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class DocumentYielder:
    &#34;&#34;&#34;Look for XML documents in a streaming HTTP response and yield them as they become available from the stream.&#34;&#34;&#34;

    def __init__(self, content_iterator, document_tag=&#34;Envelope&#34;):
        self._iterator = content_iterator
        self._document_tag = document_tag.encode()

    def _get_tag(self):
        &#34;&#34;&#34;Iterate over the bytes until we have a full tag in the buffer. If there&#39;s a &#39;&gt;&#39; in an attr value, then we&#39;ll
        exit on that, but it&#39;s OK because we just need the plain tag name later.
        &#34;&#34;&#34;
        tag_buffer = [b&#34;&lt;&#34;]
        while True:
            try:
                c = next(self._iterator)
            except StopIteration:
                break
            tag_buffer.append(c)
            if c == b&#34;&gt;&#34;:
                break
        return b&#34;&#34;.join(tag_buffer)

    @staticmethod
    def _normalize_tag(tag):
        &#34;&#34;&#34;Returns the plain tag name given a range of tag formats:
        * &lt;tag&gt;
        * &lt;ns:tag&gt;
        * &lt;ns:tag foo=&#39;bar&#39;&gt;
        * &lt;/ns:tag foo=&#39;bar&#39;&gt;
        &#34;&#34;&#34;
        return tag.strip(b&#34;&lt;&gt;/&#34;).split(b&#34; &#34;)[0].split(b&#34;:&#34;)[-1]

    def __iter__(self):
        &#34;&#34;&#34;Consumes the content iterator, looking for start and end tags. Returns each document when we have fully
        collected it.
        &#34;&#34;&#34;
        doc_started = False
        buffer = []
        try:
            while True:
                c = next(self._iterator)
                if not doc_started and c == b&#34;&lt;&#34;:
                    tag = self._get_tag()
                    if self._normalize_tag(tag) == self._document_tag:
                        # Start of document. Collect bytes from this point
                        buffer.append(tag)
                        doc_started = True
                elif doc_started and c == b&#34;&lt;&#34;:
                    tag = self._get_tag()
                    buffer.append(tag)
                    if self._normalize_tag(tag) == self._document_tag:
                        # End of document. Yield a valid document and reset the buffer
                        yield b&#34;&lt;?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39;?&gt;\n&#34; + b&#34;&#34;.join(buffer)
                        doc_started = False
                        buffer = []
                elif doc_started:
                    buffer.append(c)
        except StopIteration:
            return</code></pre>
</details>
<div class="desc"><p>Look for XML documents in a streaming HTTP response and yield them as they become available from the stream.</p></div>
</dd>
<dt id="exchangelib.util.DummyRequest"><code class="flex name class">
<span>class <span class="ident">DummyRequest</span></span>
<span>(</span><span>headers=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class DummyRequest:
    &#34;&#34;&#34;A class to fake a requests Request object for functions that expect this.&#34;&#34;&#34;

    def __init__(self, headers=None):
        self.headers = headers or {}</code></pre>
</details>
<div class="desc"><p>A class to fake a requests Request object for functions that expect this.</p></div>
</dd>
<dt id="exchangelib.util.DummyResponse"><code class="flex name class">
<span>class <span class="ident">DummyResponse</span></span>
<span>(</span><span>url=None,<br>headers=None,<br>request_headers=None,<br>content=b'',<br>status_code=503,<br>streaming=False,<br>history=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class DummyResponse:
    &#34;&#34;&#34;A class to fake a requests Response object for functions that expect this.&#34;&#34;&#34;

    def __init__(
        self, url=None, headers=None, request_headers=None, content=b&#34;&#34;, status_code=503, streaming=False, history=None
    ):
        self.status_code = status_code
        self.url = url
        self.headers = headers or {}
        self.content = iter((bytes([b]) for b in content)) if streaming else content
        self.text = content.decode(&#34;utf-8&#34;, errors=&#34;ignore&#34;)
        self.request = DummyRequest(headers=request_headers)
        self.reason = &#34;&#34;
        self.history = history

    def iter_content(self):
        return self.content

    def close(self):
        &#34;&#34;&#34;We don&#39;t have an actual socket to close&#34;&#34;&#34;</code></pre>
</details>
<div class="desc"><p>A class to fake a requests Response object for functions that expect this.</p></div>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.DummyResponse.close"><code class="name flex">
<span>def <span class="ident">close</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def close(self):
    &#34;&#34;&#34;We don&#39;t have an actual socket to close&#34;&#34;&#34;</code></pre>
</details>
<div class="desc"><p>We don't have an actual socket to close</p></div>
</dd>
<dt id="exchangelib.util.DummyResponse.iter_content"><code class="name flex">
<span>def <span class="ident">iter_content</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def iter_content(self):
    return self.content</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
</dd>
<dt id="exchangelib.util.ElementNotFound"><code class="flex name class">
<span>class <span class="ident">ElementNotFound</span></span>
<span>(</span><span>msg, data)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ElementNotFound(Exception):
    &#34;&#34;&#34;Raised when the expected element was not found in a response stream.&#34;&#34;&#34;

    def __init__(self, msg, data):
        super().__init__(msg)
        self.data = data</code></pre>
</details>
<div class="desc"><p>Raised when the expected element was not found in a response stream.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>builtins.Exception</li>
<li>builtins.BaseException</li>
</ul>
</dd>
<dt id="exchangelib.util.ParseError"><code class="flex name class">
<span>class <span class="ident">ParseError</span></span>
<span>(</span><span>message, code, line, column, filename=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class ParseError(lxml.etree.ParseError):
    &#34;&#34;&#34;Used to wrap lxml ParseError in our own class.&#34;&#34;&#34;</code></pre>
</details>
<div class="desc"><p>Used to wrap lxml ParseError in our own class.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>lxml.etree.ParseError</li>
<li>lxml.etree.LxmlSyntaxError</li>
<li>lxml.etree.LxmlError</li>
<li>lxml.etree.Error</li>
<li>builtins.SyntaxError</li>
<li>builtins.Exception</li>
<li>builtins.BaseException</li>
</ul>
</dd>
<dt id="exchangelib.util.PrettyXmlHandler"><code class="flex name class">
<span>class <span class="ident">PrettyXmlHandler</span></span>
<span>(</span><span>stream=None)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class PrettyXmlHandler(logging.StreamHandler):
    &#34;&#34;&#34;A steaming log handler that prettifies log statements containing XML when output is a terminal.&#34;&#34;&#34;

    @staticmethod
    def parse_bytes(xml_bytes):
        return to_xml(xml_bytes)

    def prettify_xml(self, xml_bytes):
        &#34;&#34;&#34;Re-format an XML document to a consistent style.&#34;&#34;&#34;
        return (
            lxml.etree.tostring(self.parse_bytes(xml_bytes), xml_declaration=True, encoding=&#34;utf-8&#34;, pretty_print=True)
            .replace(b&#34; xmlns:&#34;, b&#34;\n    xmlns:&#34;)
            .expandtabs()
        )

    @staticmethod
    def highlight_xml(xml_str):
        &#34;&#34;&#34;Highlight a string containing XML, using terminal color codes.&#34;&#34;&#34;
        return highlight(xml_str, XmlLexer(), TerminalFormatter()).rstrip()

    def emit(self, record):
        &#34;&#34;&#34;Pretty-print and syntax highlight a log statement if all these conditions are met:
           * This is a DEBUG message
           * We&#39;re outputting to a terminal
           * The log message args is a dict containing keys starting with &#39;xml_&#39; and values as bytes

        :param record:
        &#34;&#34;&#34;
        if record.levelno == logging.DEBUG and self.is_tty() and isinstance(record.args, dict):
            for key, value in record.args.items():
                if not key.startswith(&#34;xml_&#34;):
                    continue
                if not isinstance(value, bytes):
                    continue
                if not is_xml(value):
                    continue
                try:
                    record.args[key] = self.highlight_xml(self.prettify_xml(value))
                except Exception as e:
                    # Something bad happened, but we don&#39;t want to crash the program just because logging failed
                    print(f&#34;XML highlighting failed: {e}&#34;)
        return super().emit(record)

    def is_tty(self):
        &#34;&#34;&#34;Check if we&#39;re outputting to a terminal.&#34;&#34;&#34;
        try:
            return self.stream.isatty()
        except AttributeError:
            return False</code></pre>
</details>
<div class="desc"><p>A steaming log handler that prettifies log statements containing XML when output is a terminal.</p>
<p>Initialize the handler.</p>
<p>If stream is not specified, sys.stderr is used.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>logging.StreamHandler</li>
<li>logging.Handler</li>
<li>logging.Filterer</li>
</ul>
<h3>Subclasses</h3>
<ul class="hlist">
<li><a title="exchangelib.util.AnonymizingXmlHandler" href="#exchangelib.util.AnonymizingXmlHandler">AnonymizingXmlHandler</a></li>
</ul>
<h3>Static methods</h3>
<dl>
<dt id="exchangelib.util.PrettyXmlHandler.highlight_xml"><code class="name flex">
<span>def <span class="ident">highlight_xml</span></span>(<span>xml_str)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def highlight_xml(xml_str):
    &#34;&#34;&#34;Highlight a string containing XML, using terminal color codes.&#34;&#34;&#34;
    return highlight(xml_str, XmlLexer(), TerminalFormatter()).rstrip()</code></pre>
</details>
<div class="desc"><p>Highlight a string containing XML, using terminal color codes.</p></div>
</dd>
<dt id="exchangelib.util.PrettyXmlHandler.parse_bytes"><code class="name flex">
<span>def <span class="ident">parse_bytes</span></span>(<span>xml_bytes)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def parse_bytes(xml_bytes):
    return to_xml(xml_bytes)</code></pre>
</details>
<div class="desc"></div>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.PrettyXmlHandler.emit"><code class="name flex">
<span>def <span class="ident">emit</span></span>(<span>self, record)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def emit(self, record):
    &#34;&#34;&#34;Pretty-print and syntax highlight a log statement if all these conditions are met:
       * This is a DEBUG message
       * We&#39;re outputting to a terminal
       * The log message args is a dict containing keys starting with &#39;xml_&#39; and values as bytes

    :param record:
    &#34;&#34;&#34;
    if record.levelno == logging.DEBUG and self.is_tty() and isinstance(record.args, dict):
        for key, value in record.args.items():
            if not key.startswith(&#34;xml_&#34;):
                continue
            if not isinstance(value, bytes):
                continue
            if not is_xml(value):
                continue
            try:
                record.args[key] = self.highlight_xml(self.prettify_xml(value))
            except Exception as e:
                # Something bad happened, but we don&#39;t want to crash the program just because logging failed
                print(f&#34;XML highlighting failed: {e}&#34;)
    return super().emit(record)</code></pre>
</details>
<div class="desc"><p>Pretty-print and syntax highlight a log statement if all these conditions are met:
* This is a DEBUG message
* We're outputting to a terminal
* The log message args is a dict containing keys starting with 'xml_' and values as bytes</p>
<p>:param record:</p></div>
</dd>
<dt id="exchangelib.util.PrettyXmlHandler.is_tty"><code class="name flex">
<span>def <span class="ident">is_tty</span></span>(<span>self)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def is_tty(self):
    &#34;&#34;&#34;Check if we&#39;re outputting to a terminal.&#34;&#34;&#34;
    try:
        return self.stream.isatty()
    except AttributeError:
        return False</code></pre>
</details>
<div class="desc"><p>Check if we're outputting to a terminal.</p></div>
</dd>
<dt id="exchangelib.util.PrettyXmlHandler.prettify_xml"><code class="name flex">
<span>def <span class="ident">prettify_xml</span></span>(<span>self, xml_bytes)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def prettify_xml(self, xml_bytes):
    &#34;&#34;&#34;Re-format an XML document to a consistent style.&#34;&#34;&#34;
    return (
        lxml.etree.tostring(self.parse_bytes(xml_bytes), xml_declaration=True, encoding=&#34;utf-8&#34;, pretty_print=True)
        .replace(b&#34; xmlns:&#34;, b&#34;\n    xmlns:&#34;)
        .expandtabs()
    )</code></pre>
</details>
<div class="desc"><p>Re-format an XML document to a consistent style.</p></div>
</dd>
</dl>
</dd>
<dt id="exchangelib.util.StreamingBase64Parser"><code class="flex name class">
<span>class <span class="ident">StreamingBase64Parser</span></span>
<span>(</span><span>*args, **kwargs)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class StreamingBase64Parser(DefusedExpatParser):
    &#34;&#34;&#34;A SAX parser that returns a generator of base64-decoded character content.&#34;&#34;&#34;

    def __init__(self, *args, **kwargs):
        DefusedExpatParser.__init__(self, *args, **kwargs)
        self._namespaces = True
        self.buffer = None
        self.element_found = None

    def parse(self, r):
        raw_source = r.raw
        # Like upstream but yields the return value of self.feed()
        raw_source = prepare_input_source(raw_source)
        self.prepareParser(raw_source)
        file = raw_source.getByteStream()
        self.buffer = []
        self.element_found = False
        buffer = file.read(self._bufsize)
        collected_data = []
        while buffer:
            if not self.element_found:
                collected_data.extend(buffer)
            yield from self.feed(buffer)
            buffer = file.read(self._bufsize)
        # Any remaining data in self.buffer should be padding chars now
        self.buffer = None
        self.close()
        if not self.element_found:
            raise ElementNotFound(&#34;The element to be streamed from was not found&#34;, data=bytes(collected_data))

    def feed(self, data, isFinal=0):
        &#34;&#34;&#34;Yield the current content of the character buffer. The input XML may contain illegal characters. The lxml
        parser handles this gracefully with the &#39;recover&#39; option, but ExpatParser doesn&#39;t have this option. Remove
        illegal characters before parsing.&#34;&#34;&#34;
        DefusedExpatParser.feed(self, data=sanitize_xml(data), isFinal=isFinal)
        return self._decode_buffer()

    def _decode_buffer(self):
        remainder = &#34;&#34;
        for data in self.buffer:
            available = len(remainder) + len(data)
            overflow = available % 4  # Make sure we always decode a multiple of 4
            if remainder:
                data = remainder + data
                remainder = &#34;&#34;
            if overflow:
                remainder, data = data[-overflow:], data[:-overflow]
            if data:
                yield b64decode(data)
        self.buffer = [remainder] if remainder else []</code></pre>
</details>
<div class="desc"><p>A SAX parser that returns a generator of base64-decoded character content.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>defusedxml.expatreader.DefusedExpatParser</li>
<li>xml.sax.expatreader.ExpatParser</li>
<li>xml.sax.xmlreader.IncrementalParser</li>
<li>xml.sax.xmlreader.XMLReader</li>
<li>xml.sax.xmlreader.Locator</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.StreamingBase64Parser.feed"><code class="name flex">
<span>def <span class="ident">feed</span></span>(<span>self, data, isFinal=0)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def feed(self, data, isFinal=0):
    &#34;&#34;&#34;Yield the current content of the character buffer. The input XML may contain illegal characters. The lxml
    parser handles this gracefully with the &#39;recover&#39; option, but ExpatParser doesn&#39;t have this option. Remove
    illegal characters before parsing.&#34;&#34;&#34;
    DefusedExpatParser.feed(self, data=sanitize_xml(data), isFinal=isFinal)
    return self._decode_buffer()</code></pre>
</details>
<div class="desc"><p>Yield the current content of the character buffer. The input XML may contain illegal characters. The lxml
parser handles this gracefully with the 'recover' option, but ExpatParser doesn't have this option. Remove
illegal characters before parsing.</p></div>
</dd>
<dt id="exchangelib.util.StreamingBase64Parser.parse"><code class="name flex">
<span>def <span class="ident">parse</span></span>(<span>self, r)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def parse(self, r):
    raw_source = r.raw
    # Like upstream but yields the return value of self.feed()
    raw_source = prepare_input_source(raw_source)
    self.prepareParser(raw_source)
    file = raw_source.getByteStream()
    self.buffer = []
    self.element_found = False
    buffer = file.read(self._bufsize)
    collected_data = []
    while buffer:
        if not self.element_found:
            collected_data.extend(buffer)
        yield from self.feed(buffer)
        buffer = file.read(self._bufsize)
    # Any remaining data in self.buffer should be padding chars now
    self.buffer = None
    self.close()
    if not self.element_found:
        raise ElementNotFound(&#34;The element to be streamed from was not found&#34;, data=bytes(collected_data))</code></pre>
</details>
<div class="desc"><p>Parse an XML document from a URL or an InputSource.</p></div>
</dd>
</dl>
</dd>
<dt id="exchangelib.util.StreamingContentHandler"><code class="flex name class">
<span>class <span class="ident">StreamingContentHandler</span></span>
<span>(</span><span>parser, ns, element_name)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class StreamingContentHandler(xml.sax.handler.ContentHandler):
    &#34;&#34;&#34;A SAX content handler that returns a character data for a single element back to the parser. The parser must have
    a &#39;buffer&#39; attribute we can append data to.
    &#34;&#34;&#34;

    def __init__(self, parser, ns, element_name):
        xml.sax.handler.ContentHandler.__init__(self)
        self._parser = parser
        self._ns = ns
        self._element_name = element_name
        self._parsing = False

    def startElementNS(self, name, qname, attrs):
        if name == (self._ns, self._element_name):
            # we can expect element data next
            self._parsing = True
            self._parser.element_found = True

    def endElementNS(self, name, qname):
        if name == (self._ns, self._element_name):
            # all element data received
            self._parsing = False

    def characters(self, content):
        if not self._parsing:
            return
        self._parser.buffer.append(content)</code></pre>
</details>
<div class="desc"><p>A SAX content handler that returns a character data for a single element back to the parser. The parser must have
a 'buffer' attribute we can append data to.</p></div>
<h3>Ancestors</h3>
<ul class="hlist">
<li>xml.sax.handler.ContentHandler</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="exchangelib.util.StreamingContentHandler.characters"><code class="name flex">
<span>def <span class="ident">characters</span></span>(<span>self, content)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def characters(self, content):
    if not self._parsing:
        return
    self._parser.buffer.append(content)</code></pre>
</details>
<div class="desc"><p>Receive notification of character data.</p>
<p>The Parser will call this method to report each chunk of
character data. SAX parsers may return all contiguous
character data in a single chunk, or they may split it into
several chunks; however, all of the characters in any single
event must come from the same external entity so that the
Locator provides useful information.</p></div>
</dd>
<dt id="exchangelib.util.StreamingContentHandler.endElementNS"><code class="name flex">
<span>def <span class="ident">endElementNS</span></span>(<span>self, name, qname)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def endElementNS(self, name, qname):
    if name == (self._ns, self._element_name):
        # all element data received
        self._parsing = False</code></pre>
</details>
<div class="desc"><p>Signals the end of an element in namespace mode.</p>
<p>The name parameter contains the name of the element type, just
as with the startElementNS event.</p></div>
</dd>
<dt id="exchangelib.util.StreamingContentHandler.startElementNS"><code class="name flex">
<span>def <span class="ident">startElementNS</span></span>(<span>self, name, qname, attrs)</span>
</code></dt>
<dd>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def startElementNS(self, name, qname, attrs):
    if name == (self._ns, self._element_name):
        # we can expect element data next
        self._parsing = True
        self._parser.element_found = True</code></pre>
</details>
<div class="desc"><p>Signals the start of an element in namespace mode.</p>
<p>The name parameter contains the name of the element type as a
(uri, localname) tuple, the qname parameter the raw XML 1.0
name used in the source document, and the attrs parameter
holds an instance of the Attributes class containing the
attributes of the element.</p>
<p>The uri part of the name tuple is None for elements which have
no namespace.</p></div>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="exchangelib" href="index.html">exchangelib</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="exchangelib.util.add_xml_child" href="#exchangelib.util.add_xml_child">add_xml_child</a></code></li>
<li><code><a title="exchangelib.util.chunkify" href="#exchangelib.util.chunkify">chunkify</a></code></li>
<li><code><a title="exchangelib.util.create_element" href="#exchangelib.util.create_element">create_element</a></code></li>
<li><code><a title="exchangelib.util.get_domain" href="#exchangelib.util.get_domain">get_domain</a></code></li>
<li><code><a title="exchangelib.util.get_redirect_url" href="#exchangelib.util.get_redirect_url">get_redirect_url</a></code></li>
<li><code><a title="exchangelib.util.get_xml_attr" href="#exchangelib.util.get_xml_attr">get_xml_attr</a></code></li>
<li><code><a title="exchangelib.util.get_xml_attrs" href="#exchangelib.util.get_xml_attrs">get_xml_attrs</a></code></li>
<li><code><a title="exchangelib.util.is_iterable" href="#exchangelib.util.is_iterable">is_iterable</a></code></li>
<li><code><a title="exchangelib.util.is_xml" href="#exchangelib.util.is_xml">is_xml</a></code></li>
<li><code><a title="exchangelib.util.peek" href="#exchangelib.util.peek">peek</a></code></li>
<li><code><a title="exchangelib.util.post_ratelimited" href="#exchangelib.util.post_ratelimited">post_ratelimited</a></code></li>
<li><code><a title="exchangelib.util.prepare_input_source" href="#exchangelib.util.prepare_input_source">prepare_input_source</a></code></li>
<li><code><a title="exchangelib.util.require_account" href="#exchangelib.util.require_account">require_account</a></code></li>
<li><code><a title="exchangelib.util.require_id" href="#exchangelib.util.require_id">require_id</a></code></li>
<li><code><a title="exchangelib.util.safe_b64decode" href="#exchangelib.util.safe_b64decode">safe_b64decode</a></code></li>
<li><code><a title="exchangelib.util.safe_xml_value" href="#exchangelib.util.safe_xml_value">safe_xml_value</a></code></li>
<li><code><a title="exchangelib.util.sanitize_xml" href="#exchangelib.util.sanitize_xml">sanitize_xml</a></code></li>
<li><code><a title="exchangelib.util.set_xml_value" href="#exchangelib.util.set_xml_value">set_xml_value</a></code></li>
<li><code><a title="exchangelib.util.split_url" href="#exchangelib.util.split_url">split_url</a></code></li>
<li><code><a title="exchangelib.util.to_xml" href="#exchangelib.util.to_xml">to_xml</a></code></li>
<li><code><a title="exchangelib.util.value_to_xml_text" href="#exchangelib.util.value_to_xml_text">value_to_xml_text</a></code></li>
<li><code><a title="exchangelib.util.xml_text_to_value" href="#exchangelib.util.xml_text_to_value">xml_text_to_value</a></code></li>
<li><code><a title="exchangelib.util.xml_to_str" href="#exchangelib.util.xml_to_str">xml_to_str</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="exchangelib.util.AnonymizingXmlHandler" href="#exchangelib.util.AnonymizingXmlHandler">AnonymizingXmlHandler</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.AnonymizingXmlHandler.PRIVATE_TAGS" href="#exchangelib.util.AnonymizingXmlHandler.PRIVATE_TAGS">PRIVATE_TAGS</a></code></li>
<li><code><a title="exchangelib.util.AnonymizingXmlHandler.parse_bytes" href="#exchangelib.util.AnonymizingXmlHandler.parse_bytes">parse_bytes</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="exchangelib.util.BytesGeneratorIO" href="#exchangelib.util.BytesGeneratorIO">BytesGeneratorIO</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.BytesGeneratorIO.close" href="#exchangelib.util.BytesGeneratorIO.close">close</a></code></li>
<li><code><a title="exchangelib.util.BytesGeneratorIO.read" href="#exchangelib.util.BytesGeneratorIO.read">read</a></code></li>
<li><code><a title="exchangelib.util.BytesGeneratorIO.readable" href="#exchangelib.util.BytesGeneratorIO.readable">readable</a></code></li>
<li><code><a title="exchangelib.util.BytesGeneratorIO.tell" href="#exchangelib.util.BytesGeneratorIO.tell">tell</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="exchangelib.util.DocumentYielder" href="#exchangelib.util.DocumentYielder">DocumentYielder</a></code></h4>
</li>
<li>
<h4><code><a title="exchangelib.util.DummyRequest" href="#exchangelib.util.DummyRequest">DummyRequest</a></code></h4>
</li>
<li>
<h4><code><a title="exchangelib.util.DummyResponse" href="#exchangelib.util.DummyResponse">DummyResponse</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.DummyResponse.close" href="#exchangelib.util.DummyResponse.close">close</a></code></li>
<li><code><a title="exchangelib.util.DummyResponse.iter_content" href="#exchangelib.util.DummyResponse.iter_content">iter_content</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="exchangelib.util.ElementNotFound" href="#exchangelib.util.ElementNotFound">ElementNotFound</a></code></h4>
</li>
<li>
<h4><code><a title="exchangelib.util.ParseError" href="#exchangelib.util.ParseError">ParseError</a></code></h4>
</li>
<li>
<h4><code><a title="exchangelib.util.PrettyXmlHandler" href="#exchangelib.util.PrettyXmlHandler">PrettyXmlHandler</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.PrettyXmlHandler.emit" href="#exchangelib.util.PrettyXmlHandler.emit">emit</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.highlight_xml" href="#exchangelib.util.PrettyXmlHandler.highlight_xml">highlight_xml</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.is_tty" href="#exchangelib.util.PrettyXmlHandler.is_tty">is_tty</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.parse_bytes" href="#exchangelib.util.PrettyXmlHandler.parse_bytes">parse_bytes</a></code></li>
<li><code><a title="exchangelib.util.PrettyXmlHandler.prettify_xml" href="#exchangelib.util.PrettyXmlHandler.prettify_xml">prettify_xml</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="exchangelib.util.StreamingBase64Parser" href="#exchangelib.util.StreamingBase64Parser">StreamingBase64Parser</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.StreamingBase64Parser.feed" href="#exchangelib.util.StreamingBase64Parser.feed">feed</a></code></li>
<li><code><a title="exchangelib.util.StreamingBase64Parser.parse" href="#exchangelib.util.StreamingBase64Parser.parse">parse</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="exchangelib.util.StreamingContentHandler" href="#exchangelib.util.StreamingContentHandler">StreamingContentHandler</a></code></h4>
<ul class="">
<li><code><a title="exchangelib.util.StreamingContentHandler.characters" href="#exchangelib.util.StreamingContentHandler.characters">characters</a></code></li>
<li><code><a title="exchangelib.util.StreamingContentHandler.endElementNS" href="#exchangelib.util.StreamingContentHandler.endElementNS">endElementNS</a></code></li>
<li><code><a title="exchangelib.util.StreamingContentHandler.startElementNS" href="#exchangelib.util.StreamingContentHandler.startElementNS">startElementNS</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.11.6</a>.</p>
</footer>
</body>
</html>