Flask not finding files in my package's 'static' directory - python

My question is similar to several others on this site, but the answers I find there aren't working for me.
I'm learning Flask. I'm running Flask 0.10.1 and Python 2.7, on an Ubuntu 10.04 machine using a Vagrant VM.
I've tried countless suggestions from SO, the Flask docs, and Miguel Grinberg, without success.
So I'm showing the simplest version that I thought could work (but doesn't) for your perusal.
The commented-out substitute lines (in page_a.html and page_b.html) do work but are hideous.
First, here's the output of 'tree' on my project root:
And here are the files (minus a bit of boilerplate in the .html)
page_a.html:
<head>
<link rel="stylesheet" href="styles.css">
<!-- <link rel="stylesheet" href="static/styles.css"> -->
</head>
<body>
<h1>page_a</h1>
<img src="an_image.png">
<!-- <img src="static/an_image.png"> -->
to page b
</body>
page_b.html:
<head>
<link rel="stylesheet" href="styles.css">
<!-- <link rel="stylesheet" href="../../static/styles.css"> -->
</head>
<body>
<h1>page_b</h1>
<img src="../../static/an_image.png">
<!-- <img src="../../static/an_image.png"> -->
to page a
</body>
init.py:
from flask import Flask
app = Flask('my_pages')
import my_pages.views
runserver.py:
from my_pages import app
app.run(host='0.0.0.0', port=5000, debug=True)
views.py:
from my_pages import app
from flask import render_template
#app.route('/')
#app.route('/page_a')
def page_a():
return render_template('page_a.html')
#app.route('/pages/page_b/')
def page_b():
return render_template('page_b.html')
styles.css:
body {
background-color: green;
}
This version does work when, in page_a.html and page_b.html, I use the commented-out lines (instead of the lines above them).
Here's the output of runserver.py when I access page_a.html:
"GET /page_a HTTP/1.1" 200 -
"GET /styles.css HTTP/1.1" 404 -
"GET /an_image.png HTTP/1.1" 404 -
and page_b.html.
"GET /pages/page_b/ HTTP/1.1" 200 -
"GET /pages/page_b/styles.css HTTP/1.1" 404 -
(this last shows 'an_image.png' from my 'styles' directory)
My questions: What am I missing? Can this setup be made to work without a major refactoring?
I of course don't want to hard-code the full path to every static file.
Also, in the real application, the URLs run several levels deep -- e.g.,
http://localhost:5000/book/<id_1>/chapter/<id_2>/page
Many thanks to anyone who might reply!

You aren't telling Flask that the files are in your static folder. The easiest way to do that is with url_for.
<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">

You could use url_for to serve the static files. An example can be found here.
PS: Unless you are making something really large, serving them by using '/static/file.css' should work fine. In production environments it's better to get Apache or nginx to serve static files.

Related

Error 404 - Getting Stylesheet Working in Bottle (Python Webframework)

I'm using bottle (the python webframework) to familiarize myself with html, js and css and using localhost to access the site. I can't quite get the css file to be applied to the site that the templates link to. Sometimes it works, but when I edit the file, it doesn't update and even loses the file and can't find it, even after restarting the server. The Console gives the 404 error (file not found), even though I have not moved it.
I first noticed the issue when the CSS wouldn't update in the browser when I refreshed. After clearing out the cache every time I edited, I found the 404 not found issue. I've validated the css file to check if a synthax error was the issue. It came back clean. I redownloaded the bottle.py file in case it needed an update. Still the same result. I also triple checked the link path, even tried to put them all into the same folder with no change.
Here is my file structure:
project folder
static
css
main.css
views
home.tpl
bottle.py
server.py
start.bat (starts the server)
Here is the code in server.py
from bottle import route, run, template
#route('/')
def home():
return template('home')
run(host='localhost', port=8080, debug='True', reloader='True')
Here is the template home.tpl:
<!DOCTYPE html>
<html>
<head>
<title>Bottle Site</title>
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Header!</h1>
</div>
<div id="navigation">
<ul>
<li>Home</li>
</ul>
</div>
<div id="section">
Section text!
</div>
<div id="footer">
© 2019 - <b href="#" id="dev">Footer/b>
</div>
</div>
</body>
</html>
I'd like to reliably be able to apply the css to the site without it crashing and sometimes not finding the file. Whenever I paste a fresh copy of my css file and start the server, it works fine until I try and change the file (a background color, for example. Nothing syntax breaking) but it doesn't update. when I clear the cache, it turns into a plane html file and the console reads:
"GET /static/css/main.css HTTP/1.1" 404 764
I just figured it out.
In the server.py file, you apparently need a:
#route('/static/<filename:path>')
def send_static(filename):
return static_file(filename, root='./static/')
to give the server a route that it can access and find the files (i think).
So in the templates, to show it where they are, you can say:
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
And it will work fabulously every time. :)
Why without the route it sometimes found the file and sometimes not will forever be a mystery of computer science.
Routes are hard.
Have a nice day! :)
I also like to use whitenoise with bottle.
from whitenoise import WhiteNoise
...
botapp = WhiteNoise(botapp)
botapp.add_files(staticfolder, prefix='static/')

