doc_demo.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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):
  19. with use_scope(scope):
  20. exec(code, globals())
  21. IMPORT_CODE = """from pywebio.input import *
  22. from pywebio.output import *
  23. from pywebio.session import *
  24. """
  25. def copytoclipboard(code):
  26. run_js("writeText(text)", text=code)
  27. toast('已复制')
  28. def handle_code(code, title):
  29. run_js("""
  30. window.writeText = function(text) {
  31. const input = document.createElement('INPUT');
  32. input.style.opacity = 0;
  33. input.style.position = 'absolute';
  34. input.style.left = '-100000px';
  35. document.body.appendChild(input);
  36. input.value = text;
  37. input.select();
  38. input.setSelectionRange(0, text.length);
  39. document.execCommand('copy');
  40. document.body.removeChild(input);
  41. return true;
  42. }
  43. """)
  44. if title:
  45. put_markdown('## %s' % title)
  46. for p in gen_snippets(code):
  47. with use_scope() as scope:
  48. put_code(p, 'python')
  49. put_buttons(['运行', '复制代码'], onclick=[
  50. partial(run_code, code=p, scope=scope),
  51. partial(copytoclipboard, code=IMPORT_CODE + p)
  52. ])
  53. put_markdown('----')
  54. hold()
  55. def get_app():
  56. app = {}
  57. try:
  58. demos = listdir(path.join(here_dir, 'doc_domes'))
  59. except Exception:
  60. demos = []
  61. demo_infos = []
  62. for name in demos:
  63. code = open(path.join(here_dir, 'doc_domes', name)).read()
  64. title, code = code.split('\n\n', 1)
  65. app[name] = partial(handle_code, code=code, title=title)
  66. demo_infos.append([name, title])
  67. index_html = "<ul>"
  68. for name, title in demo_infos:
  69. index_html += '''<li> <a href="javascript:WebIO.openApp('{name}', true)">{name}</a>: {desc} </li>\n'''.format(
  70. name=name, desc=title)
  71. index_html += "</ul>"
  72. def index():
  73. put_markdown('# PyWebIO Document Code Example Index')
  74. put_html(index_html)
  75. app['index'] = index
  76. return app
  77. if __name__ == '__main__':
  78. start_server(get_app(), debug=True, port=8080)