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.
Related
How can I import from a local module from pyscript? This is my code:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>Title</title>
<py-env>
- paths:
- ../app/db_operations/BookOperations.py
</py-env>
</head>
<body>
<py-script>
from BookOperations import get_books_count
</py-script>
</body>
</html>
I'm trying to import the BookOperations file and the function get_books_count from it but I keep getting this error in the browser:
PyScript: Loading from file ../app/db_operations/BookOperations.py failed with error 404 (File not Found). Are your filename and path are correct?
This is the image of my local project structure
This is what I've tried so far:
write the path without the first dash /
(..app/db_operations/BookOperations.py)
using a single . at the
beginning of the path (./app/db_operations/BookOperations.py)
using no dots
writing the path like "app.db_operations.BookOperations.py"
(with . instead of /)
moving the py-env tag inside body tag
A couple of things:
Are you using a server program to serve your project? Something like VS Code's live server, or even Python's included http server will work. If your files aren't made accessible on the network, PyScript running in the browser won't be able to fetch them.
PyScript has moved on quite a bit from the Alpha version - the latest release is 2022.12.1 from mid-December. You'll find some increased functionality there; py-env: paths has been replaced with the much more flexible fetch configurations syntax (more info). Additionally, there are improved error messages for when fetching files fails that may be helpful.
I have developed a web-based tool, and currently trying to make it python-launchable. I figured using CEFpython is probably the way to do it. I followed the tutorial here and wrote the following code:
from cefpython3 import cefpython as cef
import base64
import platform
import sys
import threading
import os
HTML_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="static/css/main.css" rel="stylesheet" />
</head>
<body>
<div id="UI">
</div>
<div id="container"></div>
<script src="static/main.js"></script>
<script type="text/javascript">
function defineData(datainput){
console.log("start")
data = datainput;
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
Main();
}
</script>
</body>
</html>
"""
def html_to_data_uri(html):
html = html.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret
def main(config):
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
settings = {}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
browser.SetClientHandler(LoadHandler(config))
cef.MessageLoop()
cef.Shutdown()
return
class LoadHandler(object):
def __init__(self, config):
self.config = config
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
# Loading is complete. DOM is ready.
browser.ExecuteFunction("defineData", self.config)
unfortunately, unlike in the tutorial, my tool has to load a local .js file where the main function is defined (), and it seems if I code the html file this way, my working directory is not actually the directory where I call the script, but some strange place
the output of these lines are:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
output:
text/html;base64,CjwhRE9DVFlQRSBodG1sPgo8aHRtbCBsYW5nPSJlbiI+Cgk8aGVhZD4KCQk8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CgkJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgdXNlci1zY2FsYWJsZT1ubywgbWluaW11bS1zY2FsZT0xLjAsIG1heGltdW0tc2NhbGU9MS4wIj4KCQk8bGluayBocmVmPSJzdGF0aWMvY3NzL21haW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIC8+CgkJPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCQkJKiB7CgkJCQkuYm9yZGV....
text
Could you help me finding the correct way of hard coding html code in python with the correct path? maybe I need to somehow set the path?
PS: I did try including the html code in a separate .html file, and it worked on Windows machines, but it seems MacOS doesn't like it. Since this tutorial did work on MAC, I'm trying to hard code the html part into the python script and hope it would work on both Windows and Mac
Well, the HTML document has been converted to the body of a data URI by html_to_data_uri, so the U[niversal]R[esource]L[ocator] (window.location) of the document isn't a location on a server, but the data URI itself (the "strange place" you mention).
Remember that URLs are a subset of URIs, and you passed the URI as a URL to CEF with:
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
So, as long as you are using a data URI/URL, I don't think that window.location will be helpful. Instead, you could extract the HTML code into a separate .html file, and change that line to:
browser = cef.CreateBrowserSync(url="/path/to/that_html_file.html", window_title="Test")
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
How Insert Python code in a Html File ?
<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>
Here i want to insert Python Code
</body>
</html>
simple example for CGI
print('Content-Type: text/html')
print('\n\n')
print('''<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>''')
# Here insert Python Code
print('''</body>
</html>''')
simple example for WSGI
def application(environ, start_response):
output = '''<html>
<head>
</head>
<h1>Hello Python!</h1>
<body>'''
# Here insert Python Code which appends string to `output`
output += '''</body>
</html>'''
status = '200 OK'
response_headers = [('Content-type', 'text/plain'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
You cannot (or at least should not) mix python with HTML like you can do with PHP. For producing HTML dynamically, you can use any templating library like Jinja. You can also manipulate HTML as string directly in python script but that is obviously not recommended!
I think you try to archive the same thing as with PHP and
<php> smth </php> tags.
And it is impossible. You may try using something like Brython.
This is only true options. Or just try Coffeescript which is pretty similar to Python and Ruby.
But if you need to do it on server side only, that mean the code will be executed on you side of wire and not on browser you can look at things like Flask. This framework is really simple and easy to use and how great templating engine.
PS. Including any code other than JS or language compiled to JS inside HTML is not a good idea. It is just asking for troubles.
I think you want to design a website or web service with python language. You must use flask ot django ( my prefer is flask ) for this. Flask contains werkzeug and jinja2 packages for it. But you can't write something like javascript with python.
How do I put this python script:
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
inside of a html file?
Something like this, if you want to create an html, not necessarily display it:
html_file = open('namehere.html','w')
a = ['f','d','s','a']
x = -1
scope = vars()
data = ''
for i in a: #TIP: use a generator
scope['x']+=1
data += a[x]
data += '\n'
html_file.write(data)
html_file.close()
There's now a solution to this, the solution is PyScript. This is a python framework that enables you to embed python scripts in HTML. Check out the sample code below.
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
print("Hello World")
</py-script>
</body>
</html>
If your web server supports it, you could run it as a CGI script to output an HTML file - more information here: http://www.penzilla.net/tutorials/python/cgi/
You would need to modify your script to ouput valid HTML, but that tutorial should get you started.
Not possible. Python isn't like PHP; I can't just do this
<?php
And be good to go.
However, if your web server has a Python interpreter (most all do, these days), you can write CGI (common gateway interface) scripts to make Python code run on your webpage.
If you're trying to generate dynamic content (like change words in HTML), Javascript or PHP is better. Python is more suited to web applications.
if the script is in a server , you can run it using remote funcion call through JSON-RPC
you may refer the JSON-RPC documentation here
You can use {% %} tag in html and inside this you can write your python code.
Perhaps CGI is what you are looking for:
http://docs.python.org/library/cgi.html
http://www.penzilla.net/tutorials/python/cgi/
For example:
print "Content-Type: text/html" # HTML is following
print # blank line, end of headers
print "<html><head></head><body><pre>"
a = ['f','d','s','a']
x = -1
scope = vars()
for i in a:
scope['x']+=1
print a[x]
print "</pre></body></html>"
Surround it with a <body> and <head> tag and you're golden.
But seriously, I think what you are trying to do is print fdsa, which would would look like this:
<head>
<body>
fdsa
</body>
</head>
What you have there is not really a python script. You might need to correct that first, and then give a little more explanation what you are trying to do.
You can convert the thing into HTML or JavaScript. It would sort of be like this:
<script>
var a = ['f','d','s','a']
var x = -1
//other code
</script>
I am not showing the rest because I am not sure how to make a repeat loop.
You can't. If you want to run script in an HTML File, try another language like JavaScript or PHP. To include javascript, type this:
<script type="text/javascript">
// ...
</script>
Or in HTML5, you don't even have to type the type attribute:
<script>
// ...
</script>
To include PHP, type
<?php
// ...
?>