Upload images from file system to html page

I'm trying do develop a very simple web app using flask, following the example from this link.
My problem is: I want to show images from my file system in that page but it seems like browsers are protected against that. I have to use something like:
<img src="http://aMessyURL.png">
Instead of being able to use something like:
<img src="images/myImageName.png">
So, I can I (dynamically) show images from my file system?
You should be able to do it when hosting a simple server:
https://docs.python.org/2/library/simplehttpserver.html
This should at least allow you to load files in the same folder as your code.
Flask interprets <img src="images/myImageName.png"> as:
app/images/myImageName.png
Normally, Flask projects have a static folder inside app (app/static) which contains your CSS, JS and images. You can either render them like above or use url_for:
<link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.png') }}">
Which renders fully as:
<link rel="shortcut icon" href="/static/img/favicon.png">
You Have to specify static root path and then use code in html below
app = Flask(__name__, static_url_path='')
In HTML
<img src="/static/images/myImageName.png">

Nginx - Flask app and css asset not loaded correctly

I have a flask app which has both front and back ends. I am using flask_assets to serve both css and js assets.
assets = Environment()
assets.init_app(app)
js = Bundle(common_blueprint.name + '/dist/javascripts/scout.js', output='dist/javascripts/scout.js')
css = Bundle(common_blueprint.name + '/dist/stylesheets/base.css', output='dist/stylesheets/scout.css')
assets.register("js_all", js)
assets.register("css_all", css)
app.register_blueprint(common_blueprint)
Now are are running in a weird issue, every time I deploy the app and hit the url, the application doesn't load the css file.
After few browser hard refreshes the css file is served correctly.
Any help is appreciated.
Thanks
If there is no specific reason to use flask_assets I suggest you to store both js and css files under the folder static in your flask project folder with the structure:
FLASK_PROJECT/static/javascripts/ # for your js files
FLASK_PROJECT/static/stylesheets/ # for your css files
Then in your index.html / base.html file you would load the files as follows:
<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='stylesheets/scout.css') }}">
<script type="text/javascript" src="{{ url_for('static',filename='javascripts/scout.js') }}"></script>
For more information you can take a look here

Why won't my Flask app connect to my CSS files? [duplicate]

This question already has answers here:
CSS file not refreshing in browser
(15 answers)
Closed 5 years ago.
Here is my project hierarchy:
Project
Here is my HTML file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='custom.css') }}"/>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
My .py flask file :
from flask import Flask, render_template, redirect, json, url_for, request, abort
from pymongo import MongoClient
client = MongoClient()
db = client.web_zoo
app = Flask(__name__)
#app.route('/')
def index():
return render_template('home.html')
if __name__ == "__main__":
app.run(debug=True)
And my CSS file :
body {
color: green;
}
h1 {
color: orange;
}
The HTML and .py files work fine and the HTML is rendered and displayed on the page. However the CSS doesn't change. It just displays it in normal black text.
NOTE : All those imports are there as I was doing something else. I stripped off everything else and still have this problem.
I can link bootstrap to it, and the CSS works, but not for my own CSS files.
I have looked at and tried these following solutions :
CSS Problems with Flask Web App
Application not picking up .css file (flask/python)
best way to override bootstrap css
It's probably quite obvious but I'm stuck. Any help? Thanks in advance!
EDIT - I have added a picture of the project hierarchy now instead of just a list. As you can see there are some other HTML files in there too, but none are used nor referenced.
Try
CTRL+SHIFT+R
in Chrome to reload the CSS.
On Mac try:
CMD+SHIFT+R
Otherwise right-click on the page in Chrome, select Inspect and select the Console tab to see what errors you get.

Flask: where to put static javascript files in templates

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 21 hours ago.
I'm developing a flask app with the following folder structure:
|-->flask_app.py
|-->static
|-->css
|-->bootstrap.min.css
|-->styles.css
|-->js
|-->jquery-3.1.1.min.js
|-->bootstrap.min.js
|-->script.js
|-->templates
|-->index.html
What is the proper way to link to these css and js files in index.html and what parameters do I need associated with them?
My CSS links look like this and are located in the header:
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
And my JS links look like this and are located at the end of the body tag:
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
Is this the correct syntax? Are they located in the correct spots in my templates (I'm sure there's flexibility here)? And are there any other parameters I should pass in (e.g. type="text/css", type="text/javascript", media="screen")?
Everything is working as expected but I want to follow recommended practice if there is any.
As the Flask documentation mentions, you should store .css and .js files within your static folder and for organizational purposes, its fine to have each type of file as subdirectories (especially as your app grows).
Per this SO answer, you don't need to have type="text/css" or type="text/javascript" in the jinja expression.

Categories

Resources