doc_demo.py 2.7 KB

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