Skip to content
Permalink
Browse files

add function open_html_form to create a form on a notebook

  • Loading branch information...
sdpython committed Nov 15, 2014
1 parent d69ec8f commit 604760cbf65f5e85628c2fe237c5203ccefcc696
@@ -50,6 +50,7 @@ Versions
* **add:** function to remove extra spaces in a file :func:`remove_extra_spaces <pyquickhelper.pycode.code_helper.remove_extra_spaces>`
* **add:** function :func:`create_visual_diff_through_html_files <pyquickhelper.sync.visual_sync.create_visual_diff_through_html_files>`
* **fix:** the setup does not need the file ``README.rst`` anymore
* **add:** function :func:`open_html_form <pyquickhelper.ipythonhelper.html_forms.open_html_form>`
* **0.8 - 2014/11/03**
* **add:** Python version is now checked, ImportError is raised if it used on Python 2
* **new:** function :func:`run_doc_server <pyquickhelper.serverdoc.documentation_server.run_doc_server>` creates a local server to display documentation
@@ -0,0 +1,256 @@
{
"metadata": {
"name": "",
"signature": "sha256:c0efe7a7353a6d9d312280809fabcc9572a080bb281aab025a7000b7e6c38682"
},
"nbformat": 3,
"nbformat_minor": 0,
"worksheets": [
{
"cells": [
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Having a form in a notebook"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This following trick is inspired from [IPython Notebook: Javascript/Python Bi-directional Communication](https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/). The code is copy pasted below."
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from IPython.display import HTML\n",
"\n",
"input_form = \"\"\"\n",
"<div style=\"background-color:gainsboro; width:300px; padding:20px;\">\n",
"Variable Name: <input type=\"text\" id=\"var_name\" value=\"foo\"><br>\n",
"Variable Value: <input type=\"text\" id=\"var_value\" value=\"bar\"><br>\n",
"<button onclick=\"set_value()\">Set Value</button>\n",
"</div>\n",
"\"\"\"\n",
"\n",
"javascript = \"\"\"\n",
"<script type=\"text/Javascript\">\n",
" function set_value(){\n",
" var var_name = document.getElementById('var_name').value;\n",
" var var_value = document.getElementById('var_value').value;\n",
" var command = var_name + \" = '\" + var_value + \"'\";\n",
" console.log(\"Executing Command: \" + command);\n",
" \n",
" var kernel = IPython.notebook.kernel;\n",
" kernel.execute(command);\n",
" }\n",
"</script>\n",
"\"\"\"\n",
"\n",
"HTML(input_form + javascript)"
],
"language": "python",
"metadata": {},
"outputs": [
{
"html": [
"\n",
"<div style=\"background-color:gainsboro; width:300px; padding:20px;\">\n",
"Variable Name: <input type=\"text\" id=\"var_name\" value=\"foo\"><br>\n",
"Variable Value: <input type=\"text\" id=\"var_value\" value=\"bar\"><br>\n",
"<button onclick=\"set_value()\">Set Value</button>\n",
"</div>\n",
"\n",
"<script type=\"text/Javascript\">\n",
" function set_value(){\n",
" var var_name = document.getElementById('var_name').value;\n",
" var var_value = document.getElementById('var_value').value;\n",
" var command = var_name + \" = '\" + var_value + \"'\";\n",
" console.log(\"Executing Command: \" + command);\n",
" \n",
" var kernel = IPython.notebook.kernel;\n",
" kernel.execute(command);\n",
" }\n",
"</script>\n"
],
"metadata": {},
"output_type": "pyout",
"prompt_number": 2,
"text": [
"<IPython.core.display.HTML at 0x7a84bd0>"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"myvar"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 4,
"text": [
"'changed from bar'"
]
}
],
"prompt_number": 4
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we try to get something like this:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from pyquickhelper import open_html_form\n",
"params= {\"module\":\"\", \"version\":\"v...\"}\n",
"open_html_form(params, \"fill the fields\", \"form1\")"
],
"language": "python",
"metadata": {},
"outputs": [
{
"html": [
"<div style=\"background-color:gainsboro; width:600px; padding:10px;\">fill the fields <table border=\"0\">\n",
"<td><td>module</td><td><input type=\"text\" id=\"form1module\" value=\"\" /></td></tr>\n",
"<td><td>version</td><td><input type=\"text\" id=\"form1version\" value=\"v...\" /></td></tr>\n",
"</table><button onclick=\"set_valueform1()\">Ok</button></div>\n",
"<script type=\"text/Javascript\">\n",
"function set_valueform1(){\n",
" command='form1 = {' ;\n",
" var form1modulevar_value = document.getElementById('form1module').value;\n",
" command += '\"module\":\"' + form1modulevar_value + '\",';\n",
" var form1versionvar_value = document.getElementById('form1version').value;\n",
" command += '\"version\":\"' + form1versionvar_value + '\",';\n",
" command += '}';\n",
" var kernel = IPython.notebook.kernel;\n",
" kernel.execute(command);\n",
"}\n",
"</script>"
],
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"<IPython.core.display.HTML at 0x802a990>"
]
}
],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"form1"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 2,
"text": [
"{'module': 'version1', 'version': 'version2'}"
]
}
],
"prompt_number": 2
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With a password:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"from pyquickhelper import open_html_form\n",
"params= {\"login\":\"\", \"password\":\"\"}\n",
"open_html_form(params, \"credential\", \"credential\")"
],
"language": "python",
"metadata": {},
"outputs": [
{
"html": [
"<div style=\"background-color:gainsboro; width:600px; padding:10px;\">credential <table border=\"0\">\n",
"<td><td>login</td><td><input type=\"text\" id=\"credentiallogin\" value=\"\" /></td></tr>\n",
"<td><td>password</td><td><input type=\"password\" id=\"credentialpassword\" value=\"\" /></td></tr>\n",
"</table><button onclick=\"set_valuecredential()\">Ok</button></div>\n",
"<script type=\"text/Javascript\">\n",
"function set_valuecredential(){\n",
" command='credential = {' ;\n",
" var credentialloginvar_value = document.getElementById('credentiallogin').value;\n",
" command += '\"login\":\"' + credentialloginvar_value + '\",';\n",
" var credentialpasswordvar_value = document.getElementById('credentialpassword').value;\n",
" command += '\"password\":\"' + credentialpasswordvar_value + '\",';\n",
" command += '}';\n",
" var kernel = IPython.notebook.kernel;\n",
" kernel.execute(command);\n",
"}\n",
"</script>"
],
"metadata": {},
"output_type": "pyout",
"prompt_number": 1,
"text": [
"<IPython.core.display.HTML at 0x7503930>"
]
}
],
"prompt_number": 1
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"credential"
],
"language": "python",
"metadata": {},
"outputs": [
{
"metadata": {},
"output_type": "pyout",
"prompt_number": 2,
"text": [
"{'login': 'admin', 'password': 'hiddenpassword'}"
]
}
],
"prompt_number": 2
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}
}
]
}
@@ -12,7 +12,8 @@
if path not in sys.path : sys.path.append (path)
import src

