FLASK - TypeError: 'ImmutableMultiDict' [duplicate] - python

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 1 year ago.
So I am doing a side project for my self, trying to learn.
Framework:
Flask
pandas
csv
raspberry 4
Goal:
to import a csv or xlsx file into a html form and print it out on the html page.
this is what I have so far:
when I import the file, I get the following.
TypeError: 'ImmutableMultiDict' object is not callable
Python Code:
def read_csv(filein):
filein = pd.read_excel('file.xlxs')
print(filein)
#app.route('/import_form', methods=['POST', 'GET'])
def import_form():
if request.method == "POST":
filein = request.files()
print(filein)
#return redirect('/thankyou.html')
else:
return 'something is wrong'
HMTL Code:
<form action="import_form" method="post" class="reveal-content">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<input name="filename" type="file" accept=".csv, .xlsx" class="form-control" id="filename" placeholder="filename" required >
</div>
</div>
<button type="submit" class="btn btn-default btn-lg">Send</button>
</div>
</form>

The error is because you can't use .files() files is not a function, so it isn't call able.
The right way to do that what you want is :
request.files["filename"]
You may visit here for more information.

Related

Keep getting HTTP 405 Method Not Allowed error when trying to POST form data with Flask

I am trying to capture HTTP form data using Python and Flask, but I keep getting "method not allowed" error. I have been trying to figure out why for some time with no luck. Here is what my code looks like:
#app.route("/add_recipe")
def addrecipepage():
if request.method=="post":
print ("Successful post request") # Just testing if code is working so far
return render_template("add_recipe.html")
and the HTML code:
<form id="contact" action="browseAll" method="post">
<div class="row">
<div class="col-md-6">
<fieldset>
<input name="name" type="text" class="form-control" id="name" placeholder="Recipe Name..." required="">
</fieldset>
<div class="col-12">
<textarea name="demo-message" id="recipeText" placeholder="Enter Ingredients & Instructions Here" rows="15"></textarea>
</div>
<div class="col-md-12">
<button type="submit" id="form-submit" class="button">Add The Recipe!</button>
<button id="uploadPhotoButton">Upload A Photo!</button>
</div>
</form>
When I click on the submit button, I get a HTTP 405 Method Not Allowed error. Anybody have any ideas as to why after looking at this? "browseAll" is another HTML page that I created an endpoint for in my app.py file. The same error gets thrown even if I don't specify an action though.
You are doing a POST (your form has method = "post") but your route does not have a post method attached to it. When you define a route without attaching a method, it defaults to GET. You need to do this
#app.route("/add_recipe", methods =['GET', 'POST'])

Bootstrap 4 input field not sending value to server (python, flask, GAE)

I can't get an input field in a form to send a value to the server. (I'm using flask + python on Google App Engine).
Please excuse me if this is a rookie question...
Part of my html template file:
<form class="form-inline" action="/rm_list" method="POST">
<div class="row" >
<div class="col-span-6">
<fieldset>
<input class="form-control form-control-lg" type="text" name="searchtext" placeholder="Product...">
<input name="text1">
<button class="btn btn-primary" type="submit"><i class="material-icons w3-text-black" >search</i></button>
</div>
...
...
some radio buttons
So I dumped the POST data to the terminal to debug:
my_data = request.form
for key in my_data:
print ('form key '+key+" "+my_data[key])
After trying different solutions, I found that the culprit is the type="text" attribute.
I could see the value of the simple text1 input, but the value from the searchtext input just wasn't in the received data :-(
If I remove "type="text" as follows:
<input class="form-control form-control-lg" name="searchtext" Placeholder="Product...">
then the searchtext field is received Ok by the server.
Any ideas what I'm doing wrong?
Thanks!
It seems to me that your field is simply missing the value attribute. – Anonymous

