set_env_demo.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. async def main():
  12. set_scope('time')
  13. put_markdown('> 可用于观察 `output_animation` 项的动画效果')
  14. put_markdown('---')
  15. async def bg_task():
  16. while 1:
  17. with use_scope('time', clear=True):
  18. put_text('当前时间:', datetime.datetime.now())
  19. await asyncio.sleep(1)
  20. run_async(bg_task())
  21. put_buttons(['输出文本'], [lambda: put_text(datetime.datetime.now())])
  22. put_markdown('> 可用于观察 `auto_scroll_bottom` 项的自动滚动效果')
  23. put_markdown('---')
  24. put_text('Some text.\n' * 10)
  25. state = {
  26. 'title': 'PyWebIO set_env() Demo',
  27. 'output_animation': True,
  28. 'auto_scroll_bottom': True,
  29. 'output_fixed_height': True,
  30. }
  31. set_env(**state)
  32. while 1:
  33. curr_state_info = ', '.join('%s=%r' % (k, v) for k, v in state.items())
  34. key = await actions('选择要更改的会话环境设置项', list(state.keys()), help_text='当前状态:' + curr_state_info)
  35. if key == 'title':
  36. state['title'] = await input('请输入标题', value=state['title'])
  37. set_env(title=state['title'])
  38. toast('已将标题设置为%r' % state['title'])
  39. elif key == 'output_fixed_height':
  40. act = await actions('选择要对output_fixed_height设置项进行的操作', ['设置为False', '自定义高度'])
  41. if act == '自定义高度':
  42. state['output_fixed_height'] = await input('请输入输出区高度(像素)', type=NUMBER)
  43. else:
  44. state['output_fixed_height'] = False
  45. set_env(output_fixed_height=state['output_fixed_height'])
  46. elif key in state:
  47. state[key] = not (state[key])
  48. set_env(**{key: state[key]})
  49. toast('已将`%s`设置为%r' % (key, state[key]))
  50. if __name__ == '__main__':
  51. start_server(main, debug=True, port=8080)