from src.pyquickhelper import AutoCompletion, fLOG, AutoCompletionFile
from src.pyquickhelper import AutoCompletion, fLOG, AutoCompletionFile, open_html_form



class TestAutoCompletion (unittest.TestCase):
@@ -41,6 +42,14 @@ def test_completion_file(self):
l = len(this)
assert l > 30

def test_html_form(self):
fLOG (__file__, self._testMethodName, OutputPrint = __name__ == "__main__")
params = {"parA":"valueA", "parB":"valueB"}
title = 'unit_test_title'
key_save = 'jjj'
raw = open_html_form(params, title, key_save, raw=True)
fLOG(raw)
assert len(raw) > 0



@@ -51,7 +51,7 @@
subversion = 1

project_var_name = "pyquickhelper"
sversion = "0.8"
sversion = "0.9"
versionPython = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
path = "Lib/site-packages/" + project_var_name
readme = 'README.rst'
@@ -7,7 +7,7 @@
if sys.version_info[0] < 3 :
raise ImportError("pyquickhelper only works with Python 3")

__version__ = "0.8"
__version__ = "0.9"
__author__ = "Xavier Dupré"
__github__ = "https://github.com/sdpython/pyquickhelper"
__url__ = "http://www.xavierdupre.fr/app/pyquickhelper/helpsphinx/index.html"
@@ -42,4 +42,5 @@ def check():
from .ipythonhelper.kindofcompletion import AutoCompletion, AutoCompletionFile
from .sync.visual_sync import create_visual_diff_through_html, create_visual_diff_through_html_files
from .serverdoc.documentation_server import run_doc_server
from .pycode.code_helper import remove_extra_spaces, remove_extra_spaces_folder
from .pycode.code_helper import remove_extra_spaces, remove_extra_spaces_folder
from .ipythonhelper.html_forms import open_html_form
@@ -0,0 +1,60 @@
"""
@file
@brief Some functions to interact better with Notebook
"""

import os

def open_html_form (params,
title='',
key_save = "",
style="background-color:gainsboro; width:600px; padding:10px;",
raw = False):
"""
the function displays a form onto a notebook,
it requires a notebook to be open
@param params dictionary of parameters
@param title titre of the added box
@param style style of the form
@param key_save name of the variable to add to the notebook (as a dictionary)
@param raw returns the raw HTML and not ``HTML( text )``
@return HTML
The code comes from
`IPython Notebook: Javascript/Python Bi-directional Communication <https://jakevdp.github.io/blog/2013/06/01/ipython-notebook-javascript-python-communication/>`_.
When the notebook is converted into a HTML document, the values in the form do not appear.
This behaviour is expected in case one of the field contains a password.
.. versionadded:: 0.9
"""

row = """<td><td>{0}</td><td><input type="{3}" id="{2}{0}" value="{1}" /></td></tr>"""

rows = [ """<div style="{0}">{1} <table border="0">""".format(style, title, key_save) ]
for k,v in sorted(params.items()):
if k.startswith("password") : typ = "password"
else: typ = "text"
rows.append ( row.format(k, "" if v is None else str(v), key_save, typ ) )
rows.append( """</table><button onclick="set_value{0}()">Ok</button></div>""".format(key_save) )

rows.append("""<script type="text/Javascript">""")
rows.append("function set_value__KEY__(){".replace("__KEY__",key_save))

rows.append(" command='%s = {' ;" % key_save)
for k,v in sorted(params.items()):
rows.append( """ var {0}{1}var_value = document.getElementById('{0}{1}').value;""".format(key_save,k) )
rows.append( """ command += '"{0}":"' + """.format(k) + "{0}{1}var_value".format(key_save,k) + """ + '",';""" )
rows.append(""" command += '}';""")
rows.append(""" var kernel = IPython.notebook.kernel;""")
rows.append(""" kernel.execute(command);""")
rows.append("""}""")
rows.append("</script>")

text = "\n".join(rows)

if raw :
return text
else :
from IPython.display import HTML
return HTML(text)

0 comments on commit 604760c

Please sign in to comment.
You can’t perform that action at this time.