-
-
Notifications
You must be signed in to change notification settings - Fork 224
Expand file tree
/
Copy pathcontextvars.po
More file actions
601 lines (537 loc) · 22 KB
/
contextvars.po
File metadata and controls
601 lines (537 loc) · 22 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
# Copyright (C) 2001 Python Software Foundation
# This file is distributed under the same license as the Python package.
msgid ""
msgstr ""
"Project-Id-Version: Python 3.14\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-01-28 00:16+0000\n"
"PO-Revision-Date: 2025-07-30 22:06+0800\n"
"Last-Translator: \n"
"Language-Team: Chinese - TAIWAN (https://github.com/python/python-docs-zh-"
"tw)\n"
"Language: zh_TW\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 3.6\n"
#: ../../library/contextvars.rst:2
msgid ":mod:`!contextvars` --- Context Variables"
msgstr ":mod:`!contextvars` --- 情境變數"
#: ../../library/contextvars.rst:11
msgid ""
"This module provides APIs to manage, store, and access context-local state. "
"The :class:`~contextvars.ContextVar` class is used to declare and work with "
"*Context Variables*. The :func:`~contextvars.copy_context` function and "
"the :class:`~contextvars.Context` class should be used to manage the current "
"context in asynchronous frameworks."
msgstr ""
"本模組供 API 來管理、儲存及存取單一情境各自的狀態(context-local state)。 "
"用 :class:`~contextvars.ContextVar` 類別宣告和處理\\ *情境變數*。 :func:"
"`~contextvars.copy_context` 函式和 :class:`~contextvars.Context` 類別應在非同"
"步框架中管理目前的情境。"
#: ../../library/contextvars.rst:17
msgid ""
"Context managers that have state should use Context Variables instead of :"
"func:`threading.local` to prevent their state from bleeding to other code "
"unexpectedly, when used in concurrent code."
msgstr ""
"帶有狀態的 Context Manager 應該使用情境變數,而不是 :func:`threading.local`,"
"才能防止它們的狀態在並行(concurrent)程式碼中使用時意外外溢並干擾到其他程式"
"碼。"
#: ../../library/contextvars.rst:21
msgid "See also :pep:`567` for additional details."
msgstr "其他詳細資訊,請參閱 :pep:`567`。"
#: ../../library/contextvars.rst:27
msgid "Context Variables"
msgstr "情境變數"
#: ../../library/contextvars.rst:31
msgid "This class is used to declare a new Context Variable, e.g.::"
msgstr "此類別用在宣告新的情境變數,例如:"
#: ../../library/contextvars.rst:33
msgid "var: ContextVar[int] = ContextVar('var', default=42)"
msgstr "var: ContextVar[int] = ContextVar('var', default=42)"
#: ../../library/contextvars.rst:35
msgid ""
"The required *name* parameter is used for introspection and debug purposes."
msgstr "必要參數 *name* 用於自我檢查(introspection)和除錯。"
#: ../../library/contextvars.rst:38
msgid ""
"The optional keyword-only *default* parameter is returned by :meth:"
"`ContextVar.get` when no value for the variable is found in the current "
"context."
msgstr ""
"當在目前的情境中找不到變數的值時,:meth:`ContextVar.get` 會回傳可選的僅限關鍵"
"字參數 *default*。"
#: ../../library/contextvars.rst:42
msgid ""
"**Important:** Context Variables should be created at the top module level "
"and never in closures. :class:`Context` objects hold strong references to "
"context variables which prevents context variables from being properly "
"garbage collected."
msgstr ""
"**重要:**\\ 情境變數應該在最頂端的模組層級建立,絕對不要在閉包(closure)中"
"建立。 :class:`Context` 物件持有情境變數的強參照,這會阻止情境變數被正確地垃"
"圾回收(garbage collected)。"
#: ../../library/contextvars.rst:49
msgid "The name of the variable. This is a read-only property."
msgstr "這個變數的名稱。這是一個唯讀屬性。"
#: ../../library/contextvars.rst:55
msgid "Return a value for the context variable for the current context."
msgstr "回傳目前情境的情境變數值。"
#: ../../library/contextvars.rst:57
msgid ""
"If there is no value for the variable in the current context, the method "
"will:"
msgstr "如果在目前情境中沒有變數的值,此方法將:"
#: ../../library/contextvars.rst:60
msgid ""
"return the value of the *default* argument of the method, if provided; or"
msgstr "回傳方法的 *default* 引數值(如果有的話);否則"
#: ../../library/contextvars.rst:63
msgid ""
"return the default value for the context variable, if it was created with "
"one; or"
msgstr "回傳情境變數的預設值(如果建立情境變數時有指定預設值的話);否則"
#: ../../library/contextvars.rst:66
msgid "raise a :exc:`LookupError`."
msgstr "會引發一個 :exc:`LookupError`。"
#: ../../library/contextvars.rst:70
msgid ""
"Call to set a new value for the context variable in the current context."
msgstr "在目前的情境中,呼叫以設定情境變數的新值。"
#: ../../library/contextvars.rst:73
msgid ""
"The required *value* argument is the new value for the context variable."
msgstr "*value* 屬必要引數,是情境變數的新值。"
#: ../../library/contextvars.rst:76
msgid ""
"Returns a :class:`~contextvars.Token` object that can be used to restore the "
"variable to its previous value via the :meth:`ContextVar.reset` method."
msgstr ""
"回傳一個 :class:`~contextvars.Token` 物件,該物件可透過 :meth:`ContextVar."
"reset` 方法,用來將變數還原到之前的值。"
#: ../../library/contextvars.rst:80
msgid ""
"For convenience, the token object can be used as a context manager to avoid "
"calling :meth:`ContextVar.reset` manually::"
msgstr "為了方便起見,token 物件可以用作情境管理器,以避免手動呼叫 :meth:`ContextVar.reset`: ::"
#: ../../library/contextvars.rst:83
msgid ""
"var = ContextVar('var', default='default value')\n"
"\n"
"with var.set('new value'):\n"
" assert var.get() == 'new value'\n"
"\n"
"assert var.get() == 'default value'"
msgstr ""
"var = ContextVar('var', default='default value')\n"
"\n"
"with var.set('new value'):\n"
" assert var.get() == 'new value'\n"
"\n"
"assert var.get() == 'default value'"
#: ../../library/contextvars.rst:90
msgid "It is a shorthand for::"
msgstr "它是以下程式碼的簡寫: ::"
#: ../../library/contextvars.rst:92
msgid ""
"var = ContextVar('var', default='default value')\n"
"\n"
"token = var.set('new value')\n"
"try:\n"
" assert var.get() == 'new value'\n"
"finally:\n"
" var.reset(token)\n"
"\n"
"assert var.get() == 'default value'"
msgstr ""
"var = ContextVar('var', default='default value')\n"
"\n"
"token = var.set('new value')\n"
"try:\n"
" assert var.get() == 'new value'\n"
"finally:\n"
" var.reset(token)\n"
"\n"
"assert var.get() == 'default value'"
#: ../../library/contextvars.rst:104
msgid "Added support for using tokens as context managers."
msgstr "新增對將 token 用作情境管理器的支援。"
#: ../../library/contextvars.rst:108
msgid ""
"Reset the context variable to the value it had before the :meth:`ContextVar."
"set` that created the *token* was used."
msgstr "將情境變數重設為使用 :meth:`ContextVar.set` 建立 *token* 前的值。"
#: ../../library/contextvars.rst:111
msgid "For example::"
msgstr "舉例來說: ::"
#: ../../library/contextvars.rst:113
msgid ""
"var = ContextVar('var')\n"
"\n"
"token = var.set('new value')\n"
"# code that uses 'var'; var.get() returns 'new value'.\n"
"var.reset(token)\n"
"\n"
"# After the reset call the var has no value again, so\n"
"# var.get() would raise a LookupError."
msgstr ""
"var = ContextVar('var')\n"
"\n"
"token = var.set('new value')\n"
"# 使用 'var' 的程式碼;var.get() 回傳 'new value'。\n"
"var.reset(token)\n"
"\n"
"# 在重設呼叫之後,var 又沒有值了,所以\n"
"# var.get() 會引發 LookupError。"
#: ../../library/contextvars.rst:122
msgid "The same *token* cannot be used twice."
msgstr "同一個 *token* 不能被使用兩次。"
#: ../../library/contextvars.rst:127
msgid ""
"*Token* objects are returned by the :meth:`ContextVar.set` method. They can "
"be passed to the :meth:`ContextVar.reset` method to revert the value of the "
"variable to what it was before the corresponding *set*. A single token "
"cannot reset a context variable more than once."
msgstr ""
"*Token* 物件由 :meth:`ContextVar.set` 方法回傳,可以傳遞給 :meth:`ContextVar."
"reset` 方法,用以將變數的值還原為相對應的 *set* 之前的值。單一 token 不能重設"
"情境變數超過一次。"
#: ../../library/contextvars.rst:132
msgid ""
"Tokens support the :ref:`context manager protocol <context-managers>` to "
"automatically reset context variables. See :meth:`ContextVar.set`."
msgstr ""
"Token 支援\\ :ref:`情境管理器協定 <context-managers>`,可自動重設情境變數。"
"請參閱 :meth:`ContextVar.set`。"
#: ../../library/contextvars.rst:137
msgid "Added support for usage as a context manager."
msgstr "新增對用作情境管理器的支援。"
#: ../../library/contextvars.rst:141
msgid ""
"A read-only property. Points to the :class:`ContextVar` object that created "
"the token."
msgstr "唯讀屬性。 指向建立 token 的 :class:`ContextVar` 物件。"
#: ../../library/contextvars.rst:146
msgid ""
"A read-only property. Set to the value the variable had before the :meth:"
"`ContextVar.set` method call that created the token. It points to :attr:"
"`Token.MISSING` if the variable was not set before the call."
msgstr ""
"唯讀屬性。 值為變數在呼叫 :meth:`ContextVar.set` 方法之前的值。如果變數在呼叫"
"前沒有設定,則指向 :attr:`Token.MISSING`。"
#: ../../library/contextvars.rst:153
msgid "A marker object used by :attr:`Token.old_value`."
msgstr "由 :attr:`Token.old_value` 使用的標記物件。"
#: ../../library/contextvars.rst:157
msgid "Manual Context Management"
msgstr "手動情境管理"
#: ../../library/contextvars.rst:161
msgid "Returns a copy of the current :class:`~contextvars.Context` object."
msgstr "回傳目前 :class:`~contextvars.Context` 物件的複本(copy)。"
#: ../../library/contextvars.rst:163
msgid ""
"The following snippet gets a copy of the current context and prints all "
"variables and their values that are set in it::"
msgstr ""
"以下程式碼片段會取得目前情境的複本,並顯示在其中設定的所有變數及其值:::"
#: ../../library/contextvars.rst:166
msgid ""
"ctx: Context = copy_context()\n"
"print(list(ctx.items()))"
msgstr ""
"ctx: Context = copy_context()\n"
"print(list(ctx.items()))"
#: ../../library/contextvars.rst:169
msgid ""
"The function has an *O*\\ (1) complexity, i.e. works equally fast for "
"contexts with a few context variables and for contexts that have a lot of "
"them."
msgstr ""
"這個函式具有 *O*\\ (1) 的複雜度,也就是說,對於只有少許情境變數的情境和有大量"
"情境變數的情境,速度都一樣快。"
#: ../../library/contextvars.rst:176
msgid "A mapping of :class:`ContextVars <ContextVar>` to their values."
msgstr ":class:`ContextVars<ContextVar>` 到其值的映射。"
#: ../../library/contextvars.rst:178
msgid ""
"``Context()`` creates an empty context with no values in it. To get a copy "
"of the current context use the :func:`~contextvars.copy_context` function."
msgstr ""
"``Context()`` 會建立一個沒有值的空情境。要取得目前情境的複本,請使用 :func:"
"`~contextvars.copy_context` 函式。"
#: ../../library/contextvars.rst:182
msgid ""
"Each thread has its own effective stack of :class:`!Context` objects. The :"
"term:`current context` is the :class:`!Context` object at the top of the "
"current thread's stack. All :class:`!Context` objects in the stacks are "
"considered to be *entered*."
msgstr ""
"每個執行緒都有自己的 :class:`!Context` 物件中目前主控中的堆疊(stack)。:"
"term:`current context` 是目前執行緒堆疊頂端的 :class:`!Context` 物件。 堆疊"
"中的所有 :class:`!Context` 物件都被視為\\ *已進入*。"
#: ../../library/contextvars.rst:187
msgid ""
"*Entering* a context, which can be done by calling its :meth:`~Context.run` "
"method, makes the context the current context by pushing it onto the top of "
"the current thread's context stack."
msgstr ""
"*進入*\\ 一個情境,可以藉由呼叫其 :meth:`~Context.run` 方法來完成,此\\ *進入"
"*\\ 的動作會將一情境推到目前執行緒的情境堆疊的頂端,使該情境成為目前的情境。"
#: ../../library/contextvars.rst:191
msgid ""
"*Exiting* from the current context, which can be done by returning from the "
"callback passed to the :meth:`~Context.run` method, restores the current "
"context to what it was before the context was entered by popping the context "
"off the top of the context stack."
msgstr ""
"如果你傳遞給 :meth:`~Context.run` 方法的回呼函式(callback functions),該函"
"式回傳之後,就會自動\\ *退出*\\ 目前的情境,這會將目前的情境還原到進入情境之"
"前的狀態,方法是將情境從情境堆疊的頂端彈出。"
#: ../../library/contextvars.rst:196
msgid ""
"Since each thread has its own context stack, :class:`ContextVar` objects "
"behave in a similar fashion to :func:`threading.local` when values are "
"assigned in different threads."
msgstr ""
"因為每個執行緒都有自己的情境堆疊,當值在不同的執行緒中被指定時, :class:"
"`ContextVar` 物件的行為與 :func:`threading.local` 相似。"
#: ../../library/contextvars.rst:200
msgid ""
"Attempting to enter an already entered context, including contexts entered "
"in other threads, raises a :exc:`RuntimeError`."
msgstr ""
"嘗試進入已進入的情境,包括在其他執行緒中進入的情境,會引發 :exc:"
"`RuntimeError`。"
#: ../../library/contextvars.rst:203
msgid "After exiting a context, it can later be re-entered (from any thread)."
msgstr "退出情境後,之後可以重新進入(從任何執行緒)。"
#: ../../library/contextvars.rst:205
msgid ""
"Any changes to :class:`ContextVar` values via the :meth:`ContextVar.set` "
"method are recorded in the current context. The :meth:`ContextVar.get` "
"method returns the value associated with the current context. Exiting a "
"context effectively reverts any changes made to context variables while the "
"context was entered (if needed, the values can be restored by re-entering "
"the context)."
msgstr ""
"任何透過 :meth:`ContextVar.set` 方法對 :class:`ContextVar` 值的改變都會記錄在"
"目前的情境中。 :meth:`ContextVar.get` 方法回傳與目前情境相關的值。 退出情境"
"實際造成的效果會像是將其在進入情境時對情境變數所做的任何變一一彈出並還原(如"
"果需要,可以透過重新進入情境來還原值)。"
#: ../../library/contextvars.rst:212
msgid "Context implements the :class:`collections.abc.Mapping` interface."
msgstr "情境(Context)實作了 :class:`collections.abc.Mapping` 介面。"
#: ../../library/contextvars.rst:216
msgid ""
"Enters the Context, executes ``callable(*args, **kwargs)``, then exits the "
"Context. Returns *callable*'s return value, or propagates an exception if "
"one occurred."
msgstr ""
"進入 Context,執行 ``callable(*args, **kwargs)``,然後退出 Context。 回傳 "
"*callable* 的回傳值,如果發生例外(exception),則傳播例外。"
#: ../../library/contextvars.rst:220
msgid "Example:"
msgstr "例如:"
#: ../../library/contextvars.rst:222
msgid ""
"import contextvars\n"
"\n"
"var = contextvars.ContextVar('var')\n"
"var.set('spam')\n"
"print(var.get()) # 'spam'\n"
"\n"
"ctx = contextvars.copy_context()\n"
"\n"
"def main():\n"
" # 'var' was set to 'spam' before\n"
" # calling 'copy_context()' and 'ctx.run(main)', so:\n"
" print(var.get()) # 'spam'\n"
" print(ctx[var]) # 'spam'\n"
"\n"
" var.set('ham')\n"
"\n"
" # Now, after setting 'var' to 'ham':\n"
" print(var.get()) # 'ham'\n"
" print(ctx[var]) # 'ham'\n"
"\n"
"# Any changes that the 'main' function makes to 'var'\n"
"# will be contained in 'ctx'.\n"
"ctx.run(main)\n"
"\n"
"# The 'main()' function was run in the 'ctx' context,\n"
"# so changes to 'var' are contained in it:\n"
"print(ctx[var]) # 'ham'\n"
"\n"
"# However, outside of 'ctx', 'var' is still set to 'spam':\n"
"print(var.get()) # 'spam'"
msgstr ""
"import contextvars\n"
"\n"
"var = contextvars.ContextVar('var')\n"
"var.set('spam')\n"
"print(var.get()) # 'spam'\n"
"\n"
"ctx = contextvars.copy_context()\n"
"\n"
"def main():\n"
" # 'var' 之前被設成 'spam'\n"
" # 呼叫 'copy_context()' 和 'ctx.run(main)',所以:\n"
" print(var.get()) # 'spam'\n"
" print(ctx[var]) # 'spam'\n"
"\n"
" var.set('ham')\n"
"\n"
" # 現在, 在把 'var' 的值設成 'ham' 後:\n"
" print(var.get()) # 'ham'\n"
" print(ctx[var]) # 'ham'\n"
"\n"
"# 'main' 函式對 'var' 所做的任何變更都會\n"
"# 包含在 'ctx 裡:.\n"
"ctx.run(main)\n"
"\n"
"# 'main()' 函式是在 'ctx' 情境中執行,\n"
"# 所以對 'var' 的變更會保存在 'ctx' 中:\n"
"print(ctx[var]) # 'ham'\n"
"\n"
"# 但是,在 'ctx' 外, 'var' 的值仍然是 'spam':\n"
"print(var.get()) # 'spam'"
#: ../../library/contextvars.rst:268
msgid "Return a shallow copy of the context object."
msgstr "回傳情境物件的淺層複本(shallow copy)。"
#: ../../library/contextvars.rst:272
msgid ""
"Return ``True`` if the *context* has a value for *var* set; return ``False`` "
"otherwise."
msgstr ""
"如果\\ *情境*\\ 裡面有 *var* 的值,則回傳 ``True``,否則回傳 ``False``。"
#: ../../library/contextvars.rst:277
msgid ""
"Return the value of the *var* :class:`ContextVar` variable. If the variable "
"is not set in the context object, a :exc:`KeyError` is raised."
msgstr ""
"回傳 *var* :class:`ContextVar` 變數的值。如果該變數並沒有在情境物件中設定,則"
"會引發 :exc:`KeyError` 錯誤。"
#: ../../library/contextvars.rst:283
msgid ""
"Return the value for *var* if *var* has the value in the context object. "
"Return *default* otherwise. If *default* is not given, return ``None``."
msgstr ""
"如果 *var* 的值在情境物件中,則回傳 *var* 的值。否則回傳 *default*。如果沒有 "
"*default* 值,則回傳 ``None``。"
#: ../../library/contextvars.rst:289
msgid "Return an iterator over the variables stored in the context object."
msgstr "回傳儲存於情境物件中變數的疊代器。"
#: ../../library/contextvars.rst:294
msgid "Return the number of variables set in the context object."
msgstr "回傳情境物件中的變數個數。"
#: ../../library/contextvars.rst:298
msgid "Return a list of all variables in the context object."
msgstr "回傳情境物件中所有變數的串列。"
#: ../../library/contextvars.rst:302
msgid "Return a list of all variables' values in the context object."
msgstr "回傳情境物件中所有變數的值的串列。"
#: ../../library/contextvars.rst:307
msgid ""
"Return a list of 2-tuples containing all variables and their values in the "
"context object."
msgstr "回傳情境物件中所有變數與其值的 2-元組(2-tuples)的串列。"
#: ../../library/contextvars.rst:312
msgid "asyncio support"
msgstr "對 asyncio 的支援"
#: ../../library/contextvars.rst:314
msgid ""
"Context variables are natively supported in :mod:`asyncio` and are ready to "
"be used without any extra configuration. For example, here is a simple echo "
"server, that uses a context variable to make the address of a remote client "
"available in the Task that handles that client::"
msgstr ""
":mod:`asyncio` 原生支援情境變數,不需任何額外設定。 舉例來說,以下是一個簡單"
"的 echo 伺服器,使用情境變數讓遠端用戶端的位址在處理該用戶端的任務中可用:"
#: ../../library/contextvars.rst:320
msgid ""
"import asyncio\n"
"import contextvars\n"
"\n"
"client_addr_var = contextvars.ContextVar('client_addr')\n"
"\n"
"def render_goodbye():\n"
" # The address of the currently handled client can be accessed\n"
" # without passing it explicitly to this function.\n"
"\n"
" client_addr = client_addr_var.get()\n"
" return f'Good bye, client @ {client_addr}\\r\\n'.encode()\n"
"\n"
"async def handle_request(reader, writer):\n"
" addr = writer.transport.get_extra_info('socket').getpeername()\n"
" client_addr_var.set(addr)\n"
"\n"
" # In any code that we call is now possible to get\n"
" # client's address by calling 'client_addr_var.get()'.\n"
"\n"
" while True:\n"
" line = await reader.readline()\n"
" print(line)\n"
" if not line.strip():\n"
" break\n"
"\n"
" writer.write(b'HTTP/1.1 200 OK\\r\\n') # status line\n"
" writer.write(b'\\r\\n') # headers\n"
" writer.write(render_goodbye()) # body\n"
" writer.close()\n"
"\n"
"async def main():\n"
" srv = await asyncio.start_server(\n"
" handle_request, '127.0.0.1', 8081)\n"
"\n"
" async with srv:\n"
" await srv.serve_forever()\n"
"\n"
"asyncio.run(main())\n"
"\n"
"# To test it you can use telnet or curl:\n"
"# telnet 127.0.0.1 8081\n"
"# curl 127.0.0.1:8081"
msgstr ""
"import asyncio\n"
"import contextvars\n"
"\n"
"client_addr_var = contextvars.ContextVar('client_addr')\n"
"\n"
"def render_goodbye():\n"
" # 即使不把目前處理中的用戶端(client)傳入此函式\n"
" # 仍可取得其位址\n"
"\n"
" client_addr = client_addr_var.get()\n"
" return f'Good bye, client @ {client_addr}\\r\\n'.encode()\n"
"\n"
"async def handle_request(reader, writer):\n"
" addr = writer.transport.get_extra_info('socket').getpeername()\n"
" client_addr_var.set(addr)\n"
"\n"
" # 在任何我們呼叫的程式碼中,都可以\n"
" # 呼叫 'client_addr_var.get()' 來取得用戶端的位址\n"
"\n"
" while True:\n"
" line = await reader.readline()\n"
" print(line)\n"
" if not line.strip():\n"
" break\n"
"\n"
" writer.write(b'HTTP/1.1 200 OK\\r\\n') # status line\n"
" writer.write(b'\\r\\n') # headers\n"
" writer.write(render_goodbye()) # body\n"
" writer.close()\n"
"\n"
"async def main():\n"
" srv = await asyncio.start_server(\n"
" handle_request, '127.0.0.1', 8081)\n"
"\n"
" async with srv:\n"
" await srv.serve_forever()\n"
"\n"
"asyncio.run(main())\n"
"\n"
"# 你可以使用 telnet 或 curl 測試:\n"
"# telnet 127.0.0.1 8081\n"
"# curl 127.0.0.1:8081"