Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" 

2@file 

3@brief Some functions to interact better with Notebook 

4""" 

5 

6import re 

7 

8_reg_var = re.compile("^[a-zA-Z_]([a-zA-Z_0-9]*)$") 

9 

10 

11def open_html_form(params, title='', key_save="", 

12 style="background-color:gainsboro; padding:2px; border:0px;", 

13 raw=False, hook=None): 

14 """ 

15 The function displays a form onto a notebook, 

16 it requires a notebook to be open. 

17 

18 @param params dictionary of parameters (see comment below) 

19 @param title titre of the added box 

20 @param style style of the form 

21 @param key_save name of the variable to add to the notebook (as a dictionary) 

22 @param raw returns the raw HTML and not ``HTML( text )`` 

23 @param hook an instruction as a string which will be executed if the button is clicked (None for none) 

24 @return HTML 

25 

26 The code comes from 

27 `IPython Notebook: Javascript/Python Bi-directional Communication 

28 <https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/>`_. 

29 When the notebook is converted into a HTML document, the values in the form do not appear. 

30 This behaviour is expected in case one of the field contains a password. On a notebook, it 

31 gives the following result: 

32 

33 .. exref:: 

34 :title: Open a add a form in a notebook to ask parameters to a user 

35 

36 .. image:: images/form.png 

37 

38 Cell 1:: 

39 

40 from pyquickhelper.ipythonhelper import open_html_form 

41 params = { "module":, "version":"v..." } 

42 open_html_form (params, title="try the password *", key_save="form1") 

43 

44 Cell 2:: 

45 

46 print(form1) 

47 

48 We can execute a simple action after the button *Ok* is pressed. This second trick 

49 comes from `this notebook <https://raw.githubusercontent.com/fluxtream/fluxtream-ipy/master/ 

50 Communication%20between%20kernel%20and%20javascript%20in%20iPython%202.0.ipynb>`_. 

51 The code displays whatever comes from function ``custom_action`` in this case. 

52 You should return ``""`` to display nothing. 

53 

54 :: 

55 

56 def custom_action(x): 

57 x["combined"] = x["first_name"] + " " + x["last_name"] 

58 return x 

59 

60 params = { "first_name":"", "last_name":"" } 

61 open_html_form(params, title="enter your name", key_save="my_address", 

62 hook="custom_action(my_address)") 

63 

64 The function generates javascript based on the keys the dictionary ``params`` contains. 

65 The keys must follows the same as a javascript identifier (no space). 

66 """ 

67 global _reg_var 

68 for k in params: 

69 if not _reg_var.match(k): 

70 raise KeyError( # pragma: no cover 

71 "keys in params must look like a variable, it is not the case for " 

72 "'{}'.".format(k)) 

73 

74 row = """<br />{0} <input type="{3}" id="{2}{0}" value="{1}" size="80" />""" 

75 

76 rows = ["""<div style="{0}"><b>{1}</b>""".format(style, title)] 

77 for k, v in sorted(params.items()): 

78 if k.startswith("password"): 

79 typ = "password" 

80 else: 

81 typ = "text" 

82 rows.append(row.format(k, "" if v is None else str(v), key_save, typ)) 

83 rows.append( 

84 """<br /><button onclick="set_value{0}()">Ok</button></div>""".format(key_save)) 

85 if hook is not None: 

86 rows.append("<div id='out%s'></div>" % key_save.replace("_", "")) 

87 

88 rows.append("""<script type="text/Javascript">""") 

89 rows.append("function %scallback(msg) {" % key_save) 

90 rows.append(" var ret = msg.content.data['text/plain'];") 

91 rows.append(" $('#out%s').text(ret);" % key_save.replace("_", "")) 

92 rows.append("}") 

93 rows.append("function set_value__KEY__(){".replace("__KEY__", key_save)) 

94 

95 rows.append(" command='%s = {' ;" % key_save) 

96 for k, v in sorted(params.items()): 

97 rows.append( 

98 """ var {0}{1}var_value = document.getElementById('{0}{1}').value;""".format(key_save, k)) 

99 rows.append(""" command += '"{0}":"' + """.format(k) + 

100 "{0}{1}var_value".format(key_save, k) + """ + '",';""") 

101 rows.append(""" command += '}';""") 

102 rows.append(""" var kernel = IPython.notebook.kernel;""") 

103 rows.append(""" kernel.execute(command);""") 

104 if hook is not None: 

105 rows.append(""" kernel.execute('%s', {iopub: {output: %scallback}}, {silent: false});""" % ( 

106 hook, key_save)) 

107 rows.append("""}""") 

108 rows.append("</script>") 

109 

110 text = "\n".join(rows) 

111 

112 if raw: 

113 return text 

114 from IPython.display import HTML # pragma: no cover 

115 return HTML(text) # pragma: no cover