doc_demo.py 2.7 KB

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