Apologies in advance if this is easy but I cant figure it out.
I have a flask app which takes a txt file as an input on a webpage. I then want to run some python scripts on it and then export it back to the website user. I'm pretty much there but I just cant figure out how to get the txt file into python.
HTML
<div class="file_input">
<form action="." method="POST">
<input type="file" name = "txt_file">
<input type="submit" name="submit_form">
</form>
</div>
Python (Flask)
#app.route('/landing')
def landing():
return render_template('index.html',
PageTitle = "Landing page")
#app.route('/', methods = ['POST'])
def test():
text_file = request.form['txt_file']
book_io = open(text_file, "r", encoding = "UTF-8")
book_str = book_io.read()
book_str
return book_str
This isn't working as it's just taking the inputted text file as a string and then printing out this string.
I basically need to know how to import the text from the file into python, but I cant figure out how.
Thanks a lot in advance!!
Related
I am very new to web-development (first project) and have started playing around in Flask. The other day I made a very simple temperature converter which I was running on my local host. The page had a form input to type a value, two radio buttons with Fahrenheit and Celsius to define the system of the value, then a convert button. Here is a screenshot:
Here is my Flask code ("main.py"):
from flask import Flask, render_template
from flask import request, redirect
import temperature, convert, determine_system
app = Flask(__name__)
#app.route('/')
def html():
return render_template('index.html')
#app.route('/convert', methods = ['POST'])
def convert():
temp = request.form['temperature']
system = request.form['system']
new_temp, destination_system = determine_system.determine_system(temp, system)
return render_template('convert.html', temp=temp, system=system, new_temp=new_temp, destination_system=destination_system)
if __name__ == "__main__":
app.run()
As you can see, the first function called "html()" initially renders the "index.html" file and the function "convert()" is executed upon clicking the "Convert" button. There are a few other functions that I have in other .py files in the directory that convert the number to the new system.
Here is the body of my "index.html" code:
<body>
<div id="banner">
<h1>Temperature Converter</h1>
<p class="lead">Use this tool to convert temperature between measurement systems</p>
</div>
<form action="/convert" method="post" target="dummyframe">
<input type="text" name="temperature"></input>
<input type="radio" name="system" value="Fahrenheit">Fahrenheit</input>
<input type="radio" name="system" value="Celsius">Celsius</input>
<br>
<br>
<input type="submit" value="Convert"></input>
</form>
</body>
</html>
To display the converted temperature on the webpage, I currently have another HTML file called "convert.html" in my templates directory that is an exact copy of the "index.html" file, except it includes the following three lines of code in the body after the :
div id="output"></div>
<p class="output-statement">{{ temp }}° {{ system }} is equal to {{ new_temp }}° {{ destination_system }}</p>
</div>
In my Flask file ("main.py), I instruct the "convert()" function to render the "convert.html" template which includes the output statement in the code above:
return render_template('convert.html', temp=temp, system=system, new_temp=new_temp, destination_system=destination_system)
This then results in the following (notice the new web address):
I suspect that my way of outputting the converted temperature by redirecting to a new HTML file and web address (http://127.0.0.1:5000/convert) is not efficient or even the correct way of showing accomplishing this. What is the proper way to output something like this? Is there something I can add to the "index.html" file that would allow me to get rid of the "convert.html" file completely? If so, what would I change the last line of the "convert()" function in my Flask ("main.py") file to?
Thank you in advance and any links with more information on this concept are very appreciated!
Yes there is a more efficient solution where you do not need the convert.html:
This is what you will want in your main route. (note: I suggest renaming your route function to something like "index" or "temp" other than "html")
#app.route('/', methods=["GET","POST"])
def html():
output = ""
if request.method == "POST":
temp = request.form['temperature']
system = request.form['system']
new_temp, destination_system = determine_system.determine_system(temp, system)
output = f"{ temp}° { system } is equal to { new_temp }° { destination_system }"
return render_template('index.html', output=output)
Make sure to import request. using: from flask import request
and in your index.html you will now have:
<div id="output"></div>
<p class="output-statement">{{output}}</p>
</div>
And make sure to change form action to action="#" or action=""
I've created a python script that loads an excel file up from my computer and, after working with the information inside it using openpyxl, saves a new excel file. The script works on my computer. For longevity purposes, I want to make the script into a website, using pythonanywhere or something similar to it (incorporating flask seemed like the best way to convert my script into a website). However, I am having trouble finding a way to accept a file from the user, as I have very little experience using flask. Here's the code I currently have that creates a "choose file" button and a "process file" button:
app = Flask(__name__)
app.config["DEBUG"] = True
#app.route("/", methods=["GET", "POST"])
def file_summer_page():
if request.method == ("POST"):
input_file = request.files["input_file"]
wb_master = load_workbook(input_file)
output_data = main(wb_master)
response = make_response(output_data)
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
return response
return '''
<html>
<body>
<p>Load up the automated eval that MS Forms gives you:</p>
<form method="post" action="." enctype="multipart/form-data">
<p><input type="file" name="input_file" /></p>
<p><input type="submit" value="Process the file" /></p>
</form>
</body>
</html>
'''
Bear with me. Again, I haven't used Flask much, but this is my idea so far. Main(wb_master) essentially calls the script I made, so that it could hopefully run. At the moment, this returns the following error: "AttributeError: 'SpooledTemporaryFile' object has no attribute 'seekable'." In this case, I don't really know what it means, but I assume it is due to the fact that I am not reading the file correctly. Any help would be greatly appreciated!
I am new and have spent hours trying to setup a form in Flask for Python 3.5. I want the user to be able to enter a temperature setpoint and click submit button, and have the value stored in a variable.
I have this code in a template file called index.html:
<html>
<body>
<p><font size="6">Jewell Hot-Tub Controller</font>
<br>
<font size="4">Water Temperature: {{water_temp}}</p>
<br>
<font size="4">Set Point: {{set_point}}</p>
<br>
<font size="4">Enter New Set Point:</p>
<form class="form-newtemp" method="get" action="/ChangeTemp">
<input type="text" id="new_sp" name="new_sp" size="5" placeholder="New Temp." required>
<input id="1submit" type="submit">
</form>
</body>
</html>
and this code in the "flask-test.py" file:
from flask import Flask, render_template, request
app = Flask(__name__)
app.debug = True
#app.route('/')
def index():
return render_template('index.html', water_temp='12345')
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
Entering "27" in the textbox sends the browser to a 400 Bad Request page at:
http://127.0.0.1:5000/ChangeTemp?new_sp=27
Why does this change a bad request error, rather than returning the value? The tutorials I saw used POST, but I used GET, does this require different syntax?
Also, please let me know if anything is messy, or done wrong.
Thank you!
EDIT: I also tried "request.form.get('new-sp', new)" and this causes a 500 internal server error.
multiple ways to fix your problem. i guess the fastest way is:
<form class="form-newtemp" method="post" action="{{ url_for('process')}}">
and then
#app.route('/ChangeTemp', methods=['POST])
def process():
new = request.form['new_sp']
return 'New set point is:' + new
or you can go with not changing your template and:
#app.route('/ChangeTemp', methods=['GET'])
def process():
new = request.args.get('new_sp')
return 'New set point is:' + new
This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 5 years ago.
Essentially what I am trying to do :
I have a simple HTML page with a Textarea to input a bunch of text, my use case is a single code on each line like below:
1234
5678
1456
etc.
Ideally I want to take that into Python and be able to work with the data and return the results. So lets start simple and say take each line as a separate entry and run it against a function to add the word "Hi" in front of it So the results are:
Hi 1234
Hi 5678
etc.
So far have this working example I found but I tend to break it anytime I try something.
Html:
<!DOCTYPE html>
<html lang="en">
<body>
<h1>Enter some text</h1>
<form action="submit" id="textform" method="post">
<textarea name="text">Hello World!</textarea>
<input type="submit" value="Submit">
</form>
</body>
</html>
Python:
From flask import Flask, request
app = Flask(__name__)
#app.route('/')
def main_form():
return '<form action="submit" id="textform" method="post"><textarea name="text">Hello World!</textarea><input type="submit" value="Submit"></form>'
#app.route('/submit', methods=['POST'])
def submit_textarea():
return "You entered: {}".format(request.form["text"])
if __name__ == '__main__':
app.run()
Example :
i try to extract the textarea to a string and then return that back to the page with :
x = format(request.form["text"])
return x
Any help or guidance would be appreciated!
You can access and store the text from textarea with the following lines :
#app.route('/submit', methods=['POST'])
def submit_textarea():
# store the given text in a variable
text = request.form.get("text")
# split the text to get each line in a list
text2 = text.split('\n')
# change the text (add 'Hi' to each new line)
text_changed = ''.join(['<br>Hi ' + line for line in text2])
# (i used <br> to materialize a newline in the returned value)
return "You entered: {}".format(text_changed)
I'm trying to read and then write from a plain text in Django.
Basically I want to open a file, get an specific word and then change it for whatever else.
Here's what I have:
def address_L1():
file = open("interfaces.txt","r")
content = file.read()
file.close()
address = re.findall('address\s(.*?)\s',open('interfaces.txt','r').read())
if address:
print address[0]
else:
print 'no Address found!'
return address[0]
Here I'm opening a file and search for the word next to address, which is 192.168.5.5 and works perfect.
def get_interfaces(request):
address = str(address_L1())
if 'address' in request.POST:
write_template(request)#This is for my writing function
return render(request, 'interfaces.html', {'address':address})
Here I'm passing to template what's in address I mean, 192.168.5.5 will be shown in template.
<form method="post" action="">{% csrf_token %}
<label for="your_name">Address: </label>
<input id="your_name" type="text" name="address" value="{{ address }}">
<br>
<input type="submit" class="btn btn-success btn-xs" value="Guardar Cambios">
</form>
Here is my html were I'm displaying my variable, There's an input Address that will show my 192.168.5.5 or whatever is in address variable.
Everything works ok until now.
Now I'm trying to write to my plain text.
def write_template(request):
if request.method == 'POST':
get_address = address_L1()
change_address_L1 = request.GET.get("address", None)#Doing something with my input field in template
filedata= None
with open('interfaces.txt', 'r') as f:
filedata = f.readlines()
filedata=filedata.replace(get_address , change_address_L1)
with open('interfaces.txt', 'wb') as f:
f.writelines(filedata)
return render(request, 'interfaces.html')
Here basically what I want to do is get what's in my input address and replace for whatever I enter, I mean when I run my code I ll see my input with 192.168.5.5 I want to delete that value and enter 192.168.0.0 and change my value. When I try so I get this error:
'list' object has no attribute 'replace'
How can I solve this? how can I successful write in my plain text properly?
What am I doing wrong? thanks in advance!!
As the error says, filedata is a list. That's because f.readlines() gives you a list, where each element is a line in the file.
If you want the whole thing as a single string, do f.read() instead.