How do we execute or run python code after the submit button is pressed the html form that I created in index.html.
The following is the index.php code:
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="nopol">
<input id="print_nopol" type="submit">
</form>
<?php
system("python /home/pi/python-epson-printer/epson_printer/testpage.py");
?>
</body>
</html>
and below is a python flask application script with the name app.py :
from flask import Flask, request, render_template, Response, redirect, url_for
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['nopol']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == "__main__":
app.run(host='192.168.1.2', port=8080, debug=True)
This python code has a function to insert data into a .txt file and here is the python script path:
/home/pi/server_print/print.py
Thank you for your help.
Related
I am trying to get value from textbox on html webpage and print it in test.py file.
There are three files:
app.py
test.py
index.html
can someone please help?
app.py:
from flask import Flask, render_template, request
app = Flask(__name__)
#app.route("/")
def main():
return render_template("index.html")
#app.route("/", methods=["GET","POST"])
def get_provider():
dp = request.form["provider"]
dp_lower_case = dp.lower()
return dp_lower_case
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ALMA PROCESS FLOW</title>
</head>
<body>
<form method="POST">
<label style="position:relative; left:5px; bottom:15px;"> Data Provider:</label>
<input name ="provider" type="text"">
<input type="submit" value="Generate"/>
</form>
</body>
</html>
test.py
from app import get_provider
provider = app.get_provider()
print(provider)
When you don't specify a method for a route, it defaults to a GET. This means that your code currently has 2 handlers for when your home page is loaded.
Since your form is doing a post, drop the 'GET' in the methods list i.e. change
#app.route("/", methods=["GET","POST"])
to
#app.route("/", methods=["POST"])
Better yet, you should combine everything i.e. change your code to
#app.route("/", methods=["GET","POST"])
def main():
# When it is a GET
if request.method == "GET":
return render_template("index.html")
# When it is a POST (user has submitted your form)
elif request.method == "POST":
dp = request.form["provider"]
''' Alternatively, you can use
dp = request.values.get("provider")
I prefer it because this way, I can provide a
default value in case the form parameter has no value i.e
dp = request.values.get("provider", "default provider")
'''
dp_lower_case = dp.lower()
return dp_lower_case
I'm trying to execute a def/python script from flask, when clicked on button... but can't seem to figure it out.
Here's my Python Code
from flask import Flask, redirect, url_for, render_template, request
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
def contact():
if "open" in request.form:
print("Test")
elif "close" in request.form:
print("Test 2")
return render_template('contact.html')
if __name__ == "__main__":
app.run(debug=True)
And here is my HTML Code
<html>
<head>
<title>Home page</title>
</head>
<body>
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Test</h1>
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
{% endblock %}
</body>
</html> ```
I don't know what is in {% block content %} but you need to have a form in order to call backend where you provide the url route that you want to call and the method you want to use (usually with forms it's POST). Also in the /contact endpoint you need to provide #app.route('/contact') and that it would accept POST request #app.route('/contact', methods=['POST']). Modify your python and HTML to look like this:
from flask import Flask, redirect, url_for, render_template, request, jsonify
import webbrowser
app = Flask(__name__)
#app.route("/")
def home():
return render_template("index.html")
#app.route('/contact', methods=['POST'])
def contact():
result = False
if "open" in request.form:
result = activate_lamp() # expecting True as a result of function
elif "close" in request.form:
result = deactivate_lamp()
return jsonify({'result': result}) # expecting True as a result of function
if __name__ == "__main__":
app.run(debug=True)
<html>
<head>
<title>Home page</title>
</head>
<body>
<h1>Test</h1>
<form action="{{ url_for('contact') }}" method="post">
<input type="submit" name="open" value="Open">
<input type="submit" name="close" value="Close">
</form>
</body>
</html>
The jsonify will return an object to the front end with default 200 response code. Then you can either do something with it or ignore it. The idea is that in the route you can call other functions, but you must return a valid HTTP response to the front-end, e.g. jsonify, or plain return '', 200 might be enough.
I am trying to upload file from my flask site,but it keeps returning the error
method is not allowed for the requested URL. Even my teacher does not have the answer to this question. According to him he has never seen this error. really appreciate your help
my HTML file is as follows
<!DOCTYPE html>
<html lang="en">
<title> Data Collector App </title>
<head>
<link href="../static/main.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Data Collector</h1>
<form action={{url_for('index')}} method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
Python srcipt is
from flask import Flask, render_template, request, send_file, url_for
import pandas
from werkzeug.utils import secure_filename
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/index')
def upload():
if method == "POST":
file=request.files['file']
file.save(secure_filename("new"+file.filename))
return render_template('index.html')
if __name__ == "__main__":
app.run(debug = True)
Add any allowed methods to a route in the decorator, e.g.
#app.route('/index', methods=['POST', ...])
EDIT:
You should probably also check on the method field of request instead of just method.
if request.method == 'POST':
By default routes only accept the GET method. If you want your route to answer to other methods, pass a custom methods parameter to #app.route as follows
#app.route('/', methods=['GET', 'POST',])
...
#app.route('/index', methods=['GET', 'POST',])
...
Source https://flask.palletsprojects.com/en/1.1.x/quickstart/#http-methods
I've been having this big issue with my python code. I'm trying to set a cookie, and sometimes the cookie gets set, but most of the time it just doesn't. I've been trying to print out the value of the cookie, and quite often (most of the time) it's None. Can anyone please help me find out what I've done wrong? I appreciate all help. Thanks in advance
This is my run.py file
from flask import Flask, request, url_for, redirect, render_template, make_response
import os
app = Flask(__name__)
app.secret_key = os.urandom(16)
#app.route('/')
#app.route('/home')
def home():
return render_template('home.html')
#app.route('/login', methods=['POST'])
def login():
user = request.form.get('username')
password = request.form.get('password')
response = make_response('')
response.set_cookie('id', 'test', domain='127.0.0.1')
return redirect('home')
if __name__ == '__main__':
app.run('127.0.0.1', debug=True)
And below here is my html code. (templates/home.html)
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h1>Please login</h1>
<form method="POST" action="{{ url_for('login') }}">
<input type="text" name="username">
</br>
<input type="password" name="password">
</br>
<input type="submit">
</form>
</body>
</html>
what happens if you change your the part of your code to this
response = make_response(redirect('/home')
response.set_cookie('id', 'test')
return response
I have tried the existing code, but it still fails. My problem is how to insert data into the .txt file using the Flask form.
The following is my app.py code:
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
input_nopol = request.form.get['nopol']
if request.method == 'POST' and input_nopol:
print(listdir)
with open('/home/pi/web-server/nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == "__main__":
app.run(host='192.168.1.2', port=8080, debug=True)
The following is a simple code for the form at index.html in template folder:
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form method="POST">
<input name="text">
<input type="submit">
</form>
</body>
</html>
I am very grateful for the help and solution from all of you.
Update your code as below
index.html
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box">
<input type="submit">
</form>
</body>
</html>
app.py
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['text_box']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == '__main__':
app.debug = True
app.run()
<!DOCTYPE html>
<head>
<title>Hello</title>
</head>
<body>
<form action="" method="POST">
<input name="text_box">
<input type="submit">
</form>
from flask import Flask, request, render_template
from os import listdir
app = Flask(__name__)
#app.route('/')
def my_form():
return render_template('index.html')
#app.route('/', methods=['POST'])
def my_form_post():
input_nopol = request.form['text_box']
if request.method == 'POST':
with open('nopol.txt', 'w') as f:
f.write(str(input_nopol))
return render_template('index.html', nopol=input_nopol)
if __name__ == '__main__':
app.debug = True
app.run()