set_env_demo.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. put_buttons(['返回底部'], [lambda: scroll_to('ROOT', Position.BOTTOM)])
  13. put_markdown('---')
  14. set_scope('time')
  15. put_markdown('---')
  16. async def bg_task():
  17. count = 5
  18. while 1:
  19. with use_scope('time', clear=True):
  20. put_text('当前时间:', datetime.datetime.now())
  21. put_text(count)
  22. count += 1
  23. await asyncio.sleep(1)
  24. put_text('\n'.join(str(i) for i in range(5)))
  25. run_async(bg_task())
  26. state = {
  27. 'title': 'PyWebIO set_env() Demo',
  28. 'output_animation': True,
  29. 'auto_scroll_bottom': True,
  30. 'output_fixed_height': True,
  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('选择要更改的会话环境设置项', list(state.keys()), help_text='当前状态:' + curr_state_info)
  36. if key == 'title':
  37. state['title'] = await input('请输入标题')
  38. set_env(title=state['title'])
  39. toast('已将标题设置为%r' % state['title'])
  40. elif key == 'output_fixed_height':
  41. act = await actions('选择要对output_fixed_height设置项进行的操作', ['设置为False', '自定义高度'])
  42. if act == '自定义高度':
  43. state['output_fixed_height'] = await input('请输入输出区高度(像素)', type=NUMBER)
  44. else:
  45. state['output_fixed_height'] = False
  46. set_env(output_fixed_height=state['output_fixed_height'])
  47. elif key in state:
  48. state[key] = not (state[key])
  49. set_env(**{key: state[key]})
  50. toast('已将`%s`设置为%r' % (key, state[key]))
  51. if __name__ == '__main__':
  52. start_server(main, debug=True, port=8080)