Bokeh integration with CSS and jinja - python

I have a bokeh dashboard which needs some custom styling(CSS).
I'm relatively new to the bokeh library and from what I understand, I need to use a jinja2 template wherein I can specify the CSS.
The dashboard has a 4 level hierarchy and the lower level plots only show up on selection at the level above. The hierarchy is as follows-
Dropdown(widget) - This is the only thing shown on first load
Plot 1(shows/updates on change of dropdown)
Plot 2 (shows/updates on selection in plot 1)
Plot 3 (shows/updates on selection in plot 2)
My index.html looks something like:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sales Performance Analysis</title>
<link *CDN Links*>
<script *CDN Links*</script>
{{ script }}
</head>
<body class="bk-body">
<h1>Sales Performance Analysis</h1>
{{ div }}
</body>
</html>
In my main.py, I have the following lines of code at the end to render-
script, div_plot = components(curdoc())
curdoc().template_variables["script"] = script
curdoc().template_variables["div"] = div_plot
When I execute this as a server app (bokeh serve --show folder_name), the browser application shows the dropdown widget but nothing happens on changing the values.
The same thing runs perfectly when run in standalone mode as bokeh serve --show main.py
Would appreciate any kind of pointers.
TIA

You want to use bokeh.embed.server_session instead of bokeh.embed.components (which only statically embed the document)
Here's the reference:
https://docs.bokeh.org/en/latest/docs/user_guide/embed.html#bokeh-applications

Related

Can Bottle's rebase() and include() be made to run from templates in memory?

I can get rebase() and include() to work with templates files on disk using rebase("base_template.tpl"), but am not seeing how to get this to run with templates stored in memory.
Here is my current effort:
from bottle import template
base_template = '''\
<html>
<head>
<title>{{title or 'No title'}}</title>
</head>
<body>
{{!base}}
</body>
</html>
'''
inner_template = '''\
% rebase(base_template, title='Page Title')
<p>Page Content ...</p>
'''
print(template(inner_template, base_template=base_template))
The above code results in a TemplateError.
Looks like it's a known issue with bottle, and this discussion https://github.com/bottlepy/bottle/issues/521 mentions a workaround.
However, no clues if it's working or not with latest version.

How can I run a Python script in HTML?

Currently I have some Python files which connect to an SQLite database for user inputs and then perform some calculations which set the output of the program. I'm new to Python web programming and I want to know: What is the best method to use Python on the web?
Example: I want to run my Python files when the user clicks a button on the web page. Is it possible?
I started with Django. But it needs some time for the learning. And I also saw something called CGI scripts. Which option should I use?
You are able to run a Python file using HTML using PHP.
Add a PHP file as index.php:
<html>
<head>
<title>Run my Python files</title>
<?PHP
echo shell_exec("python test.py 'parameter1'");
?>
</head>
Passing the parameter to Python
Create a Python file as test.py:
import sys
input=sys.argv[1]
print(input)
Print the parameter passed by PHP.
It probably would depend on what you want to do. I personally use CGI and it might be simpler if your inputs from the web page are simple, and it takes less time to learn. Here are some resources for it:
cgi — Common Gateway Interface support
Python - CGI Programming
However, you may still have to do some configuring to allow it to run the program instead of displaying it.
Here's a tutorial on that: Apache Tutorial: Dynamic Content with CGI
If your web server is Apache you can use the
mod_python module in order to run your Python CGI scripts.
For nginx, you can use mod_wsgi.
Thanks to WebAssembly and the Pyodide project, it is now possible to run Python in the browser. Check out my tutorial on it.
const output = document.getElementById("output")
const code = document.getElementById("code")
function addToOutput(s) {
output.value += `>>>${code.value}\n${s}\n`
output.scrollTop = output.scrollHeight
code.value = ''
}
output.value = 'Initializing...\n'
// Init pyodide
languagePluginLoader.then(() => { output.value += 'Ready!\n' })
function evaluatePython() {
pyodide.runPythonAsync(code.value)
.then(output => addToOutput(output))
.catch((err) => { addToOutput(err) })
}
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Default Pyodide files URL ('packages.json', 'pyodide.asm.data', etc.)
window.languagePluginUrl = 'https://pyodide-cdn2.iodide.io/v0.15.0/full/';
</script>
<script src="https://pyodide-cdn2.iodide.io/v0.15.0/full/pyodide.js"></script>
</head>
<body>
Output:
</div>
<textarea id='output' style='width: 100%;' rows='10' disabled></textarea>
<textarea id='code' rows='3'>
import numpy as np
np.ones((10,))
</textarea>
<button id='run' onclick='evaluatePython()'>Run</button>
<p>You can execute any Python code. Just enter something
in the box above and click the button.
<strong>It can take some time</strong>.</p>
</body>
</html>
There's a new tool, PyScript, which might be helpful for that.
Official website
GitHub repository
You can't run Python code directly
You may use Python Inside HTML.
Or for inside PHP this:
http://www.skulpt.org/
You should try the Flask or Django frameworks. They are used to integrate Python and HTML.
There is a way to do it with Flask!
Installation
First you have to type pip install flask.
Setup
You said when a user clicks on a link you want it to execute a Python script
from flask import *
# Importing all the methods, classes, functions from Flask
app = Flask(__name__)
# This is the first page that comes when you
# type localhost:5000... it will have a tag
# that redirects to a page
#app.route("/")
def HomePage():
return "<a href='/runscript'>EXECUTE SCRIPT </a>"
# Once it redirects here (to localhost:5000/runscript),
# it will run the code before the return statement
#app.route("/runscript")
def ScriptPage():
# Type what you want to do when the user clicks on the link.
#
# Once it is done with doing that code... it will
# redirect back to the homepage
return redirect(url_for("HomePage"))
# Running it only if we are running it directly
# from the file... not by importing
if __name__ == "__main__":
app.run(debug=True)
You should use Py Code because it could run Any python script In html Like this:
<py-script>print("Python in Html!")<py-script>
Im not sure if it could run modules like Ursina engine ect But what i know is
That It allows you to type Python in Html. You can check out its offical Site for more info.
We can use Python code in HTML files. We have to use Python’s libraries within our browsers.
As we use Pyscript, we don’t need to worry about deployments. Everything happens in a web browser. We can share our HTML files with anyone containing fancy dashboards or any chars data. They can directly run it in a web browser without any complex setup.
Pyscript allows us to write python code with the help of 3 main components:
Py-env: It defines the python packages list which needs to run your
code.
Py-script: In this tag, the user will write their python code.
Py-repl: It will Create a REPL component. The REPL component
executes the code user enters and displays the result of the code in
the browser.
Let's start:
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
Our Hello world program will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>Python HTML app Hello World</title>
</head>
<body>
<py-script>
print("Hello World!")
</py-script>
</body>
</html>
This project is still in the alpha stage, so maybe we can see many more new things in the upcoming days. Let know more about how to use python in HTML file.

