i just would like to run a python script by clicking on a html button.
python script is reallly simple. when you run it, it just add a "name" and "age" data in my database.
import sqlite3
conn = sqlite3.connect('bdaremplir.sqlite')
cur = conn.cursor()
"""cur.execute('DROP TABLE IF EXISTS latable')
cur.execute('CREATE TABLE latable (noms TEXT, age INTEGER)')"""
nom = 'TheName'
age = 100
cur.execute('''INSERT OR IGNORE INTO latable (noms, age) VALUES ( ?, ? )''', (nom, age))
conn.commit()
and the basics of html
<!DOCTYPE html>
<html>
<head>
<title>visualisateur</title>
</head>
<body>
<button></button>
</body>
</html>
now from here i don't at all what i can do.
if anyone can help... thank you.
Web browsers only know how to run JavaScript, not Python, so unless you really want to run Python in the browser1, you have to learn about the client-server architecture of the web.
Basically, you have to
make your Python program available as a web server, and
send a request to that server when your HTML button is clicked.
Running a web server
There are many ways to implement a web server in Python. When you get to writing a proper application, you'll probably want to use a library like Flask, Django, or others. But to get started quickly, you can use the built-in Python HTTP server with CGI:
Create a Python script named handle_request.py with the following content:
#!/usr/bin/env python3
print("Content-Type: text/plain\n")
print("hello world")
and put it into the cgi-bin directory next to your HTML file and make sure you can run it by typing "handle_request.py" into the console;
2. Run the built-in HTTP server:
python3 -m http.server --bind localhost --cgi 8000
Open http://localhost:8000 in your browser to access the server.
You should see the listing of the directory, including your HTML file and the cgi-bin directory. Clicking the HTML file should display it in the browser (with a URL like http://localhost:8000/test.html), and opening http://localhost:8000/cgi-bin/handle_request.py will run the script we've created and display its response as a web page. You can add your code to the script, and it will run whenever the browser accesses its URL.
Making a request from your web page
Now the question is how to make the browser access the http://localhost:8000/cgi-bin/handle_request.py URL when a button on your page is clicked.
To do that you need to invoke the API for making requests from JavaScript. There are different ways to do that (e.g. XMLHttpRequest or jQuery.ajax()), but a simple way that works in the modern web browsers is fetch():
<button id="mybutton"></button>
<script>
document.getElementById("mybutton").onclick = async function() {
let response = await fetch("http://localhost:8000/cgi-bin/handle_request.py");
let text = await response.text();
alert(text);
}
</script>
Now when you click the button, the browser will make a request to the specified URL (thus running your script), but instead of displaying the results as a web page in a tab, it will be made available to your JavaScript.
notes
1 ...which you probably don't at this point, but if you do, see the pointers by Michael Bianconi.
Related
I created a Flask app that displays the latest pictures on an HTML website. The website is set to automatically refresh every 10 seconds using a meta tag
<meta http-equiv="refresh" content="10" />
it all works great when the server and website run on a local PC, but when I run the app over LAN, the page refreshes correctly a few times, but sooner or later it stops. The webpage itself looks like it is loading (spinning wheel), but no new requests are registered in the flask app. The only way to start refreshing it again is by manual refresh on the client-side or by restarting the flask app on the server-side.
What could be the problem that causes this and how to mitigate it? Can it be caused by a firewall that doesn't like the constant refreshes? Are there any alternatives to said meta tag? I don't want to have any difficult set-up on the client-side like job scheduling etc (unless it is the only solution).
You could just use javascript for this. Just put the code below in your html file somewhere or in a seperate javascript file named script.js and link that javascript file like <script src="/Path/To/File.js"></script>
<script>
window.setTimeout(function () {
window.location.reload();
}, 30000);
</script>
Please help me people!
I have setup a xcat server so that I can manage my many nodes therefrom. I want to stop running python scripts directly from within my xcat server. I figured it would be better for simplicity to create a webpage as my interface and use python as the server-side script from the xcat server
I am finding that my underlying python script is not really doing everything I want it to do. For example, my script is unable to power up or down my nodes defined on the xcat server. To illustrate better, my node (hs22n12 ) is defined on my xcat server (xcatmn5). I am able to use “nodels | grep hs22n12” to locate that node on xcatmn5 and operate it which ever way I see fit such as power up (“rpower hs22n12 on”) or power down (“rpower hs22n12 off”). However, when I build this commands into my python scripts such that they are operated when I provide input from html,
The operation is not successful.
Some specs are indicated here:
I am using apache and I have confirmed that this is running
My python scripts are in my var/www/cgi-bin and I am able to run them
My htnl files are located in /var/www/html
Please find below my code snippets
First html code (which is currently okay for me and is working well)
****<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="title">
<title> Node Provisioning Application </title>
</div>
<form action='cgi-bin/powerOff11.py' method="post">
Enter Node: <input type="text" name ="Node"/>
<input type="submit" value="submit">
</form>
</body>
</html>**
I will add my python code shortly
Here's my python code
#!/usr/bin/python
import cgi
import cgitb
import subprocess
import os
import sys
cgitb.enable()
print "Content-type: text/html\n"
form = cgi.FieldStorage()
Node = form.getvalue('Node')
print"<p>%s</p>"% Node
if Node == None:
print"<p>No node provided</p>"
else:
find_node = subprocess.call('nodels | grep ' + Node, shell=True)
if find_node == 0:
print("<p>Node not defined yet!</p>")
else:
if find_node > 0:
print"<p>%s</p>"% Node
p_off = subprocess.call('rpower ' + Node + ' on',shell=True)
print"<p>%s powering on...</p>"% Node
else:
sys.exit()
update:
After some diggging around, I was able to enable the HTTPS protocol for REST API and also enabled the certificate of HTTPs by following the instruction here: https://xcat-docs.readthedocs.io/en/stable/advanced/restapi/restapi_setup/restapi_setup.html
After i did this, I was actually able to access different resources, such as the repository of my xcat server via https. However, original problem has become clearer. The new response I am getting from http whenever I try to run a command that needs root priviledge is:
"Error: Permission denied for request warning: the client certificates under /usr/share/httpd/.xcat/ are not setup correctly, please run '/opt/xcat/share/xcat/scripts/setup-local-client.sh ' as 'root' to generate the client certificates; otherwise, the SSL connection between xcat client and xcatd will be setup without certificate verification and open to Man-In-The-Middle attacks."
This leads me to believe that my problem is how to configure /etc/httpd/conf/httpd.conf to be able to request root access and also make requests from there. Mind you I am able to get response to all binary commdans such as (ls, cd etc) that are in the /usr/bin directory (these commands do not require root priviledge to be made. Can someone point me to how to configure httpd.conf such that my request can be legitimately made from /root to xcat? Thank you all for your helps.
This is xCAT2, I assume?
If so, did you give correct permission to the apache process to execute xCAT commands?
xCAT policy table serves as ACL (access control list) for xCAT.
You can do something like:
mkdef -t policy -o 7.0 name=apache rule=allow
7.0 is just an example - use any other number as long as it doesn't conflict with any preexisting rule - tabdump policy can be convenient as there shouldn't be too many lines in the policy table.
for name use the apache process owner.
By default unless limited with commands= flag, all commands are allowed by this new policy rule.
Thank you again for taking the time to respond to my issue. I have tried it out. It appears that this is not the problem, however you have nudged me in the right direction of thinking beyond the actual code to the entire web service configuration of httpd and how it makes requests from xcatd. I was able to do some adjustment and noticed that I am able to get response from xcatd to all binary commands in /usr/bin/python (e.g ls) but I am unable to get response to such commands that needs root access like lsdef. This leads me to believe that the problem I am having is that I am not given permission to request root priviledge (run root commands) from http client. I need someone who has done web service configuration to look ino this. I believe the problem is most likely in httpd.conf (Still reading up on it) But tanks again.
After exposure to Svelte/Rollup in the JavaScript world I was impressed that it could refresh the browser automatically when changes were made to the source code. Seeking a similar behaviour in Python I found the package livereload that supports integration with Flask (pretty sure using the same tech). I want the result of the refresh to reflect ALL changes to the source code.
I am using WSL with livereload v2.5.1 and viewing via Chrome. I can successfully get the page to refresh on a detected source code change but the refresh doesn't re-download the new files and just displays the cached files. The page does refresh but I need to hit Ctrl + click refresh to see the actual changes. Using developer mode and turning off caching works as desired. Using Svelte/Rollup doesn't require disabling caching to see source changes.
Most of my changes are to *.css or *.js files served from the 'static' folder in a standard Flask project template and rendered using the 'render_template' function of Flask.
I'm launching my Flask server as follows:
app = create_app()
app.debug = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
server = Server(app.wsgi_app)
server.watch(filepath='static/*', ignore=lambda *_: False)
server.serve(liveport=35729, host='127.0.0.1', port=80)
I would like to not have to disable the cache so that the refresh triggered by livereload actually reflects the changes in the source. Is there a setting in Flask or livereload I can use to achieve this or is this a feature request for the livereload package?
Related Question:
How to automate browser refresh when developing an Flask app with Python?
UPDATE EDIT:
Further testing has shown that this is specifically an issue with Chrome, with Firefox it works as expected out of the box. Digging into the underlying livereload.js library it seems there is a parameter of 'isChromeExtension' which I have tried to force set to True but had no effect.
I came across the same issue and here is what I did to solve the issue.
As you mentioned this is a browser caching problem. So we want invalidate the cached css/js files. We can achieve this by setting a version on the static file. We want the version to change each time you make changes to the css file. What I did feels a bit hacky but you'll get the idea.
Here is what I have for my html template
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<link href="{{ url_for('static', filename='main.css', version=time)}}" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="hello-color">
{{ message }}
</h1>
</body>
</html>
You can see version=time I am passing the template the current time with the following.
from flask import Flask, render_template
from time import time
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('hello.html', message="Hello World!", time=time())
from time import time and
time=time()
And finally my main python file
from app import app
from livereload import Server
if __name__ == '__main__':
server = Server(app.wsgi_app)
server.serve(port=2200, host='0.0.0.0')
Hopefully this helps you or anyone else running to this issue.
I've tried various different ways to open an HTML file from python code, but each time I get a '500 internal server error'.
Here is my python script:
if (variable == "0, User and IP logged"): #conditional to check if user's credentials were accepted by the API
page = urllib.urlopen("mainPage.html").read()
print page
#html file is opened and read - NOT WORKING!
Here is my html file:
<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>
How do I get the python script to display my hello world page?
My tutor said I should use open(), but I'm not sure how.
First of all you need to run Web Server which will server web pages :
Here I am using sample bottle web framework
bottle_server.py
from bottle import route, run
#route('/')
def dashboard():
return '<b>This is index page</b>'
run(host='localhost', port=8080)
Run script using
python bottle_server.py
Now, Server is running on localhost on port 8080
Here is sample python script
Client.py
import urllib
print urllib.urlopen('http://localhost:8080/").read()
Run client script using
python Client.py
This will produce output like
<b>This is index page</b>
Try this one...
webbrowser.open_new_tab('helloworld.html')
I used to create web app in the same computer, but if the server and the client is not in the same computer, how can we access to the web page ?
I mean, for example I have an html form and a button "ok" :
If the server and the client are in the same computer, in action = " " we put localhost/file.py , but if the server and the client are not in the same computer how to do this ? Because the client can't to have localhost in his webbrower (url).
The "action" part of a form is an url, and If you don't specify the scheme://host:port part of the URL, the client will resolve it has the current page one. IOW: just put the path part of your script's URL and you'll be fine. FWIW hardcoding the scheme://host:port of your URLs is an antipattern, as you just found out.
Your script is supposed to be run as a CGI script by a web-server, which sets environment variables like REMOTE_ADDR, REQUEST_METHOD ...
You are running the script by yourself, and this environment variable are not available.
That's why you get the KeyError.