doc_demo.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """
  2. 文档中示例代码在线运行
  3. Run the example code in the documentation online
  4. """
  5. from pywebio import start_server
  6. from pywebio.input import *
  7. from pywebio.output import *
  8. from pywebio.session import *
  9. from pywebio.session import info as session_info # for demo of `pywebio.session.info`
  10. from os import path, listdir
  11. from functools import partial
  12. from pywebio.platform import seo
  13. def t(eng, chinese):
  14. """return English or Chinese text according to the user's browser language"""
  15. return chinese if 'zh' in get_info().user_language else eng
  16. here_dir = path.dirname(path.abspath(__file__))
  17. def gen_snippets(code):
  18. code = code.replace('# ..demo-only', '')
  19. code = '\n'.join(i for i in code.splitlines() if '# ..doc-only' not in i)
  20. parts = code.split('\n## ----\n')
  21. for p in parts:
  22. yield p.strip('\n')
  23. def run_code(code, scope, locals):
  24. with use_scope(scope):
  25. try:
  26. exec(code, globals(), locals)
  27. except Exception as e:
  28. toast('Exception occurred: "%s:%s"' % (type(e).__name__, e), color='error')
  29. IMPORT_CODE = """from pywebio.input import *
  30. from pywebio.output import *
  31. from pywebio.session import *
  32. """
  33. def copytoclipboard(code):
  34. code = IMPORT_CODE + code
  35. if 'put_buttons(' in code or 'put_file(' in code:
  36. code += '\n\nhold() # keep session alive'
  37. run_js("writeText(text)", text=code)
  38. toast('The code has been copied to the clipboard')
  39. def handle_code(code, title):
  40. run_js("""
  41. window.writeText = function(text) {
  42. const input = document.createElement('textarea');
  43. input.style.opacity = 0;
  44. input.style.position = 'absolute';
  45. input.style.left = '-100000px';
  46. document.body.appendChild(input);
  47. input.value = text;
  48. input.select();
  49. input.setSelectionRange(0, text.length);
  50. document.execCommand('copy');
  51. document.body.removeChild(input);
  52. return true;
  53. }
  54. """)
  55. locals = {}
  56. if title:
  57. put_markdown('## %s' % title)
  58. for p in gen_snippets(code):
  59. with use_scope() as scope:
  60. put_code(p, 'python')
  61. put_buttons([t('Run', '运行'), t("Copy to clipboard", '复制代码')], onclick=[
  62. partial(run_code, code=p, scope=scope, locals=locals),
  63. partial(copytoclipboard, code=p)
  64. ])
  65. put_markdown('----')
  66. hold()
  67. def get_app():
  68. """PyWebIO demos from document
  69. Run the demos from the document online.
  70. """
  71. app = {}
  72. try:
  73. demos = listdir(path.join(here_dir, 'doc_demos'))
  74. except Exception:
  75. demos = []
  76. for name in demos:
  77. code = open(path.join(here_dir, 'doc_demos', name)).read()
  78. title, code = code.split('\n\n', 1)
  79. app[name] = partial(handle_code, code=code, title=title)
  80. app[name] = seo('', title, app[name])
  81. return app
  82. if __name__ == '__main__':
  83. a = get_app()
  84. start_server(get_app(), debug=True, port=8080, cdn=False)