doc_demo.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """
  2. 文档中示例代码在线运行
  3. ^^^^^^^^^^^^^^^^
  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. here_dir = path.dirname(path.abspath(__file__))
  12. def gen_snippets(code):
  13. code = code.replace('# ..demo-only', '')
  14. code = '\n'.join(i for i in code.splitlines() if '# ..doc-only' not in i)
  15. parts = code.split('\n## ----\n')
  16. for p in parts:
  17. yield p.strip('\n')
  18. def run_code(code, scope, locals):
  19. with use_scope(scope):
  20. try:
  21. exec(code, globals(), locals)
  22. except Exception as e:
  23. toast('代码产生异常:"%s:%s"' % (type(e).__name__, e), color='error')
  24. IMPORT_CODE = """from pywebio.input import *
  25. from pywebio.output import *
  26. from pywebio.session import *
  27. """
  28. def copytoclipboard(code):
  29. code = IMPORT_CODE + code
  30. if 'put_buttons(' in code or 'put_file(' in code:
  31. code += '\n\nhold() # keep session alive'
  32. run_js("writeText(text)", text=code)
  33. toast('已复制')
  34. def handle_code(code, title):
  35. run_js("""
  36. window.writeText = function(text) {
  37. const input = document.createElement('textarea');
  38. input.style.opacity = 0;
  39. input.style.position = 'absolute';
  40. input.style.left = '-100000px';
  41. document.body.appendChild(input);
  42. input.value = text;
  43. input.select();
  44. input.setSelectionRange(0, text.length);
  45. document.execCommand('copy');
  46. document.body.removeChild(input);
  47. return true;
  48. }
  49. """)
  50. locals = {}
  51. if title:
  52. put_markdown('## %s' % title)
  53. for p in gen_snippets(code):
  54. with use_scope() as scope:
  55. put_code(p, 'python')
  56. put_buttons(['运行', '复制代码'], onclick=[
  57. partial(run_code, code=p, scope=scope, locals=locals),
  58. partial(copytoclipboard, code=p)
  59. ])
  60. put_markdown('----')
  61. hold()
  62. def get_app():
  63. app = {}
  64. try:
  65. demos = listdir(path.join(here_dir, 'doc_demos'))
  66. except Exception:
  67. demos = []
  68. demo_infos = []
  69. for name in demos:
  70. code = open(path.join(here_dir, 'doc_demos', name)).read()
  71. title, code = code.split('\n\n', 1)
  72. app[name] = partial(handle_code, code=code, title=title)
  73. demo_infos.append([name, title])
  74. index_html = "<ul>"
  75. for name, title in demo_infos:
  76. index_html += '''<li> <a href="javascript:WebIO.openApp('{name}', true)">{name}</a>: {desc} </li>\n'''.format(
  77. name=name, desc=title)
  78. index_html += "</ul>"
  79. def index():
  80. put_markdown('# PyWebIO Document Code Example Index')
  81. put_html(index_html)
  82. app['index'] = index
  83. return app
  84. if __name__ == '__main__':
  85. start_server(get_app(), debug=True, port=8080)