Creating a basic web page to trigger a Python script - python

I have a Python script that loops through a list of SQL queries read from an Excel file, executes them, and stores output results to a .csv file.
Currently I trigger this from the command line locally. I would like to create a very basic Web page, something that basically has a button to click to execute the Python script for now. If I can get the output file stored there somehow as well, even better.
The idea being I would start with it locally, but then move the web page somewhere where my team could access it and do the same thing.
I don't need much functionality at all for this web page obviously but this stuff is new to me so not quite sure where to start. Any ideas?
Thanks

I guess Flask would be a decent choice for a simple web app.
folder structure:
├── app.py
├── static
│   ├── index.html
app.py (EDIT added index.html route handling, duh doy)
from flask import Flask
app = Flask(__name__, static_url_path='', template_folder='static')
#app.route('/')
def index():
return app.send_static('index.html')
#app.route('/execute')
def execute_sql_logic():
# Do stuff here
return 'SQL executed', 200
if __name__ == '__main__':
app.run()
You'll need to export FLASK_APP=app.py in your working directory
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href='/execute'><button>execute SQL</button></a>
</body>
</html>
Simplest example I could think of.
Now when you'll run app.py and navigate to localhost:5000 (Port defaults to 5000 if I remember correctly) you'll see the HTML page with the execute SQL button. Clicking on it will send a GET to localhost:5000/execute which in turn will call your function.
Deploying on a server is beyond the scope of this answer unfortunately.

Related

Firefox or Chrome can't find a photo inserted in a Bottle template

I am old timer but young learner. I want make my own website, using Python and Bottle.
I have an HTML page which contains a title, a subtitle and a photo. This is a template used by Bottle in this little code:
from bottle import route, run, view
#route("/")
#view("pagedegarde.html")
def menu() :
contenu = "Moto de l'abbé Khan"
return {"titre" : "Bécanes", "contenu" : contenu}
run(host = '0.0.0.0', port = 8080, debug = True, reloader = True)
Here is the template, "gardepage.html":
<!doctype html>
<!-- page_de_garde.tpl -->
<HTML lang="fr">
<HEAD>
<TITLE>{{titre}}</TITLE>
<meta charset="UTF-8">
</HEAD>
<body>
<header>
<h1>Phrases et attrapes</h1>
</header>
<h3>{{titre}}</h3>
<p><image src="turquoise.jpg" alt="125 k4" /></p>
{{!contenu}}
<hr/>
</body>
</html>
The photo is in the same directory as the template and the python file.
Results :
127.0.0.1 - - [13/Mar/2022 11:10:58] "GET /turquoise.jpg HTTP/1.1" 404 746
The page is displayed, the title, the subtitle, but not the photo, there is instead the alternative mention "125 k4".
I wonder what it is, "746". Since I've had so many 404s (!), I've found that terminal messages always follow "404" with another number. I tried to find out about it, but couldn't find anything.
Otherwise, if I click on the html file, it displays without a problem, including the photo.
I tried both suffixes .tpl or .html, there is no difference. I tried .png or .jpg : no difference.
And I get the same result with Python 3.8.1 and Bottle 0.12.7 or with Python 3.10.2 and Bottle 0.12.19.
Thanks for reading me.
Bottle doesn't serve image/js/css automatically - you have to add own function for this.
It is simpler if you put static files in subfolder because then function can recognize this folder in url and run correct function. And this is popular method in other frameworks.
See: Routing Static Files
Example uses subfolder static for this - so you should have files
main.py
pagedegarde.html
static/turquoise.jpg
from bottle import route, run, view, static_file
#route("/")
#view("pagedegarde.html")
def menu() :
contenu = "Moto de l'abbé Khan"
return {"titre" : "Bécanes", "contenu" : contenu}
#route('/static/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='static/')
# or with full path
#return static_file(filepath, root='/full/path/to/static/')
run(host='0.0.0.0', port=8080, debug=True, reloader=True)
And remember to use /static in HTML
<p><image src="/static/turquoise.jpg" alt="125 k4" /></p>
Other frameworks may have the same problem. Some may serve static file only in debug mode but in normal mode they should be executed with web servers like Apache or nginx which should serve static files (because they do this faster)
EDIT:
To serve image in the same folder you would need to use regex to recognize filename in URL
#route('<filepath:re:.*\.(jpg|png|gif)>')
def server_static(filepath):
return static_file(filepath, root='')
The same you would have to do for other static files .css, .js, etc.
And if you would like to server other files for downloading or displaying then you would have to add also other extensions - ie. .csv, .xls, .mov, .mp3, etc.
If you would use regex .* as last route then it would serve all files (which don't match to previous routes)
#route('<filepath:re:.*>')
def server_static(filepath):
return static_file(filepath, root='')
but it is not safe because someone could run ie. http://0.0.0.0:8080/main.py to download source code.

python not reading in a web page

I run the python (server?) in the background that creates the pages etc.
I then have my usual index.html file and the header and nav bar are in a /shared folder.
On my index.html page, I have the following code :-
<html>
%include('shared/html-head.html')
%include('shared/html-nav.html')
for some reason, this is not loading the files. They are there and correctly named and are .html files.
The page in Chrome displays the following at the top of the page:- %include('shared/html-head.html') %include('shared/html-nav.html')
Any ideas why?

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

Template render on HTML AND CSS using Google App Engine

I'm currently working on my website hosted on GAE.
It has not been update since a while, so now, I'm trying to made a refresh of it :D
To do the trick, I try to use the MVC model using Python and WSGI, WebAPP2 and Render.Template.
Everything goes right, except for the CSS part.
Indeed, I can't render some part of my CSS using the GAE (django) method.
My Python controller is calling the HTML file and replace the variables by the dict() values correctly.
But now, and to be able to only have restricted amount of CSS file, I'm trying to do the same thing.
Unfortunatly I don't know how I'm suppose to call the CSS File.
I'm currently calling my CSS on my HTML as usual:
<link rel="stylesheet" media="screen" type="text/css" href="/assets/css/struct/index.css">
And trying to dynamically render this part of the file:
header#navigation{
height:auto;
min-height:480px;
width:100%;
min-width:100%;
background-image:url('/assets/img/content/{{content_cat_name}}/cat_img.jpg');
background-repeat:no-repeat;
background-position: left top;
background-size:contain;
background-color:#efefef;
}
and everything is then call by my python code like this:
class URIHandler(webapp2.RequestHandler):
def get(self, subdomain, page):
name = subdomain
pattern = os.path.join(os.path.dirname(__file__), '../views' ,'index.html')
template_values = {
'content_cat_name':name,
'cat_menu_title':name,
'cat_menu_text':name,
}
self.response.out.write(template.render(pattern, template_values))
So, if someone could help me to correctly call my CSS and replace the variables using my python script, I'll be really happy :D
Thanks in advance.
template.render can only replace tokens in the file that you specify in the path parameter (the first parameter). You're serving the .css file out of a static directory, so no token replacement happens, because that file's not getting passed through that code.
You could inline the parts of your CSS that contain tokens in your index.html file.
I was having what I think is the same problem. I found this GAE documentation very helpful. In short you need to go into your app.yaml file create a new handler:
url: /foldername
static_dir: foldername
And then in your link tag:
href="foldername/index.css"

Categories

Resources