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

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">

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'])

HTML button to next page is not working in Flask development server

I have two pages index.html having code as following
<form action="/" method="POST">
<div class="form-group">
<textarea class="form-control" name="text" placeholder="Enter Text" rows="6"></textarea>
</div>
<input type="submit" class="btn btn-primary">
</form>
<button>
</div>
<div class="col-md-3 col-sm-1"></div>
<input type=button onClick="location.href='upload.html'"
value='click here'>
</div>
<button>
It has js and css in head. As you can see there is a button to go to upload.html page, which contains code to upload file as following
<body>
<h1>File Upload</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file" accept=".pdf"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
If I open index.html page in a browser and click on click here button it redirects me to the intended page, But when I run Flask app and try to click on this button it gives 404 error. Right now I haven't created any Flask method for this file. I have tried to add absolute path to upload.html file and ./upload.html and almost every method to create a button mentioned here. I also tried to redirect it to a blank page and index.html itself but every time the error is same. It is only giving me error with local HTML files if I give an address of some website it redirects me to it. Can someone help me with what I need to do to make it work?
I think you need to create a route and point the input element to the new page. Right now that won't work within Flask because the app does not "see" the upload.html page.
so you would first create a route in your routes.py or app.py
#app.route(methods=["GET", "POST"])
def file_upload():
return render_template("upload.html")
and then in your index.html you would point the input to this route:
<input type=button href="{{url_for('file_upload')}}" value='click here'>
just remember, url_for as a function points to the function name, not the html template itself. So here you call url_for which in turn calls file_upload which in turn renders upload.html.

FLASK - TypeError: 'ImmutableMultiDict' [duplicate]

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.

Flask access json data and embedding it in a <img> tag [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Link to Flask static files with url_for
(2 answers)
Closed 1 year ago.
I have the following flask route
#app.route("/rec_demo")
def rec_demo():
print("de lokos")
response_data = {"rec_one": "pic_trulli.jpg"}
return render_template("demografico.html", data=response_data)
And I try to access the rec_one to display it as an image
<div id='info_section'>
<img src={{ data.rec_one }} alt="Girl in a jacket" width="500" height="600">
</div>
But when I check the web on a live server the src doesn't resolve to the url I passed. If instead I had
<div id='info_section'>
{{ data.rec_one }}
</div>
I can see the url value as text in my webpage
You should be putting quotes around your flask call -- IE
<img src="{{ data.rec_one }}" alt="Girl in a jacket" width="500" height="600">
This will cause problems not only with the flask output .. But the browser's interpretation as well.

Why does Python Flask throw a HTTP 404 error

It is several years since I have used Flask, starting on a new project.
I get a HTTP 404 error. The requested URL is not found??
The index and the requested URL are both in the templates folder.
I don't understand why it is throwing a HTTP 404 error??
Any pointers appreciated, thanks.
Clive
I have a code snippet in routes.py.
#app.route('/service_response', methods=['GET','POST'])
def service_response():
servicesql = "SELECT * FROM DASHBOARD_SERVICE_RESPONSE"
data = list(conn.execute(servicesql))
return render_template('service_response.html', service_response=servicesql)
In index.html I have:
<div class="form chartdisplay" >
<div class="form-heading">BCC Report Period</div>
<br>
<div class="form-group"; class="height-auto";>
<table>
<thead>
<iframe src="service_response.html" width="90%" height="90%"></iframe>
</thead>
</table>
</div>
</div>
Your code points to src="service_response.html" while what you want to do is to point to /service_response which will render the 'service_response.html' jinja template.

Categories

Resources