I developed a simple application in Python (with a Tkinter interface). But now I want provide a web interface for the same. I know that the python script will wun on the server as CGI. But I would like everything to happen on one page i.e. something like this:
There is a text box for the user to provide input
When a submit button is clicked, the python script runs on the input and generates the output
The output is displayed on the same page without the page reloading
I think Ajax can be used to do this (and I'll learn it if that's the only way), but is there any easier way to do this? I tried generating the front end in python, and linking the button to a function in the same script but that doesn't work...
Thanks
PS: Sorry if the title and the tags are a bit misleadsing...i wasn't so sure what to pick...
EDIT: I tried this but it doesn't work
#!/usr/bin/python2
import cgi
print 'Content-type: text/html'
print """
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
"""
data = cgi.FieldStorage()
sometext = data['sometext'].value
if sometext != '':
print "<p>" + sometext + "</p>"
print """
<form action="test.py" method="post">
<input type="text" name="sometext">
<input type="submit">
</form>
</body>
</html>
"""
Related
I am trying to call my python function created. But not getting any output and no resource how to achieve.
Code :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<p>Click on the "Choose File" button to upload a file:</p>
<form>
<input type="file" id="myFile" name="filename">
<input type="submit" onClick="readfile(filename)" name="SUBMIT">
</form>
<py-script>
def readfile(filename):
with open(filename) as mfile:
head = [next(mfile) for x in range(1,5)]
print(head)
</py-script>
</body>
</html>
It would be great helpful if some one provide input like …
How to pass selected file to my function and python will be executed & return output on screen.
When writing Python in the browser, you must rethink how actions are performed. Typically, Python programs are procedural. Browser-based applications are asynchronous.
The first step is to enable asynchronous features:
import asyncio
Browser based programs cannot directly access the local file system. Your code is not doing what you think it is.
def readfile(filename):
with open(filename) as mfile:
head = [next(mfile) for x in range(1,5)]
print(head)
Your code is reading from the browser virtual file system which is allowed. You are trying to process the event from the ` element but trying to access a different location.
Note: I do not know what the file contents of "filename" are, so I did not incorporate your code after the file is read.
Your code cannot read files. You must ask the browser to read a file for your application. This is performed with the FileReader class.
Example:
async def process_file(event):
# Currently, PyScript print() does not work in this
# type of code (async callbacks)
# use console.log() to debug output
fileList = event.target.files.to_py()
for f in fileList:
data = await f.text()
document.getElementById("content").innerHTML = data
# Add your own code to process the "data" variable
# which contains the content of the selected file
Another problem is that you are passing a Python function as a callback. That will not work. Instead, you must call create_proxy() to create a callback proxy for the Python function. The browser will call the proxy which then calls your Python function.
Example:
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
document.getElementById("myfile").addEventListener("change", file_event, False)
I put a copy of this solution on my website. You can right-click on the page to download the source code.
File Example Demo
Complete solution:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<title>File Example</title>
</head>
<body>
<p>This example shows how to read a file from the local file system and display its contents</p>
<br />
<p>Warning: Not every file type will display. PyScript removes content with tags such as XML, HTML, PHP, etc. Normal text files will work.</p>
<br />
<p>No content type checking is performed to detect images, executables, etc.</p>
<br />
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile">
<br />
<br />
<div id="print_output"></div>
<br />
<p>File Content:</p>
<div style="border:2px inset #AAA;cursor:text;height:120px;overflow:auto;width:600px; resize:both">
<div id="content">
</div>
</div>
<py-script output="print_output">
import asyncio
from js import document, FileReader
from pyodide import create_proxy
async def process_file(event):
fileList = event.target.files.to_py()
for f in fileList:
data = await f.text()
document.getElementById("content").innerHTML = data
def main():
# Create a Python proxy for the callback function
# process_file() is your function to process events from FileReader
file_event = create_proxy(process_file)
# Set the listener to the callback
e = document.getElementById("myfile")
e.addEventListener("change", file_event, False)
main()
</py-script>
</body>
</html>
I’m learning py-script where you can use <py-script></py-script> in an HTML5 file to write Python Code. As a python coder, I would like to try web development while still using python, so it would be helpful if we could output and input information using py-script.
For example, could someone explain how to get this function to work:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input id = “test_input”></input>
<-- How would you get this button to display the text you typed into the input into the div with the id, “test”--!>
<button id = “submit-button” onClick = “py-script-function”>
<div id = “test”></div>
<div
<py-script>
<py-script>
</body>
</html
I would appreciate it and I hope this will also help the other py-script users.
I checked source code on GitHub and found folder examples.
Using files todo.html and todo.py I created this index.html
(which I tested using local server python -m http.server)
Some elements I figured out because I have some experience with JavaScript and CSS - so it could be good to learn JavaScript and CSS to work with HTML elements.
index.html
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />-->
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input type="text" id="test-input"/>
<button id="submit-button" type="submit" pys-onClick="my_function">OK</button>
<div id="test-output"></div>
<py-script>
from js import console
def my_function(*args, **kwargs):
#print('args:', args)
#print('kwargs:', kwargs)
console.log(f'args: {args}')
console.log(f'kwargs: {kwargs}')
text = Element('test-input').element.value
#print('text:', text)
console.log(f'text: {text}')
Element('test-output').element.innerText = text
</py-script>
</body>
</html>
Here screenshot with JavaScript console in DevTool in Firefox.
It needed longer time to load all modules
(from Create pyodine runtime to Collecting nodes...)
Next you can see outputs from console.log().
You may also use print() but it shows text with extra error writing to undefined ....
An alternative to way to display the output would be to replace the
Element('test-output').element.innerText = text
by
pyscript.write('test-output', text)
I am teaching a year 11 class how to write dynamic webpages, using lighttpd and python on ubuntu.
In my /var/www/cgi-bin I have one python file (testing.py), which gets executed and I see the output in the browser. I have another python file (greet.py) which is supposed to process a form(form1), but I get a "500 - internal server error". It is not 404, so I believe the server is accessing the (file greet.py) but is having some problem.
The file /var/www/html/index.html:
<!DOCTYPE html>
<html>
<title>This is from the html file</title>
<body>Testing<br>
This should show the output of python file in /var/www/cgi-bin <br>
Form1
</body>
</html>
The file /var/www/cgi-bin/testing.py:
#! /usr/bin/python
print("<!DOCTYPE html>")
print("<html>")
print("<title>")
print("Testing from cgi-bin")
print("</title>")
print("<body>")
print("This is testing from /var/www/cgi-bin/")
print("</body>")
print("</html>")
The file /var/www/html/form1.html:
<!DOCTYPE html>
<html>
<title>Form Testing </title>
<body>
<form method="POST" action="/cgi-bin/greet.py">
Name: <input type="text" name="fname">
<input type="submit" value="submit">
</form>
</body>
</html>
This is the file /var/ww/cgi-bin/greet.py:
#!/usr/bin/python
form=cgi.FieldStorage()
name = form['fname'].value
print("<!DOCTYPE html>")
print("<html>")
print("<title> greet - form processed</title>")
print("<body>")
print("Hello "+name.title())
print(<"/body>")
print("</html>")
I see the output of the /var/www/cgi-bin/testing.py.
But when I submit the form1, I get "500 - Internal Server Error'.
Is there something I am missing. Both the files in cgi-bin have same permissions.
Thanks in advance.
sonip
I got it working.
All it needed was one import cgi statement in the greet.py.
sonip
I am wanting to POST a user inputted data in an html file to a Python script with AJAX and have the Python script return it so that it shows up in a specific div in the html file.
HTML
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX Test</title>
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
<script>
function test()
{
var message = $('input[name=message]').val();
$.ajax({
url: "/cgi-bin/hello.py",
type: "POST",
data: {"text" : message},
success: function(response){
$("#div").html(response);
}
});
};
</script>
</head>
<body>
<form>
Enter Message: <input type="text" name="message">
<input type="submit" value="submit" onclick="test()">
</form>
<div id="div">Default Message</div>
</body>
</html>
Python
#!/home/user/virtualenv/test/3.5/bin/python
import cgi, cgitb
cgitb.enable()
data = cgi.FieldStorage()
print "Content-Type: text/html\n"
print data
When I type a message into the input box and press the submit button, nothing happens. I am new to this so I feel like I am probably not understanding how this works. Any help would be appreciated!
Edit: Console is showing Uncaught TypeError: $.ajax is not a function
Edit 2: The first problem was due to using the slim version of jquery. After fixing that, nothing is happening on the page when I input and click submit.
The problem was that the form was submitting when I clicked the button. The solution was to change the input type to <button value="Submit" onclick="test()">.
The next problem was that python was returning FieldStorage(None, None, [MiniFieldStorage('text', 'blahblah')]). The solution was to access the value by using print (data["text"].value)
I have an html form and I want to use python to send the information from the form to an sqlite database file. Right now I am trying to do it with cgi. I don't need anything fancy. Here is my code:
html:
<!DOCTYPE HTML>
<html>
<head>
<title>Sample page to test fill_web_form.py</title>
</head>
<body>
<p1><strong>SAMPLE PAGE TO TEST FILL_WEB_FORM.PY</strong></p1>
<!--test form-->
<form action="send_form_to_db.py" method="post">
Form to be tested:<br>
<input type="text" name="test_form"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
python:
# send_form_to_db.py
# sends data from html form to database
# import statements
import cgi
import sqlite3
cgitb.enable()
form = cg.FieldStorage()
data = form.getvalue('test-form')
conn = sqlite3.connect('sample.db')
conn.execute("INSERT INTO test_table [test_column] VALUES (data)")
conn.commit()
conn.close()
When I run this the web browser doesn't run the python code, it just displays it as text.
Right now I'm just trying to do this in the simplest way possible without implementing things like Django.
Minor detail: change form = cg.FieldStorage() to form = cgi.FieldStorage().
Note: i in cgi.