Why does Django template script src only works if hard-coded? - python

In order to avoid mixing non-SSL and SSL content, I want to use a relative path for my Javascript file. In settings.py, I have defined JS_ROOT = "/path/js/".
In my html file, the following line results in no mixed content warning:
<script src="/path/js/Foo.js" type="text/javascript"></script>
This line gives a mixed content warning:
<script src="{{ JS_ROOT }}Foo.js" type="text/javascript"></script>
Any explanation?

I discovered that my problem was that I was not returning JS_ROOT correctly as part of my request context. Now that I include it in my context_processors.py and have the context_instance as part of my response, it works.

Related

Flask static file content type is text/html after redirect

I have run into a problem with static files after a redirect in Flask.
The web app I am writing will redirect users after logging in for the first time to a site where they need to change the default password they've been provided. On this site my custom stylesheets are entirely broken and images won't display either.
A quick inspection in the Chrome dev tools showed that after the redirect the content type for the all files from the static folder is set to text/html. I suspect that this is the issue.
In my template html the stylesheet is linked in the following way:
<link rel="stylesheet" href="{{ url_for('static', filename='css/colorVariables.css') }}">
The stylesheets and images work fine on every other page of the app and also if you go to the exact same page without the redirect.
The redirecting part looks like this:
if user.first_login:
return redirect(url_for("change_password"))
I have found the issue. The redirect was happening in a function run with app.before_request. Wrapping the routes with the function manually solved the problem.

URL Parameter breaks Flask template

I'm working on an html form page using a template which can be found here. The template works as expected, however when I include a URL parameter, the page loses its CSS.
Works:
#app.route('/add', methods=['GET', 'POST'])
def add_form():
return render_template('form.html')
Doesn't work:
#app.route('/add/<param>', methods=['GET', 'POST'])
def add_form(param):
return render_template('form.html')
I've worked with URL parameters in the past and never had this problem, what could be causing this behaviour?
Check if your CSS files are included with relative path f.e.
<link rel="stylesheet" type="text/css" href="css/main.css">
If there is no lead slash then files are relative to the given path.
In the first case, it will be relative to / (last part omitted)
in the second case, it will be relative to /add/.
Try change path from above to
<link rel="stylesheet" type="text/css" href="/css/main.css">
with a leading slash.

Generate pages with Flask without using separate template files

I'm trying to keep things minimal, so I don't want to create templates, directory structures, etc. I have a simple CSS file available on the web (via RawGit) and I want to use it to style the page generated by a view. How can I render a page without templates?
from flask import Flask
application = Flask(__name__)
# <insert magic here>
# application.get_and_use_my_super_cool_CSS_file(URL)
# <insert magic here>
#application.route("/")
def hello():
return "hello world"
if __name__ == "__main__":
application.run(host = "0.0.0.0")
If you don't want to write templates as separate files, you can use render_template_string instead. This is typically not a very useful feature, as it becomes difficult to maintain large templates written as Python strings. Flask's Jinja env also provides some extra help when rendering files it recognizes, such as turning on autoescape for HTML files, so you need to be more careful when rendering from strings directly.
return render_template_string('''<!doctype html>
<html>
<head>
<link rel="stylesheet" href="css url"/>
</head>
<body>
<p>Hello, World!</p>
</body>
</html>
'''

flask templates: nginx cache or serve static assets called in jinja markups

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.

serve static files css and js via wheezy.template?

I have this master html template:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Start Bootstrap - SB Admin Version 2.0 Demo</title>
<!-- Core CSS - Include with every page -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<!-- SB Admin CSS - Include with every page -->
<link href="css/sb-admin.css" rel="stylesheet">
<!-- Core Scripts - Include with every page -->
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
<!-- SB Admin Scripts - Include with every page -->
<script src="js/sb-admin.js"></script>
</head>
this is the test.py file:
from wheezy.template.engine import Engine
from wheezy.template.ext.core import CoreExtension
from wheezy.template.loader import FileLoader
T = ['where/project/folderbase/is']
engine = Engine(
loader=FileLoader(T),
extensions=[CoreExtension()]
)
master_template = engine.get_template(r'master.htm')
#route('/test')
def login_name():
return master_template.render({})
I'm a complete n00b at templating and web design.
lets say i run this via any of python web server like flask on localhost:port/test
Nothing shows up.
Why?
And what is this #path_for in wheezy.template?
Do I need to include #require(path_for) or anything else?
is that necessary to server static files in the html file to define all the files in a specific folder-> 'static'
or can they be accessed from where they are now, as in the code above?
You had lots of questions. I'll answer even though you may not care anymore...
If you have correctly configured Flask, and served that template on the route/url 'test', then nothing would appear as you have not defined a <body> with any content in the html.
In wheezy.templates, you access local variables/functions with the #my_variable syntax (ie you prefix it with an # symbol). If you want to access a variable that was passed to the template as part of the context, you need to require it first, #require(my_variable). Your example uses an empty dict as the context, so there would be no variables to access/require.
path_for is part of wheezy.routing, not wheezy.templates. It is used for getting the url of a named route (ie you could do #path_for('test'), and it would return localhost:1234/test. Using path_for would only make sense if you are using the complete wheezy.web framework (which uses wheezy.routing and wheezy.templates). Flask would have its own functions for doing this (I'm not sure what they are though, I don't use Flask). You would need to pass these functions into the template via the context, then #require them to use them though (or make some custom extension for wheezy.template).

Categories

Resources