I'm trying to do the following:
Having a file structure like the following:
/app
/static
/start
/css
/js
- index.html
/templates
Id like to know how I can serve this index.html and make this load its CSS and JS without using url_for('static', filename='') or other kind of serving trough Flask.
Basically, I want to put http://local.com/start and trough Flask serve index.html which will load its own css and js like <link href="css/style.css" rel="stylesheet">
I tried send_from_directory('/static/start', "index.html") and app.send_static_file('index.html') but they don't work.
I also tried current_app.send_static_file('start/index.html') but this only serves the html. It doesn't make the index.html load its own CSS and JS.
I got the information from these links
How to serve static files in Flask
python flask - serving static files
Flask: How to serve static html?
They don't do what I want (or maybe I'm doing it wrong).
Thanks in advance, if there is more info needed just tell me.
You can load a regular html file as a jinja template. Just call render without any parameters.
Related
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') }}">
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.
I am trying to render a couple of files on Bottle web server. The first HTML file has a button which links to another file. So I need both of these to run on the server.
My (updated)Project structure is something like this
-app.py
-static
-css
bootstrap.css
bootstrap.min.css
-fonts
-js
jquery.js
etc etc
-index.html
-visualization.html
My index.html file has to be rendered first. From which the user has to option to click on a button which takes him to visualization.html.
My pages are not rendering. What could be the reason for this?
The routing snippet from app.py is as show below:
from bottle import route, run, template, static_file, response, request
#route('/noob')
def map():
return static_file('index.html',root = './static')
run(host='0.0.0.0', port='8030')
This is how I access those files in my index.html:
<script src="./static/js/jquery.js"></script>
<link href="./static/css/grayscale.css" rel="stylesheet">
I'm relatively new to Python and Bottle. Is this right? I get a 404 error
.
Also, how to I place two files on the bottle server. As explained above, a button in index.html links to visualization.html. So I'm guessing this should also be running on Bottle server. Do I run it in the same file? Different port?
Thanks in advance.
You need to put index.html in static folder.
-app.py
-static
various css and img files being used in my two html files
index.html
visualization.html
A better way for accessing static files and templates would be to rename index.html to index.tpl like this:
-app.py
-static
-js
bootstrap.min.js (example)
-css
-fonts
index.tpl
visualization.tpl
profile.tpl
And:
from bottle import route, run, template, static_file, response, request
#route('/noob')
def map():
return template('index.tpl')
#route('/profile')
def profile():
return template('profile.tpl')
#route('/static/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./static/')
run(host='0.0.0.0', port='8030')
And in your tpl files use path like this:
<script src="/static/js/bootstrap.min.js"></script>
Hope this answers your question.
I'm just starting out with Flask, and I was wondering what the best method for
dealing with how flask deals with static files when trying to use a premade CSS template.
Basically, I have downloaded a CSS template that I liked off the internet, but when if I simply drag the files into my flask application folder the CSS, JS, and image files do not work since they are not located in the static folder.
But if I move all the static files into the static folder, then I have to go through all the code and change the link urls, which is very time consuming.
The CSS Template I am using has an index.html that uses links like
<link rel = "stylesheet" href = "css/style.css" >
I have set both the static_folder = ""
and the static_url_path = "" in my flask app and I have moved the css, js, and image folders from the downloaded template into the base folder for the application, but the links are still not working.
Is there a better way to deal with using premade CSS templates with flask? Can I override the need to put css and js and image files in the static folder somehow? Thanks for your help!
(Sorry for opening this old post, but I'm on a badge hunt :])
There are several possible solutions, but the one I would recommend is to move the file style.css to folder <server_root>/static/css/.
Then create the flask app like app = Flask(__name__, static_url_path=''), what means that it still serves static files from the static/ folder, but on path / (so <server_root>/static/css/style.css is served on /css/style.css).
With this setup, your links href="/css/style.css" will work.
However, it's strongly recommended to use flask.url_for('endpoint', param='value') instead of /endpoint/url/value both in code and templates (surrounded with {{ ... }}) for all URLs - static files ('static', filename='css/style.css') and your own endpoints. So if your endpoint looks like this,
#app.route('/some/path/<variable>')
def some_endpoint(variable):
# do something and return response...
... you can use url_for('some_endpoint, variable='something') no matter what the actual URL (/some/path/something/ in this case) is. (Tested python 3.6.7; flask 1.0.2)
Let's suppose I have an HTML page (base.html) that must include one JavaScript file.
<script type="text/javascript" src="/js/main.js"></script>
It is my understanding that a Django project is not hosted in a public folder. Rather, requests are routed to views.py which generates a response.
Let's suppose my project directory looks like this
- project
- project_app
- views, models, ecc…
- templates
- base.html
- css
- main.css
- js
- main.js
How come base.html can reference main.css and main.js? If I access myserver.com/js/main.js this should not return anything (as the template folder is not public). Yet the browser need to access those file and I need to include them.
Do I need to write a specific URL rule to redirect requests to /js/main.js to the actual js file or what sort of magic can make a simple html include works?
The usual method is to keep your CSS, javascript, and similar files in a static folder and serve them to your html. General Django documentation can be found here.
In a nutshell, your directory will look like this:
- project
- project_app
- views, models, ecc…
- templates
- base.html
- static
- css
- main.css
- js
- main.js
Then, your base.html will reference the file using:
<script type="text/javascript" src="/static/js/main.js"></script>
The docs I referenced at the top show how to serve static files in production. Lots of people use a content delivery network (CDN) to serve their static files. Amazon's S3 service is an example of this. Then, you'll change the STATIC_URL setting in your settings.py to your S3 bucket (or similar network). You can then reference the STATIC_URL in your templates.
{% load static %}
...
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
...
You'll use commands like ./manage.py collectstatic to collect your static files and move them to your CDN at certain times. Basics of collectstatic can be found here.
You need to put all your static files in STATIC_ROOT folder by using command django-admin.py collectstatic and serve this folder. More details and explanation you can find here:
https://docs.djangoproject.com/en/dev/howto/static-files/#managing-static-files-css-images