Seems like my static files aren't being served properly. This is what it looks like right now:
myApp
__init__.py
static
img
js
bootstrap.min.js
etc.
This is what my app config in my __init__.py looks like:
app = Flask(__name__, static_url_path="", static_folder="static")
This is the error:
127.0.0.1 - - [01/Dec/2014 13:12:01] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 -
As far as the url routing goes, no problems there, localhost/home routes to home, localhost/contact routes to contact, etc. But static files aren't being found :( Am I missing something?
NOTE: I'm hosting this on my Mac, purely local host
This is my __init__.py main method:
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
Running as:
python __init.py__
It looks like you are hardcoding to static file URLs. You tell Flask to server them with no URL prefix -- the default would have been /static -- but the log shows the request going to /static/js/bootstrap.min.js. You probably have something like the following in a template file.
<script src="/static/js/bootstrap.min.js"></script>
Instead, you should use url_for to create the URL for you. Change the above to
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
This will result in
<script src="/js/bootstrap.min.js"></script>
Related
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">
Python code:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def hello():
return render_template('testing.html')
if __name__ == "__main__":
app.run()
Html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>My name is pk</h1>
</body>
</html>
Also how to enable jinja2 in pycharm community version. I am directly creating html file and .py file in the same project
flask file structure
|-app
|--templates // where your html files must be in
|--static // where your js and css files must be in
|--.py files
|--other packages
Also jinja is enabled in your system, if you have already downloaded flask package.
By default, Flask looks in the templates folder in the root level of your app.
http://flask.pocoo.org/docs/0.10/api/
template_folder – the folder that contains the templates that should
be used by the application. Defaults to 'templates' folder in the root
path of the application.
So you have some options,
rename template to templates
supply a template_folder param to have your template folder recognised by the flask app:
app = Flask(__name__, template_folder='template')
Flask expects the templates directory to be in the same folder as the module in which it is created;
You'll need to tell Flask to look elsewhere instead:
app = Flask(__name__, template_folder='../pages/templates')
This works as the path is resolved relative to the current module path.
You cannot have per-module template directories, not without using blueprints. A common pattern is to use subdirectories of the templates folder instead to partition your templates. You'd use templates/pages/index.html, loaded with render_template('pages/index.html'), etc.
I want to better understand the logic of how flask serves jinja templates behind ningx.
My goal is to optimize loading time, by caching or make ningx serves JS, CSS and if possible fragment of html's template that is not dynamic.
UPDATED based on comment
How can I test which service between Ningx and Flask serves the static assets called in html template by jinja markup as src="{{ url_for('static', filename='static/js/pageScript.js'}} ?
I would like to delegate static assets to Nginx as much as possible,
and I would like to understand which does which with the following configuration.
As example, all JS, CSS called from page.html template are the same for all the <int:ids> of the route /path/:
#application.route('/path/<int:id>/')
def graph_template(id):
meta = {'og:title':'the title of my page is about element ID'}
return render_template('page.html', meta=meta)
The only dynamic part is the <meta> fragment, but in the template I will call JS and CSS by:
<script type="text/javascript" src="{{ url_for('static', filename='static/js/pageScript.js') }}"></script>?
does flask serve the whole final html template, including js and css ?
or
does flask serve only the html page, while js and css are served by nginx ?
or
or would it be even possible to make flask serve a portion of the html, and let nginx serve the complete html page and assets?
how to cache js and css elements which are commons in dynamic jinja templates?
In this other question:
[Flask: Caching static files (.js, .css)
is suggested to use nginx serving static elements, but here I have dynamic elements called via jinja markup and it is not clear to me which service is handling what.
My nginx configuration use these blocks for routing /static/ and /path/:
location /static {
alias /var/www/mySite/static;
}
location /path/ {
include uwsgi_params;
uwsgi_pass unix:/var/www/mySite/myApp.sock;
}
Jijnja markup in Page.html template for calling assets:
<script type="text/javascript" src="{{ url_for('static', filename='static/js/pageScript.js') }}"></script>
rendered: src=/static/js/pageScript.js
Structure of flask app is:
/app.py
/templates/page.html
/static/js/pageScript.js
The easiest way to see what is actually being served by what is to add a custom header to each element that could be serving something and then track which header(s) are returned:
# In your application setup code:
#app.after_request
def add_served_by_flask_header(response):
response.headers["X-Served-By-Flask"] = "true"
return response
And in your nginx configuration:
location /static {
alias /var/www/mySite/static;
add_header X-Served-By-NGINX true always;
}
That said, it looks like you should see that your markup is served by Flask but your static files will be served by nginx. Flask generates the markup dynamically, but when the browser goes to download the file pointed at by the HTML nginx handles it without needing to invoke Flask.
I have a blueprint defined as :
auth_login = Blueprint('auth_login', __name__, template_folder='templates', static_folder='static', static_url_path='/static')
I am registering it as :
app.register_blueprint(auth_login, url_prefix='/user')
I have a route:
#auth_login.route('/<username>/')
def profile(username):
return render_template('profile/user.html',
username = username)
With this setup, the /user/ endpoint never manages to load the static files as I get,
"GET /user//static/css/lib/bootstrap.min.css HTTP/1.1" 404 -
"GET /user//static/css/lib/font-awesome/css/font-awesome.min.css HTTP/1.1" 404 -
What I really want is to look into the static folder of the root application and not the blueprint, so I want it to request
"GET /static/css/lib/bootstrap.min.css HTTP/1.1" 200 -
Is it possible to configure this via static_folder or static_url_path so that the route will look for the static files at root and not relative to where the blueprint is mounted?
By default, Flask sets up the /static URL to serve files out of {application_root}/static - you are overwriting that default with your blueprint's code. (The URL is still /static but the folder is {application_root}/path/to/blueprint/static, which, by the sound of things, is not what you want).
Simply remove the static_folder and static_url arguments to your Blueprint initialization and the URLs should work just fine (assuming that you have the appropriate CSS in your {application_root}/static folder.)
My Platform : Django 1.5.4 , running with a wsgi module in apache
Issue: I am trying to deploy a django site using a secure connection for one route, and for this route, css fails to work (it seems to load though, meaning, the resource is fetched correctly and I can see the code when I go to its path)
I have an alias in my Virtual Host Section on the http.conf file that allows the wsgi to load static files that looks something like this:
Alias /static/ /home/username/public_html/mysite/static_dir/
And, I have a rewrite rule that looks like this so that I can make one of my routes secure:
RewriteRule ^/product/(.*)/buy/$ https://%{SERVER_NAME}/product/$1/buy/ [L,R]
This works in terms of getting to the secure product page where customers will input credit card info, yet the css will not load correctly. The images will load normally, and they share the thew same path as the style.css that loads.
What's weird is that when I navigate to the css path that is loaded in the head of the page, I see my CSS code!
Here are my static files settings in settings.py
STATIC_ROOT = '/home/username/public_html/mysite.com/static/'
STATIC_URL = 'http://34.56.78.93/~username/mysite.com/static/'
STATICFILES_DIRS = (
'/home/username/public_html/path/to/project/static/',
and I'm loading the css like this in a base template <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
If you've ever experienced this or have any clue whats going on, please respond. Thanks