set_env_demo.py 2.0 KB

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