Python 3 Flask - 404 Page Not Found Error [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Why use Flask's url_for?
(1 answer)
Closed 3 years ago.
I'm new to Flask and followed this walkthrough but am running into an issue. I want a user to be able to input text in a text field on the index.html page, hit the submit button, and take them to trader.html page. I'm running into a 404 Page Not Found error with my below code when the button is hit, but I'm not sure where I'm going wrong? The URL bar shows the correct /trader.html address after the button is hit, but getting the 404 error page.
The 2 answers I found on SO for similar issues didn't work here as they mentioned that there needed to be a separate app.route to navigate them to the correct second page, but I already have that set up in my code???
app.py
from flask import Flask, request, jsonify, render_template
#app.route('/', methods = ['GET'])
def hello():
return render_template('index.html')
#app.route('/trader', methods = ['POST'])
def trader_page():
the_stock=request.form['inputted_stock']
return render_template('trader.html')
index.html
<h1 style="color: #4485b8;">Welcome to the live stock trader!</h1>
<p>Select a stock ticker below to begin testing:</p>
<form action="/trader.html" method="POST">
<option value="AAPL">AAPL</option>
<option value="ABBV">ABBV</option>
<option value="ABT">ABT</option>
</select><br /><br />
<table>
<tr><td>Enter Stock Ticker</td><td><input type="text" name="inputted_stock" /></td></tr>
</table>
<input type="submit" value="Submit"/></form>
<p></p>
<table class="editorDemoTable" style="vertical-align: top;">
<thead></thead>
</table>
trader.html
<h1 style="color: #4485b8;">{{inputted_stock}} trader!</h1>
<p>Begin testing...</p>
The path for your trader_page handler is just "/trader". So that's what you need to use in the form action.
<form action="/trader" method="POST">
Even better, use url_for to generate the URL:
<form action="{{ url_for('trader_page') }}" method="POST">

Flask Bad Request Error; ocurring because of multiple POST requests [duplicate]

This question already has answers here:
Why dict.get(key) instead of dict[key]?
(14 answers)
Closed 4 years ago.
<form method = "POST">
<div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
<div class="box">
<input type="text" name="image-url" placeholder="Image URL Link"style="color:black" required="required" value = "new"/>
<textarea cols=80 rows=4 style="color:black" name = "description" placeholder="Place your description here" value = "new"></textarea>
<button type="submit">Upload</button>
</div>
</div>
</form>
{% for i in range(amount_of_images) %}
<div class=" col-lg-4 col-lg-4 col-lg-4 col-lg-4">
<div class="box">
<img src="{{image[i]}}" alt="view" width = "300" height = "300"/>
<form method = "POST">
<textarea cols=80 rows=4 style="color:black" name = "update-description" value = "update">{{description[i]}}</textarea>
<button type="submit">Update Description</button>
</form>
Above is my HTML/Jinja Code
#app.route("/gallery-manager", methods = ["GET", "POST"])
def gallery_manager():
if request.method == "POST":
if(request.form["image-url"] and request.form["description"]) is not None:
model.add_new_image(request.form["image-url"], request.form["description"])
id, image, description, amount_of_images = model.get_gallery()
return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)
if request.form['update-description'] is not None:
print("hello")
id, image, description, amount_of_images = model.get_gallery()
return render_template("gallery-manager.html", image = image, description = description, amount_of_images = amount_of_images, id = id)
Above is my Python/Flask Code...
The issue, when I click on the update-description submit button, aka the second POST being handled in the html code, I get a 400 error
Bad Request
The browser (or proxy) sent a request that this server could not understand.
I realized that this error occurs when one of the POST fields are empty and can not be found. I understand that this happens because when I click the second POST submit button, it runs through the first POST check (request.form["image-url"] etc and finds that it is satisfied therefore wanting to run that code, but cant because update-description is still empty. How do I avoid this.
In other words how do I handle multiple POST methods.
Thank you,
This is because you are missing the action section in form where the form should send the request
<form action="/whereYouWantToSendRequest" method="post">
add your url endpoint by replacing this in the above
whereYouWantToSendRequest
here are the two request
<input type="text" name="image-url" value = "new"/>
<input type="text" name="update-description" value = "update"/>
and to figure out which request
if request.form["image-url"] == "new":
somethinggg
elif request.form["update-description"] =="update":
sommmm

Flask: how to send values by get method in temples? [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I have a html code such as:
<form action="/labeling?id={{id}}" method="get" target="hiddenFrame">
<input type="radio" name="options" value="x" onchange="this.form.submit()"> X<br>
<input type="radio" name="options" value="y" onchange="this.form.submit()"> y<br>
</form>
and the python code that gets the id of the element:
#app.route('/labeling', methods=['GET', 'POST'])
def labeling():
value = request.form['options']
d_id = request.form['id']
but it does not sent the values of id in the GET request? why?
Your id param is not form param, try:
d_id = request.args['id']
or better use id as method param:
<form action="{{ url_for('labeling', id=id) }}" method="POST" target="hiddenFrame">
<input type="radio" name="options" value="x" onchange="this.form.submit()"> X<br>
<input type="radio" name="options" value="y" onchange="this.form.submit()"> y<br>
</form>
#app.route('/labeling/<int:d_id>', methods=['GET', 'POST'])
def labeling(d_id):
value = request.form['options']

Categories

Resources