doc_demo.py 2.9 KB

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