Insert or write data to .txt file with flask - python

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()

Related

get html textbox values as input to python file to print the returned value

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

Method not allowed for requested URL

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

Run python script from html page Flask

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.

Files not uploading in flask

I am trying to upload files into server using flask but the files are *not uploading.
I am new to python and flask.
import os
from flask import *
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
#app.route('/')
def index():
return render_template('upload.html')
#app.route('/upload', methods = ['POST'])
def upload():
target = os.path.join(APP_ROOT, 'uploads/')
if not os.path.join(target):
os.mkdir(target)
for file in request.files.getlist('file'):
print(file.filename)
destination = '/'.join([target, file.filename])
print(destination)
file.save(destination)
return render_template('successful.html')
if __name__ == '__main__':
app.run(debug = True)
upload.html
<!DOCTYPE html>
<html>
<head>
<title> Upload file </title>
</head>
<body>
<form id="upload-form" action="{{ url_for('upload') }}"
method="post" enctype="multipart/form-data">
<input type="file" name="cssv_file" multiple>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Change this line
if not os.path.join(target):
to
if not os.path.isdir(target):

Flask HTTP Server won't allow upload of multiple files at once

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/home/ubuntu/shared/'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file:
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method="post" enctype="multipart/form-data">
<p><input type="file" multiple="" name="file">
<input type="submit" value="Upload">
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, debug=False)
If I launch the server and select 2 files through the form, it only uploads one of them. I tried for serveral hours and read about 15 topics on it, including the documentation.
Nada :c
Edit:
I also tried changing:
file = request.files['file']
into:
file = request.files.getlist('file')
would not work either. The type of quotes have no effect either. Wasn't that a python3 thing?
import os, ssl
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/home/ubuntu/shared/'
certfile = "/home/ubuntu/keys/fullchain.pem"
keyfile = "/home/ubuntu/keys/privkey.pem"
ecdh_curve = "secp384r1"
cipherlist = "ECDHE-ECDSA-AES256-GCM-SHA384 ECDHE-ECDSA-CHACHA20-POLY1305"
sslcontext = ssl.create_default_context(purpose=ssl.Purpose.CLIENT_AUTH)
sslcontext.options |= ssl.OP_NO_TLSv1
sslcontext.options |= ssl.OP_NO_TLSv1_1
sslcontext.protocol = ssl.PROTOCOL_TLSv1_2
sslcontext.set_ciphers(cipherlist)
sslcontext.set_ecdh_curve(ecdh_curve)
sslcontext.load_cert_chain(certfile, keyfile)
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
my_data = request.files.getlist('file')
my_pass = request.form['password']
if my_data and my_pass == 'yakumo':
for file in my_data:
my_handler(file)
return redirect(url_for('index'))
return """
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file multiple name=file>
<input type="password" name="password" value="">
<input type=submit value=Upload>
</form>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
def my_handler(f):
filename = secure_filename(f.filename)
f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8000, ssl_context=sslcontext, threaded=True, debug=False)
I made a very rookie mistake and didn't for-loop over the multiple files being uploaded. The code here was tested without issues with 4 simultaneous file uploads. I hope it will be useful to someone.
Edit: Code updated with some sweet TLS_1.2 and a password field. Enjoy a reasonably secure upload server. Password is transferred over HTTPS.

Categories