I am trying to develop an flask web application in which banners should be displayed on web pages,but when I run the app initially banners are displayed on title page,when I click on any hyperlink it should redirect to next page,but on that page banners are not displaying why?
my html codes are in templates folder and images are in static folder
i had used this in title.html
<img src="../static/inner_banner5.jpg" width="1400" height="222">
and i had also used the same in admin_login.html
my app.py code is
__author__ = 'mullapudi'
from flask import Flask,request,redirect,Blueprint,render_template,flash
blueprint = Blueprint('app', __name__, url_prefix='/title')
#blueprint.route('/', methods=['GET', 'POST'])
def title():
# Located at https://yourdomain.com/login
return render_template('title.html')
#blueprint.route('/home/', methods=['GET', 'POST'])
def home():
return redirect('/title/')
#blueprint.route('/admin/', methods=['GET', 'POST'])
def admin():
return render_template('admin_login.html')
the problem here is the banner is displaying in title page where it has a hyper link to redirect to the admin_login page but in admin_login page it was not displaying the banner why
Don't use relative URLs, use url_for:
<img src="{{ url_for('static', filename='inner_banner5.jpg') }}" width="1400" height="222">
Your directory structure would then be
.
├── app.py
├── env
├── static
│ └── inner_banner5.jpg
└── templates
Related
I am trying to delete two files from my flask application. But it does not work
html
<button href="/remove/wellness" id="remove" class="btn btn-success mr-2">Remove</button>
Here is my delete function:
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
return os.remove(filename_jsonl, filename_csv)
Any and all help is appreciated. Thanks!
I solved the issue with the following directory structure:
.
├── app.py
├── templates
│ └── delete_files.html
├── wellness.csv
└── wellness.jsonl
As you can see I have two files called wellness.csv and wellness.jsonl in the directory where I have placed my app.py file. The name wellness will be passed from the template and these two files will be deleted from the directory.
app.py:
import os
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return "Files are deleted successfully"
except Exception as e:
return f"Error in deleting files: {e}"
delete_files.html:
<html>
<head>
<title>Delete files using button click in Flask</title>
</head>
<body>
Remove
</body>
</html>
Output:
After clicking the delete button I see the message Files are deleted successfully.
The folder structure after deletion of the files:
.
├── app.py
└── templates
└── delete_files.html
Update
If you want to redirect to root url after successful deletion you can use redirect method like below:
import os
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
#app.route('/')
def search():
return render_template('delete_files.html')
#app.route('/remove/<file_id>')
def remove(file_id):
filename_jsonl = f"{file_id}.jsonl"
filename_csv = f"{file_id}.csv"
try:
os.remove(filename_jsonl)
os.remove(filename_csv)
return redirect(url_for('search'))
except Exception as e:
return f"Error in deleting files: {e}"
I was trying to run my html code using flask framework. When I tried to run the python script, it showed 404 error in the browser
<html>
<body>
<h1>Hello world!</h1>
</body>
</html>
python script:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/hello/<user>')
def hello_name(user):
return render_template('hello.html', name = user)
if __name__ == '__main__':
app.run(debug = True)
What is the reason of this error?
The code works fine.
Make sure that you keep the html file in templates folder. My folder structure is like this:
flask_app
├── hello.py
└── templates
└── hello.html
And also visiting the http://127.0.0.1:5000/ will cause the error as you did not define any view for root path.
While visiting the indexed path http://127.0.0.1:5000/hello/arsho I got the expected view:
Use jinja to print your name
<html>
<body>
<h1>Hello {{name}}</h1>
</body>
</html>
Go throught the flask quickstart
Even though my issue might be a common one, I couldn't find a clear answer for it.
I'm a beginner with AngularJS and there is a very simple code that is not working, and actually all my directives doesn't work.
Here is my small project
/templates
-index.html
-header.html
-script.js
mainapp.py
In index.html there is
<!DOCTYPE html>
<html data-ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<div data-ng-include="'header.html'"></div>
</body>
</html>
in header.html
<div> I'm supposed to see this </div>
And mainapp.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def mainpage():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Nothing in script.js
When I'm running mainapp.py I'm expecting to see "I'm supposed to see this" but I don't because the directives doesn't seem to be working. However if I'm trying the html code alone (on Plunker for example) it's working fine.
I assume there is configuration that I need to do but I have no idea what, any ideas? (and if someone could provide an explanation for why it's not working that would be great)
Note that using data- before my directives doesn't change the issue.
Thanks
The issue has to do with how Flask handles static files vs. templates. The header.html file is really a static file in your situation, not a Flask template.
Change your directory structure to:
├── mainapp.py
├── static
│ └── partials
│ └── header.html
└── templates
└── index.html
Then update the ng-include to:
<div data-ng-include="'header.html'"></div>
If this were me, I wouldn't even use a "templates" directory. Just serve up a your index.html file from the static directory so that when an end user hits the main / route, Angular takes over. Then, you can just interact with the server-side via making AJAX requests against the RESTful API.
On a Raspberry Pi, I have written a simple Flask app that displays the server's current date and time on a web page. That part works great.
The page should also display an image. That part doesn't work. The image is stored in the photos folder under the app folder: Web_Test/photos.
I use a css file that is stored in a static folder, and that works great.
I use url_for to create the URL to the image:
<p><img src="{{url_for('photos', filename='image1.jpg')}}"></p>
Since photos is not a known endpoint for the url_for command, I used: app.add_url_rule('/photos/<path:filename>', view_func=app.send_static_file) to add the photos folder as an endpoint.
Every time I access the web page from a web browser, my command window, that I ran python (python3 photo.py) from, shows GET /photos/image1/jpg HTTP/1.1" 404.
There are no specific errors, but also no image.
I have read many of the posts on here about this issue, but nothing has helped.
This is my photo.py code:
from flask import Flask, render_template
import datetime
app = Flask(__name__)
app.add_url_rule('/photos/<path:filename>', endpoint='photos', view_func=app.send_static_file)
#app.route('/')
def photo():
now = datetime.datetime.now()
timeString = now.strftime("%Y-%m-%d %H:%M")
templateData = {
'title' : 'Latest Photo',
'time' : timeString
}
return render_template('photo1.html', **templateData)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=80)
This is my photo1.html code:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href='/static/style.css' />
<title>{{title}}</title>
</head>
<body>
<h1>Latest Photo</h1>
<h2>Current date and time: {{time}}</h2>
<p> <img src="{{url_for('photos', filename='image1.jpg')}}"></p>
</body>
</html>
Any thoughts or suggestions would be greatly appreciated.
Thanks!
The way your program is currently written, the image will be visible if you reorganize the project layout like this:
project
├── app.py
├── static
│ └── image1.jpg
└── templates
└── photo1.html
The fact that you want to use send_static_file to display photos suggests that photos are static resources. If that's the case, then it would be better to:
1) Move image1.jpg to static/photos/image1.jpg
2) Change the template like this:
<p> <img src="{{url_for('static', filename='photos/image1.jpg')}}"></p>
3) Drop the app.add_url_rule('/photos/<path:filename>', ...) in app.py
I just created a folder named "static" in the project folder and moved my images to it and my problem got solved.
app.py
static
|----image.jpg
templates
|----index.html
and changed index.html file like this:
<img src="/static/image.jpg">
I'm trying to use cherrypy for application dispatching with Flask. The docs give an example with a development server, but when using the cherrypy example snippet and modifying the url prefix, the page is unable to find the static folder.
My directory structure is as follows:
cherry
├── app1
│ ├── __init__.py
│ └── app1.py
├── app2
│ ├── __init__.py
│ ├── app2.py
│ ├── static
│ │ └── js.js
│ └── templates
│ └── index.html
└── cherry_app.py
Some relevant files:
## cherry_app.py
from cherrypy import wsgiserver
from app1.app1 import app as app1
from app2.app2 import app as app2
d = wsgiserver.WSGIPathInfoDispatcher({'/first': app1,
'/second': app2,
})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9999), d)
if __name__ == '__main__':
try:
print 'Start at 0.0.0.0:9999'
server.start()
except KeyboardInterrupt:
server.stop()
## app2.py
from flask import Flask, send_file
import flask
app = Flask(__name__)
#app.route("/")
def root():
return ("Hello World!\nThis is the second app. Url is %s"
% flask.url_for('root'))
#app.route("/index")
def index():
return send_file('templates/index.html')
if __name__ == "__main__":
app.run()
## index.html
<script src="/static/js.js"></script>
JS loaded?
## js.js
alert('Loaded!');
Going to http://0.0.0.0:9999/second/ correctly tells me that the Url is /second/, and the javascript is loaded when I go to http://0.0.0.0:9999/second/static/js.js. But the html gives the error GET http://0.0.0.0:9999/static/js.js 404 (Not Found). It appears it doesn't know to use the prefix /second when looking for /static even when I change the line:
app = Flask(__name__, static_url_path='/second/static')
How can I get the webpage to correctly load the static files? Preferrably without html templating (like jinja).
Did you try to use url_for to locate static files? Here is the static files section in Flask quickstart.
So in your situation, modify src value of script element in index.html:
<script src="{{ url_for("static", "js.js") }}"></script>
The second argument js.js should be the relative path of static file (say js.js) to the static folder. So if the directory structure of static looks like:
static/scripts/js.js
just replace js.js with scripts/js.js:
<script src="{{ url_for("static", "scripts/js.js") }}"></script>
Hope this will make sense.