CSS not loading completely when i run my python application - python

I intend to apply basic CSS over my HTML under my python/ flask application. I got a HTML with CSS file from getbootstrap.com.
Link: https://getbootstrap.com/docs/5.2/examples/cover/
The HTML loads up completely when I run it locally (outside the project) but it does not load properly when I try running the application using flask on dev (localhost).
Can someone please suggest a fix here. I have tried placing the CSS file in static folder and then loading it with below approach (adding link to CSS file in my HTML):
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='stylesheets/cover.css') }}">
My project directory looks like:
env
static > stylesheets > cover.css
templates > index.html
app.py
app.py file:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def base():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True, port=5000)
By default it comes with the following link:
<link href="cover.css" rel="stylesheet">
After running the project, it looks like as attached under the snap. This means that the CSS is getting applied but not completely.

Related

why I do get a broken picture icon instead of the image in my folder when I run the flask app? [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 11 months ago.
I get this broken-image-icon thing when I run my flask app
from flask import Flask
panda = Flask(__name__)
#panda.route("/")
def home():
return '''
<body>
<img src="panda.jpg"
alt="A picture of a panda"
height="600" width="600">
</body>
'''
if __name__ == "__main__":
panda.run()
When I set the source of the <img tag to the relative or absolute path of that image (it is in the same directory as the flask app btw) the server doesn't show the image. Amazingly, when I set the source as the url of that image (it is taken from the internet) it works just fine!
Could this be a problem specific to my device or maybe the web servers I use? I use Google Chrome and Microsoft Edge, same problem on both. Is it a flask thing? because the same html code works perfectly fine on its own, it is only within flask that I get this problem.
I need help, please don't answer with "just use the url then!", obviously I want to upload different images and this is just a simplified version of my actual code, this is the problem part of it, everything else is ok.
you need to use flask render templates.
File structure:
app.py
static
|----test.jpg
templates
|----index.html
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/', methods=['GET'])
def index():
return render_template('index.html')
app.run()
index.html
<html>
<head>
</head>
<body>
<h1>Index page</h1>
<img src="{{url_for('static', filename='test.jpg')}}" />
</body>
</html>

Flask Server in Python ruining looks

I'm trying to render my website inside of flask as I made a backend inside of it.
I've used both of the following codes:
def TestDir():
return render_template('Index/index.html')
and
def HomeDir():
return(open('Templates/Index/index.html').read())
but it shows all glitchy: https://i.1nch.dev/cdn/0pPwq1kDY2Oc9CMM.gif
But on my pc it shows normal: https://i.1nch.dev/cdn/l3LnfmUzyad78Nl5.gif
You need to have a static folder setup for your css and js files unless you override it when you initialize Flask.
Your app directory should look something like this:
/app
- app_runner.py
/templates
/Index
- Index.html
/static
/css
- style.css
To access the css file in your html use something like this:
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/style.css') }}">

Flask 404'ing on static content I have in an assets directory

My project structure looks like this:
/project home
app.py
/templates/index.html
/templates/assets
and my index.html file has several references to relative stylesheets that look like this:
<link rel="stylesheet" href="assets/css/slick.css">
<link rel="stylesheet" href="assets/css/slick-theme.css">
Same for various JS files that exist in assets/js. Now when I load the page, I get this error:
Loading failed for the <script> with source “http://localhost:5000/assets/js/popper.min.js”. localhost:5000:564:1
There are many of these messages and in the python debugger I see:
127.0.0.1 - - [24/Dec/2019 18:29:16] "GET /assets/js/main.js HTTP/1.1" 404
I tried googling and changing this line in Flask
STATIC_URL_PATH = '/templates/assets/' # Where the css is stored
STATIC_FOLDER = '/templates/assets/'
app = flask.Flask(__name__, static_folder=STATIC_FOLDER,
static_url_path=STATIC_URL_PATH)
But still when I click the index.html page in templates its able to load fine with all the CSS and JS and images, but from Flask, its like the CSS is stripped out.
First, make sure that the templates folder is in the same directory as your app.py:
.
├── app.py
└── templates
└── assets
Then create the Flask instance like this:
STATIC_FOLDER = 'templates/assets'
app = Flask(__name__,
static_folder=STATIC_FOLDER)
1st, /templates and templates (without /) are 2 different paths. The 1st one refers to a templates folder under the root path / of your system, which certainly isn't the one you want. The 2nd one refers to a templates folder in the same directory, which is the one you want.
2nd, there is no need to specify static_url_path if it's just the same as the static_folder, because that's the default behavior ("Defaults to the name of the static_folder folder").
Then, in your HTML files, instead of hardcoding the paths to the assets folder, let Flask build the URL for you. See the Static Files section of the Flask docs:
To generate URLs for static files, use the special 'static' endpoint
name:
url_for('static', filename='style.css')
By default, it will look for static files under the static folder (ex. static/style.css) because that it is the default value for the static_folder parameter in the Flask constructor. When you set it to templates/assets, Flask will use that and will automatically build the correct URL with url_for.
<link rel="stylesheet" href="{{ url_for('static', filename='css/slick.css') }}">
Note:
Make sure that, when testing the loading of static files, clear your browser's cache first or test your app on private/incognito mode of your browser, to force re-downloading of static files.

Flask can't find static folder when I have set a new root_path

I have a Flask app that sets a custom root_path.
app = Flask(
__name__,
root_path='flask_news'
)
#app.route('/login')
def login():
return render_template('login.html')
Flask can serve flask_news/templates/login.html but will not find the required CSS, which is under flask_news/static/bulma.css
In my template file I'm asking for the CSS like so:
<link rel="stylesheet" href="{{url_for('static', filename='bulma.css')}}">
and the head of the served webpage looks like
<link rel="stylesheet" href="{{url_for('static', filename='bulma.css')}}">
Why is Flask not able to serve the required CSS? I think I need to change something in how the static folder is located but I'm not sure on how.
Perhaps you can try specifying the static directory as well as the templates directory locations when initializing your application, something along the lines of:
app = Flask(__name__,
static_folder='./flask_news/static',
template_folder='./flask_news/templates')
Hopefully that helps!
You can define the static folder to be whatever you'd like, as in this case you can set it up to './flask_news/static/'
To do so, when you initialize your Flask object, pass in the path to the static_folder parameter:
app = Flask(__name__, static_folder='./flask_news/static')

Python Not Finding CSS File

Hi I'm new to using python with web programs and I'm trying to make a basic website that uses a CSS style sheet. I have three files: app.py, index.html, and style.css. They are all in the same directory. When I run app.py and go to localhost:8080, it displays "Hello World!", but it has not style from the style.css file and my terminal says "HTTP/1.1 GET /style.css" - 404 Not Found. When I just open my index.html file in chrome without using the app.py file, though, it does have the style formatting. Any help with this? Thanks in advance. My code is as follows:
app.py:
import web
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
web.config.debug = True
class Index(object):
def __init__(self):
self.render = web.template.render('.')
def GET(self):
return self.render.index()
if __name__ == '__main__':
app.run()
index.html:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="style.css" />
<title>Basic Web Project</title>
</head>
<body>
<p>Hello World!</p>
</body>
</html>
style.css:
p {
color: green;
font-size: 22px;
}
When you specify <link type="text/css" rel="stylesheet" href="style.css" /> you say to your web browser the following thing : The style.css is on the same level as the index.html
Let me give you and example:
/app
index.html
style.css
if you open index.html from your browser you go to the following url
file://some/directory/app/index.html
)it is the same as file://some/directory/app/ because the browser will always search for the index when displaying a web page )
and when in this index.html the browser finds the <link> that specified by you it will search for that style.css under the following url : file://some/directory/app/style.css
and of course that it will find that file.
Now the fun part.
When you open localhost:8080 it will display localhost:8080/index.html which works because your web app ( that python script that you run ) knows what to do when somebody goes to that url ( because you defined it in the urls variable and you created that class )
But when on this page the browser find the <link> tag he tries to go to localhost:8080/style.css which your web app dose not know how to handle because you did not specified it in your app .
Now the solution:
You must define a url for /style.css and a class that will render that web page for you.
Have you tried to add style.css to urls, your application knows nothing about /style.css get request, probably that's why it returns 404.

Categories