set_env_demo.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. `pywebio.session.set_env()` demo
  3. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  4. """
  5. from pywebio import start_server
  6. from pywebio.input import *
  7. from pywebio.output import *
  8. from pywebio.session import *
  9. import datetime
  10. import asyncio
  11. def t(eng, chinese):
  12. """return English or Chinese text according to the user's browser language"""
  13. return chinese if 'zh' in info.user_language else eng
  14. async def main():
  15. """`pywebio.session.set_env()` demo"""
  16. set_scope('time')
  17. put_markdown(t('> Can be used to observe the animation effect of the `output_animation` setting',
  18. '> 可用于观察 `output_animation` 项的动画效果'))
  19. put_markdown('---')
  20. async def bg_task():
  21. while 1:
  22. with use_scope('time', clear=True):
  23. put_text('Current time:', datetime.datetime.now())
  24. await asyncio.sleep(1)
  25. run_async(bg_task())
  26. put_buttons([t('Output some texts', '输出文本')], [lambda: put_text(datetime.datetime.now())])
  27. put_markdown(t('> Can be used to observe the automatic scrolling effect of the `auto_scroll_bottom` setting',
  28. '> 可用于观察 `auto_scroll_bottom` 项的自动滚动效果'))
  29. put_markdown('---')
  30. put_text('Some text.\n' * 10)
  31. state = {
  32. 'title': 'PyWebIO set_env() Demo',
  33. 'output_animation': True,
  34. 'auto_scroll_bottom': False,
  35. }
  36. set_env(**state)
  37. while 1:
  38. curr_state_info = ', '.join('%s=%r' % (k, v) for k, v in state.items())
  39. key = await actions(t('Select the setting item to be changed', '选择要更改的会话环境设置项'), list(state.keys()), help_text='Current state: ' + curr_state_info)
  40. if key == 'title':
  41. state['title'] = await input('Title', value=state['title'])
  42. set_env(title=state['title'])
  43. toast('Title is set to %r' % state['title'])
  44. elif key in state:
  45. state[key] = not (state[key])
  46. set_env(**{key: state[key]})
  47. toast('`%s` is set to %r' % (key, state[key]))
  48. if __name__ == '__main__':
  49. start_server(main, debug=True, port=8080, cdn=False)