Why does Python Flask throw a HTTP 404 error - python

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.

Related

Flask app shows only 1 image and does not show other images

I have flask application via python. In my page, there is three images but flask only shows one of them.
I could not figure out where is the problem.
Here is my code.
HTML
<div class="col-xs-4">
<img style="width:40%;padding:5px" src="static/tomato.png"/>
<br>
<button class="btn btn-warning"><a style="color:white;" href="http://127.0.0.1:5000/detect">Tomato Analysis</a></button>
</div>
<div class="col-xs-4">
<img style="width:40%;padding:5px" src="static/grapes.png"/>
<br>
<button class="btn btn-warning"><a style="color:white;" href="http://127.0.0.1:5000/detect">Grape Analysis</a></button>
</div>
PYTHON
#app.route("/main")
def index():
return render_template('gui2.html')
It shows tomato.png but it did not sohws the grapes.png, what is the problem of it and how can I solve it.
Also I am using electron.js. After running python script, I am running nmp start.
The error is output is:
GET /%7B%7B%20url_for('static',%20filename%20=%20'image/corn2.png')%20%7D%7D HTTP/1.1" 404 -
Any help is appreciated...
Thanks
You can change the route main to mainPage. Try below code
#app.route("/mainPage")
def index():
return render_template('gui2.html')
The error message 404 clear tells that the resource you are looking for was not found in the given location. Make sure that the file exists on the path you give. Simply, as tomato.png file is displayed correctly, just make sure that other files are also in the same location as tomato.png
Try opening in Incognito or private browser.

View to Download FileField From Django

I have files which are saved to the MEDIA_ROOT - and I am displaying the file paths as URLs in a table in my UI. I would like for these files to download when the user clicks the link in the table. However, when that happens I get an error because I don't have a URL or View defined to handle this I suppose. Problem is, I'm not really sure where to start - any suggestions. Below is my model, and the .html which displays the table and the link.
models.py
class Orders(models.Model):
...
order_file = models.FileField(upload_to='web_unit', null=True, blank=True)
...
def __str__(self):
return self.reference
index.html
<div class="table-responsive">
<table id="main_table" class="table table-striped table-bordered" cellspacing="0" style="width="100%">
<thead>
<tr>
....
</thead>
<tbody>
{% for orders in orders %}
<tr>
<td>
<!-- Update book buttons -->
<button type="button" class="update-book btn btn-sm btn-primary" style="color: #FFCF8B; border-color: #FFCF8B; background-color: #FFF;" data-id="{% url 'order_update' orders.pk %}">
<span class="fa fa-pencil"></span>
</button>
</td>
....
<td>Download</td> #this is the link
</tr>
{% endfor %}
</tbody>
</table>
When the link in the table is clicked - I'd like for the file to be downloaded - I need help on how to define the URL and the View to make this happen.
This has been marked as a duplicate a few times now - but I don't believe it is. The link that I have been referred to only shows a view. I don't understand how I am to trigger that view using a url since there will be many download links in the same screen. How does the view know which file link I have clicked on? Wouldn't that need to leverage the URL somehow?
First, don't do {% for orders in orders %}; instead do {% for order in orders %}
Then this should work (assuming order_file is the field name you didn't show in the model)
<td>Download</td>

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

How to render template with image in flask?

I'm trying to render a template that uses image using flask but I'm encountering the following error:
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'static'.
I get the following error message on page:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
I already tried to put the images in the same directory as app.py but the images did not appear. I am using flask 1.0.3.
gallery.html:
<body>
<h2>Images Side by Side</h2>
<div class="row">
<div class="column">
<img src="{{url_for('static', filename='resultado_final.png)}}" alt="Resultado final" style="width:100%">
</div>
<div class="column">
<img src="{{url_for('static', filename='resultado_final.png)}}" alt="Resultado final" style="width:100%">
</div>
</div>
</body>
app.py:
#app.route('/uploaded/<filename>', methods=['GET', 'POST'])
def uploaded_image(filename):
img_seg = main(filename)
return render_template("gallery.html", name=None)
File structure:
app.py
static
|----resultado_final.png
templates
|----gallery.html
As the error says, it should be
<img src="{{ url_for('static', filename='resultado_final.png') }}" alt="Resultado final" style="width:100%">
noting the ' at the end of the filename.

Python flask generator function not working with JQuery-mobile

I've been stuck with the following problem for a while, and i can't seem to get it to work on this Python flask web application i've been developing:
1) my flask view -> obtains image data from a local database and passes the data via a generator to a template
My flask route/view code:
#app.route(#app.route('/viewer',methods=['GET'])
def viewer():
archive = request.args.get('filepath')
arc = rarTools()
pagetotal = arc.pageTotal(archive)
def g():
for n in range(pagetotal):
data = arc.getPageb64(archive,n+1)
print(n+1)
yield data
return Response(stream_template('viewer.html',data=g()))
2) My HTML template with JQuery Mobile UI obtains this data and simply displays all the image data on 1 page
My HTML viewer.html with JQuery mobile UI:
<body style="background-color: black">
<div data-role="page" class="page" id="mainpage" data-theme="b">
<div data-role="main" class="ui-content">
<div id="frame" align="middle" style="width: 100%">
{% for page in data %}
<img id="page_img" src="data:image/png;base64,{{ page }}" width="80px" height="auto"/>
{% endfor %}
</div>
</div>
</div>
</body>
My HTML viewer.html WITHOUT JQuery mobile UI:
<body style="background-color: black">
<div id="frame" align="middle" style="width: 100%">
{% for page in data %}
<img id="page_img" src="data:image/png;base64,{{ page }}" width="80px" height="auto"/>
{% endfor %}
</div>
</body>
My problem is how long it takes to load pages when there are many images in my database. The load time is vastly different when I use JQuery Mobile and when I don't:
Because i'm using a generator to pass the data to the template, the images are loaded dynamically with the page loading immediately and each page appearing as the image data is generated on the flask back-end when I don't use JQuery Mobile to style the page.
When I use JQuery Mobile on the other hand, the page only loads once all the image data is passed even though i'm using a generator.
How can I get my JQuery Mobile template page to refresh after every yield, so that
The page loads immediately irrespective of image count?
The pages refreshes after each new image data "yield" so the the images are loaded dynamically? - like it works when I don't use JQuery Mobile?
I am aware that it has something to do with the - either: 'pageinit' or 'pageload' events with Jquery Mobile, but for the life of me, i can't seem to get the above code to work!!
Any assistance would be much appreciated, thanks in advance!

Categories

Resources