Use flask to get an image uploaded on a html form - python

I am new to flask and i am using google colab to do some basic flask stuff.
I have a html-form:
<!DOCTYPE html>
<html>
<body>
<h1>The input accept attribute</h1>
<form action="#" method="post">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" enctype="multipart/form-data" accept="image/*">
<input type="submit" value="submit">
</form>
</body>
</html>
Then i have FLASK code as to get the uploaded image:
#app.route("/test", methods=['POST','GET'])
def test_page():
if request.method == "POST":
image = request.files.get('img', '')
image = request.form["img"]
print("img ",image)
return "<h1> yo! </h1>"
else:
return render_template('index.html')
DEBUGGING RESULTS:
#debug
print('request.method', request.method)
print('request.args', request.args)
print('request.form', request.form)
print('request.files', request.files)
request.method POST
request.args ImmutableMultiDict([])
request.form ImmutableMultiDict([('img', 'cat.jpg')])
request.files ImmutableMultiDict([])
The problem is i want to doo some processing on the uploaded image but request.files return nothing and request.form just gives me the name. Please any help will be appreciated.

The enctype attribute should be defined within the form tag, not within the input element. Here, the formatting of the data is defined when the form is transmitted.
This could fix the problem.
<form method="post" enctype="multipart/form-data">
<label for="img">Select image:</label>
<input type="file" id="img" name="img" accept="image/*">
<input type="submit" value="submit">
</form>

Related

How to write in my excel file by taking data from an HTML form under the previous data in next rows?

This is my basic flask route
#app.route('/home/form', methods=('GET','POST'))
def form():
if request.method == 'POST':
machine = request.form['machine']
df = pd.DataFrame([[machine]], columns=["Machine"])
with pd.ExcelWriter('P:\\Rohaan\\LATEST WEBSITE\\sample.xlsx') as writer:
df.to_excel(writer)
if not machine:
flash('Title is required!')
else:
return redirect(url_for('home'))
return render_template('form.html')
if __name__ == "__main__":
app.run(debug=True)
My form.html that I retrieve data frame
HTML Code
<form method="post">
<label for="Machine">Machine</label>
<br>
<input type="text" name="machine"
placeholder="Message machine"
value=''></input>
<br>
<label for="content">Message Content</label>
<br>
<textarea name="content"
placeholder="Message content"
rows="15"
cols="60"
></textarea>
<br>
<button type="submit">Submit</button>
</form>
Currently getting this result using this code
My question is:
Why the incoming data override my previous data?
Currently getting this result using this code
#app.route('/home/form', methods=('GET','POST'))
def form():
if request.method == 'POST':
machine = request.form['machine']
df = pd.DataFrame([[machine]], columns=["Machine"])
with pd.ExcelWriter('P:\\Rohaan\\LATEST WEBSITE\\sample.xlsx') as writer:
df.to_excel(writer)
if not machine:
flash('Title is required!')
else:
return redirect(url_for('home'))
return render_template('form.html')
if name == "main": app.run(debug=True)
According to documentation you should specify mode = "a" if you want to append and not override (default is mode = "w") inside ExcelWriter, but if it is actually supported is probably dependent on the chosen excel engine.
HTML Code
<form method="post">
<label for="Machine">Machine</label>
<br>
<input type="text" name="machine"
placeholder="Message machine"
value=''></input>
<br>
<label for="content">Message Content</label>
<br>
<textarea name="content"
placeholder="Message content"
rows="15"
cols="60"
></textarea>
<br>
<button type="submit">Submit</button>
</form>

Flask, why does request.form runs error 400?

I am trying to extract text from the following HTML code:
#app.route("/", methods=['GET', 'POST'])
def home():
if request.method == 'POST':
H_desiderata = float(request.form.get('H_desiderata')) #THIS CAUSES THE ERROR
return render_template('form1.html')
HTML below:
<body>
<h2>Brioche Recipe</h2>
<form>
<div class="grid-container">
<div class="grid-item">
<label class="text" for="H_desiderata">
H_desiderata:
</label><be>
<input type="number" id="H_desiderata" name="H_desiderata1"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
Before putting it into a grid it worked:
old working code:
<form>
<label for="H_desiderata">H_desiderata:</label><br>
<input type="number" id="H_desiderata" name="H_desiderata"
value={{val_H_desiderata}} min="1" max="99" step="1"><br>
How should I adapt request.form to return the value within the input box?
There is so much wrong with your code, but let's start with this:
request.form is empty when request.method == "GET. So. request.form['H_desiderata'] will give a key error.
Move that to the POST section of your view. Also, use request.form.get('H_desiderata', -9999999) in case it's not defined.
UPDATE:
OK, now try:
if request.method == 'POST':
print(request.form)
print(request.form.get('H_desiderata'))
print(float(request.form.get('H_desiderata')))
H_desiderata = float(request.form.get('H_desiderata'))
Then, you are going to want:
return render_template('form1.html', val_H_desiderata=H_desiderata)
UPDATE2:
Your <form> tag is malformed. Try:
<form action="/" method="post">
UPDATE3:
You change the name of the input, so change to: request.form.get('H_desiderata1')

Django upload file using get method

I would like to upload a single file or files at a time using get method.
I have already done with the post method and working fine. But for some reason i would like to do the file upload using get method using command line.
The below code is which i have already tried to get the string from get method and i can able to get the varValue as string. But i would like to get the file using get method.
def home(request):
if request.method == 'GET':
varValue = request.GET.get('myfile', '')
print(varValue)`
HTML code:
<form method="GET" enctype="multipart/form-data">
<input type="file" name="myfile" accept="image/*" multiple>
<button type="submit">Upload files</button>
Try This Method
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
A dictionary-like object containing all uploaded files. Each key in FILES is the name from the . Each value in FILES is an UploadedFile.
<form method="GET" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload File</button>
</form>
Found the solution using the post method itself. By skipping the csrf token we can do the command line script execution method.
Python views.py code below
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def home(request):
if request.method == 'POST':
uploaded_file = request.FILES['myfile']
fs = FileSystemStorage()
name = fs.save(uploaded_file.name, uploaded_file)
print(name)
return render(request, "home.html")
HTML code:
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="myfile" accept="image/*" multiple>
<button type="submit">Upload files</button>
</body>
python code for file upload using post method:
import requests
files = {'myfile': open('d:\\20190819-140341-627485.png','rb')}
y = requests.post("http://127.0.0.1:8000",files=files)

Flask giving error 400 on file upload

I have the following
<form action="classify_upload" method="post" id="upload-form">
<input type="file" name="imagefile" id="imagefile"/>
<input type="submit" />
</form>
And in my flask webapp I have the following rule:
#webapp.route('/upload', methods=['POST'])
def upload():
try:
imagefile = flask.request.files['imagefile']
...
except Exception as err:
...
But I am getting a error 400: bad request, which from my googling tells me Flask can not find the file under the key 'imagefile' which is the name of the input in the html. Any ideas why it is not finding it?
Turns out I need to include the enctype in the form, so the html should be
<form action="classify_upload" method="post" id="upload-form" enctype="multipart/form-data">
<input type="file" name="imagefile" id="imagefile"/>
<input type="submit" />
</form>

flask - url with searched word

I want to ask how to make my urls to include the worh that I searched. Something like this:
http://host/filter?test
My code:
#app.route('/filter', methods=['POST', 'GET'])
def filter():
if request.method == 'POST':
if str(request.form['search_string']) <> '':
api.queryMessage(request.form['search_string'])
return render_template('main.html', search_string=search_string)
And my template, main.html:
<form name="filters" action="{{ url_for('filter') }}" method=post id="filters">
<div style="position: absolute; top:100px; left:300px">
<p>Search string: <input type=text size=80 title="Match all of the words" name=search_string value="{{search_string}}"></p>
<input type=submit value=Filter/Search onclick=loopSelected();>
<input type="hidden" name="chosen" id="chosen" value="{{chosen}}" />
</div>
</form>
You're now using POST request. Use GET request, so browser will put your form values to URL.
in HTML form set method="GET":
<form name="filters" action="{{ url_for('filter') }}" method="GET" id="filters">
You'll get URL in the following form:
http://host/filter?search_string=test&chosen=<id>&<some other trash>
In Flask use request.args instead of request.form:
if request.method == 'GET':
if request.args.get('search_string'):
...

Categories

Resources