python eel - and 404 when block=False - python

Just looking a bit into the idea of python and eel - and got somehow a strange behavior by trying around the callbacks and expose'es.
Well - I put out all my code with feedbacks and came back again to the basic level. But the behavior is still there. block=False seems not working and will crash:
import eel
eel.init("view")
eel.start("index_blank.html", block=False)
And my puristic html code:
<!doctype html>
<html lang="en">
<head>
<script src="eel.js"></script>
</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
It gives me a 404 error.
But when I start eel with this basic pattern:
eel.start("index_blank.html")
it will work. When I use block=False it wont't:
eel.start("index_blank.html", block=False)
Any idea?
Yes... I know. I kicked out all my callbacks out of this code and came back to this very basic pattern. Just to get the idea what's wrong. I know that I do not need block=False here - but at the end of the day I want draw back something on the html-code.
python3. pip3.

Related

Repetitive execution of a Python code daily without Javascript

I intend to use Python to generate an HTML code that will be saved to an external file. The HTML code will display the current day. No Javascript nor PHP allowed. How can I make the Python code repeat every day after midnight, so that the corresponding HTML file will contain a valid day in a week info? Thank you. My code:
import datetime
t=datetime.datetime.now()
s="""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Daily Portal</title>
</head>
<body>
<div>{maininfo:}</div>
</body>
</html>"""
s1=t.strftime("%A")
s2="Good morning John. Today is "+s1+"."+" Have a beautiful day."
s=s.format(maininfo=s2)
print(s)
You can set a job scheduler to execute the code everyday. Refer here and here (if you are running on a unix system).

Bokeh integration with CSS and jinja

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

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.

Writing Files not working (Windows 7)

I'm trying to output some of my data to an HTML file.
Python has no problem creating a new file, but it seems to have problem with the write command. The program functions with no errors or warnings, but the filesize remains 0kb (empty).
I'm a bit of a newbie to python, so I'm hoping someone can point out my mistake.
Here is the code:
#OUTPUT
calcfile = open('calculation.html','w');
CALCOUT = """<!DOCTYPE html>
<html>
<head>
<title>Quick Calculation</title>
</head>
<body>
<h1>Estimate</h1>
<table>
"""
#Some code which appends to CALCOUT -- long but it works perfectly via STDOUT.
calcfile.write("%s" % CALCOUT);
#also tried calcfile.write(CALCOUT);
You have to remember to close the file after opening it. Or even better, use the with constuct, which closes files automatically as soon as the scope of the with block is exited.
with open('calculation.html','w') as calcfile:
CALCOUT = """<!DOCTYPE html>
<html>
<head>
<title>Quick Calculation</title>
</head>
<body>
<h1>Estimate</h1>
<table>
"""
calcfile.write(CALCOUT)
Try this:
calcfile.write(str(CALCOUT))
Also, there are no semicolons needed in Python.
You have to calcfile.close() the file of course.

System error with .cpt file Grok Framework

I don't know why this is happening. I'm getting to grips with the Grok framework. While following the tutorial I encountered this error. When using TAL:attributes to link to a CSS style sheet, the index page loads with a system error message. The index file is called index.cpt If I change it to index.pt it loads correctly. Can anyone tell me why this is happening? Is the cpt file type restrictive or is it my code?
index.cpt:
<html>
<head>
<link rel="stylesheet" type="text/css"
tal:attributes="href static/style.css" />
</head>
<body>
<p>Hello world!</p>
</body>
</html>
style.css:
body {
background-color: #FF0000;
}
app.py:
import grok
from sample import resource
class Sample(grok.Application, grok.Container):
pass
class Index(grok.View):
pass
class Bye(grok.View):
pass
It appears that the newest version of Grok uses the 'Chameleon' language(.cpt files) but the tutorial is still based on the Zope language(.pt files). There are some nuances between them so that is why I was getting the system error.
It's just a language syntax problem. I'm just renaming the files as .pt files instead of .cpt and working with Zope.

Categories

Resources