本文整理汇总了Python中contextvars.ContextVar方法的典型用法代码示例。如果您正苦于以下问题:Python contextvars.ContextVar方法的具体用法?Python contextvars.ContextVar怎么用?Python contextvars.ContextVar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类contextvars
的用法示例。
在下文中一共展示了contextvars.ContextVar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _make_threadlocal_contextvars
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def _make_threadlocal_contextvars(local):
# type: (type) -> type
class ContextVar(object):
# Super-limited impl of ContextVar
def __init__(self, name):
# type: (str) -> None
self._name = name
self._local = local()
def get(self, default):
# type: (Any) -> Any
return getattr(self._local, "value", default)
def set(self, value):
# type: (Any) -> None
self._local.value = value
return ContextVar
示例2: reset
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def reset(self, token): # type: (Token) -> None
if token.context_var is not self:
raise ValueError('Token was created by a different ContextVar')
if self._cv_variable is not None:
if not isinstance(token, _ContextVarToken):
raise TypeError('Unexpected `{}` expecting `_ContextVarToken`'.format(token.__class__.__name__))
self._cv_variable.reset(token.token)
elif self._tl_variable is not None:
if not isinstance(token, _ThreadLocalToken):
raise TypeError('Unexpected `{}` expecting `_ThreadLocalToken`'.format(token.__class__.__name__))
if token.previous_value is _NO_DEFAULT:
delattr(self._tl_variable, 'value')
else:
self._tl_variable.value = token.previous_value
else:
raise TypeError('This context var has been internally messed with and is no longer valid.')
示例3: coroutine
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def coroutine(self, coroutine):
create_call_trace.append('SpecialCoroutineMiddleware')
# noinspection PyCompatibility
async def wrapper():
var = contextvars.ContextVar('middleware_var') # type: contextvars.ContextVar[int]
var.set(self.var_value)
run_call_trace_pre.append('SpecialCoroutineMiddleware')
try:
return await coroutine
finally:
run_call_trace_post.append('SpecialCoroutineMiddleware')
return wrapper()
示例4: test_context_var_repr_1
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def test_context_var_repr_1(self):
c = contextvars.ContextVar('a')
self.assertIn('a', repr(c))
c = contextvars.ContextVar('a', default=123)
self.assertIn('123', repr(c))
lst = []
c = contextvars.ContextVar('a', default=lst)
lst.append(c)
self.assertIn('...', repr(c))
self.assertIn('...', repr(lst))
t = c.set(1)
self.assertIn(repr(c), repr(t))
self.assertNotIn(' used ', repr(t))
c.reset(t)
self.assertIn(' used ', repr(t))
示例5: test_context_getset_3
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def test_context_getset_3(self):
c = contextvars.ContextVar('c', default=42)
ctx = contextvars.Context()
def fun():
self.assertEqual(c.get(), 42)
with self.assertRaises(KeyError):
ctx[c]
self.assertIsNone(ctx.get(c))
self.assertEqual(ctx.get(c, 'spam'), 'spam')
self.assertNotIn(c, ctx)
self.assertEqual(list(ctx.keys()), [])
t = c.set(1)
self.assertEqual(list(ctx.keys()), [c])
self.assertEqual(ctx[c], 1)
c.reset(t)
self.assertEqual(list(ctx.keys()), [])
with self.assertRaises(KeyError):
ctx[c]
ctx.run(fun)
示例6: test_context_copy_1
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def test_context_copy_1(self):
ctx1 = contextvars.Context()
c = contextvars.ContextVar('c', default=42)
def ctx1_fun():
c.set(10)
ctx2 = ctx1.copy()
self.assertEqual(ctx2[c], 10)
c.set(20)
self.assertEqual(ctx1[c], 20)
self.assertEqual(ctx2[c], 10)
ctx2.run(ctx2_fun)
self.assertEqual(ctx1[c], 20)
self.assertEqual(ctx2[c], 30)
def ctx2_fun():
self.assertEqual(c.get(), 10)
c.set(30)
self.assertEqual(c.get(), 30)
ctx1.run(ctx1_fun)
示例7: test_context_threads_1
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def test_context_threads_1(self):
cvar = contextvars.ContextVar('cvar')
def sub(num):
for i in range(10):
cvar.set(num + i)
time.sleep(random.uniform(0.001, 0.05))
self.assertEqual(cvar.get(), num + i)
return num
tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)
try:
results = list(tp.map(sub, range(10)))
finally:
tp.shutdown()
self.assertEqual(results, list(range(10)))
# HAMT Tests
示例8: __init__
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def __init__(self, peer: Peer):
self._cached_funcs = {}
self.peer = peer
self.order_key = ContextVar('order_key', default=None)
示例9: test_contextvars
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def test_contextvars(self):
from contextvars import ContextVar
var = ContextVar('var')
var.set(0)
async def set_val():
var.set(42)
async def coro():
await set_val()
await asyncio.sleep(0.01)
return var.get()
result = self.loop.run_until_complete(coro())
self.assertEqual(result, 42)
示例10: _is_contextvars_broken
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def _is_contextvars_broken():
# type: () -> bool
"""
Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars.
"""
try:
from gevent.monkey import is_object_patched # type: ignore
if is_object_patched("threading", "local"):
# Gevent 20.5 is able to patch both thread locals and contextvars,
# in that case all is good.
if is_object_patched("contextvars", "ContextVar"):
return False
return True
except ImportError:
pass
try:
from eventlet.patcher import is_monkey_patched # type: ignore
if is_monkey_patched("thread"):
return True
except ImportError:
pass
return False
示例11: _get_contextvars
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def _get_contextvars():
# type: () -> Tuple[bool, type]
"""
Figure out the "right" contextvars installation to use. Returns a
`contextvars.ContextVar`-like class with a limited API.
See https://docs.sentry.io/platforms/python/contextvars/ for more information.
"""
if not _is_contextvars_broken():
# aiocontextvars is a PyPI package that ensures that the contextvars
# backport (also a PyPI package) works with asyncio under Python 3.6
#
# Import it if available.
if sys.version_info < (3, 7):
# `aiocontextvars` is absolutely required for functional
# contextvars on Python 3.6.
try:
from aiocontextvars import ContextVar # noqa
return True, ContextVar
except ImportError:
pass
else:
# On Python 3.7 contextvars are functional.
try:
from contextvars import ContextVar
return True, ContextVar
except ImportError:
pass
# Fall back to basic thread-local usage.
from threading import local
return False, _make_threadlocal_contextvars(local)
示例12: __init__
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def __init__(self, name):
"""Initialize a StackVar."""
self.var = ContextVar(name, default=(None, None))
self.var.set((None, None))
示例13: __init__
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def __init__(self) -> None:
self._current_context = ContextVar(
self._CONTEXT_KEY, default=Context()
)
示例14: __init_subclass__
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def __init_subclass__(cls, **kwargs):
cls.__context_instance = contextvars.ContextVar(
"instance_" + (kwargs.get("ctx_name") or cls.__name__)
)
return cls
示例15: __init__
# 需要导入模块: import contextvars [as 别名]
# 或者: from contextvars import ContextVar [as 别名]
def __init__(self, name, default):
self.name = name
self.contextvar = contextvars.ContextVar(name)
self.default = default if callable(default) else (lambda: default)