How to insert data to HTML page with Python?

I have some data and I would like to write it into an HTML page.
In PHP in would be possible just to write
<?php .... take the data and print it ?>
How can it be done with Python?
Should I generate the WHOLE page with Python or can I just extract this data and place it in the needed place in the HTML page?
This should be accessed from a web server when someone requests a URL.
If you use a framework like Flask or Django, you can use templates to render data into HTML without having to print out the entire HTML from Python (actually, it does that behind-the-scenes, but you only have to write your template once).
Flask uses a templating language called Jinja2, which lets you write templates like this:
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
Hello, {{ name }}.
</body>
</html>
and render them out like this:
#app.route('/index')
def index():
title = "My Page"
name = "Foo"
return render_template('mytemplate', title=title, name=name)
Django has a similar function with its inbuilt templating system.
If you are running on a cheap webhost, you might not have the flexibility for running a full-blown web framework like Django or Flask (which have a lot of dependencies and should be run in a WSGI server). On my webhost, Siteground, I use a microframework called Bottle.py, which is similar to Flask but has only a single-file dependency so it can run wherever Python is running, using CGI. I have it set up as detailed in this post, by running it as CGI—app.run(server='cgi')—and use .htaccess rules with mod_rewrite to remove the app.py from the URL.
Documentation: https://pypi.python.org/pypi/html/
Do like this:
print("Content-type: text/html\n")
print("""<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Обработка данных форм</title>
</head>
<body>""")
print("<h1>Обработка данных форм!</h1>")
print("<p>TEXT_1: {}</p>".format(text1))
print("<p>TEXT_2: {}</p>".format(text2))
print("""</body>
</html>""")
You can push the data to mysql and fetch that using php code.
python code for pushing to mysql
php code for fetching from mysql

In Python, I can print HTML to the browser, how can I ensure that the CSS that relates to it also get "printed"

// After the "Content-type..." declaration...
print """<html>\
<head>
<title>Create Survey</title>
<link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body>...."""
Assuming you are using something like CGI to "print" text based on a web request you should rely on your web server (Apache for example) to "print" the content back to the requesting client based on where your CSS file is located in the htdocs directory.
However if you are just wanting some output in a command line window you could do...
print file('/path/to/your/file/styles.css').read()

Markdown preview Python-based plugin for gedit

I've installed the markdown preview plugin for gedit running on Lubuntu 13.04. It works as expected.
However, for ease of viewing, I altered the appearance of the resulting html panel (left panel) by including a link to a local stylesheet at the top of each markdown file. But this approach obviously means that I have to alter all my existing markdown files.
To avoid that, I looked at ~/.local/share/gedit/plugins/markdown-preview/__init__.py which has the code for the plugin, and I see lines #39 and #40 (reproduced below):
# Can be used to add default HTML code (e.g. default header section with CSS).
htmlTemplate = "%s"
That gives me the impression that I can somehow tell the plugin to look at a stylesheet and style the html accordingly. But I don't know what to do (if indeed htmlTemplate = "%s" has to be changed).
Set htmlTemplate to something like the following
# Can be used to add default HTML code (e.g. default header section with CSS).
htmlTemplate = """
<html>
<head>
<link rel="stylesheet" type="text/css" charset="utf-8" media="screen" href="http://paste.ubuntu.com/static/pastebin.css">
</head>
<body>
%s
</body>
</html>
"""

Categories

Resources