Not able to load static file CSS and JS thru pyBottle? - python

Always getting 404 while trying to load static file using Bottle. I have referred stack overflow question and Google group chat but nothing is helping me to correct my problem. Please help me.. spent lot of time in this...
Tuts
main.py
static/
bootstarp.css
views/
index.tpl
main.py code
import bottle
from bottle import Bottle
from os.path import basename,abspath, dirname, join
app = bottle.default_app()
appPath = dirname(abspath(''))
print appPath
#bottle.route('/')
def index():
return bottle.template('index', dict(title=appPath,get_url=app.get_url))
#bottle.route('/static/:filename#.*#', name='css')
def server_static(filename):
return bottle.static_file(filename, root=join(appPath,'static'))
bottle.debug(True)
bottle.run(host='localhost', port=8082,reloader=True)
**Template:**
<link href="{{ get_url('css', filename='bootstrap.css') }}" rel="stylesheet" media="screen">

Add
from bottle import static_file
at top. Then just use static_file(..., ...) is fine:
#bottle.route('/static/:filename#.*#', name='css')
def server_static(filename):
return static_file(filename, root=join(appPath,'static'))

Related

FastAPI serving static files through symlinks

I have mounted the static directory in my FastAPI app using the following code:
from fastapi.staticfiles import StaticFiles
app = FastAPI(
title="Title of the Application",
description="Over all description of the application")
app.mount("/public", StaticFiles(directory='public'), name='public')
If I have a symlink pointing to a path outside the app folder, e.g.
/home/xyz/app/main.py
/home/xyz/app/index.html
/home/xyz/app/public/data -> /home/xyz/static/whatever.tgz
The FastAPI application can recognize the URL xyz.com/public/index.html, but it can't recognize xyz.com/public/data.
Is this doable? Unfortunately, I cannot use FileResponse due to the blob size being too large. I want to return the file with a simple link somehow.
It is doable, as long as you mount a StaticFiles instance on that specific path as well. For example:
app.mount("/public", StaticFiles(directory="public"), name="public")
app.mount("/publicsym", StaticFiles(directory="public/data"), name="publicsym")
Then in your Jinja2 template you can requesst the files as below:
<link href="{{ url_for('public', path='/styles.css') }}" rel="stylesheet">
<img src="{{ url_for('publicsym', path='/image.png')}}" width="50%">
or, as per your given example (if there is a "static" directory including a "whatever.tgz" file):
{{ url_for('publicsym', path='static/whatever.tgz')}}

Flask rendering previous version of CSS [duplicate]

This question already has an answer here:
Flask css not updating [closed]
(1 answer)
Closed 2 years ago.
Flask app is rendering a previous version of my css file (I have saved and made changes, but when I inspect page, the css file shown is a previous version). Maybe previous version of css file is somehow stuck in the cache? I tried restarting browser, no luck .
Here is the code:
Part of app.py file (the part where I'm rendering the HTML file):
from flask import Flask,render_template,url_for,request
from twilio.rest import Client
app = Flask(__name__, template_folder='templates')
app.static_folder = 'static'
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader as pdr
#import yahoo finance api fixer
import fix_yahoo_finance as fyf
from pandas_datareader import data as pdr
from datetime import datetime, timedelta
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}" />
</head>
<body>
<h1>Ticker Predictor</h1>
<h2>Using Machine Learning to Predict Tomorrow's Stock Prices</h2>
<br>
<h3>Simply enter a valid stock ticker below and hit the predict button to receive a text message of tomorrow's predicted opening price of that stock within around 10 minutes!</h3>
<!-- Main Input For Receiving Query to our ML -->
<form action="{{ url_for('predict')}}"method="post">
<input type="text" placeholder="Input Stock Ticker Here" required="required" />
<button type="submit">Predict</button>
</form>
{{ prediction_text }}
</body>
</html>
And here is the file structure:
TickerPredictor
|--static/
|--styles.css
|--templates/
|--index.html
|--app.py
Any help would be much appreciated! Thank you!
your app.py should be something like this
from flask import Flask,render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
DEBUG = True
HOST = '0.0.0.0'
app.run(debug=DEBUG, host=HOST)
In your app.py file you did not mention the host. Update your app.py file and it should work.
Thanks to help from Rahul and stackoverflow.com/questions/21714653/flask-css-not-updating , I just performed a hard reload in my browser to clear the cache (CMD + SHIFT + R). In other words, the previous version of the css file was getting stored in the browser cache, clearing the cache gets rid of previous css file version and most recent version is then displayed (which is obviously what I want). Thanks everyone!

Web.py not serving static files

Running on the devel server, I can render 0.0.0.0:8080/index.html without CSS fine, but no static files load. 0.0.0.0:8080/static results in "Not found" and 0.0.0.0:8080/static/style.css gets a 404.
All I've googled quotes or links to http://webpy.org/cookbook/staticfiles, which I feel like I've followed to point.
filetree
code.py
/web
...
/static
style.css
/images
...
/pages
index.html
code.py
import web
render = web.template.render('/home/keith/code/webpy/skeleton/pages/')
urls = (
'/', 'index',)
class index:
def GET(self):
return render.index()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
/pages/index.html
...
<link rel="stylesheet" type="text/css" href="static/style.css" />
...
Would appreciate any help!
I tried running python code.py from a terminal window and the static files served fine! Before, I was using the terminal emulator in my IDE (Geany 1.24.1). So that was the problem, for whatever reason.

CherryPy static content from different paths

I have read some Q&A like load-static-content-with-cherrypy
However, I am unable to figure out how to do it to be shared by different paths.
I have the following Class:
class Root(Base):
#cherrypy.expose
def index(self):
return self.html_head()+self.header()+"Root"+self.footer()+self.html_end()
#cherrypy.expose
def help(self):
return self.html_head()+self.header()+"HELP"+self.footer()+self.html_end()
And the config file is:
[global]
server.socket_host = "127.0.0.1"
server.socket_port = 8080
server.thread_pool = 10
[/]
tools.staticfile.root = "/path/to/app/"
[/css/style201306.css]
tools.staticfile.on = True
tools.staticfile.filename = "css/style201306.css"
When accesing the css from /help I got a 404 error. Must I add a [path] entry for every method in my class where I want to serve the css file? Or must I use the [global] tag instead, though maybe I don't want to use it from other apps? What is the difference between an app config and a path config entry? Until know I was considering this as one App with 2 paths ("/" and "/help")
I am passing configuration like:
# Configuration
import os.path
tutconf = os.path.join(os.path.dirname(__file__), 'myconf.conf')
cherrypy.quickstart(root, config=tutconf)
Both webpages load the CSS the same way (actually, is the same code):
css/style201306.css
The problem is in your html itself use an absolute URL, there is no reason to use a relative url when is the same content, instead of:
<link rel="stylesheet" type="text/css" href="css/style201306.css" />
use
<link rel="stylesheet" type="text/css" href="/css/style201306.css" />
otherwise the browser will append the current URL, for example if the current URL is /help, then it will try to fetch:
/help/css/style201306.css

Difficulty accessing json file with d3 and flask

I am using Flask as a web framework, and I am trying to implement the first example from the book Getting Started with D3, by Mike Dewar. I have a Python script named run.py and two directories, templates/ and static/, containing index.html and service_status.json, respectively. Unfortunately, my code is not rendering the data at all, nor is it producing any glaring errors.
This is what I have in run.py:
#!/usr/bin/env python
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
if __name__=="__main__":
port = 5000
app.debug = True
app.run( port=port )
This is what I have in templates/index.html:
<!DOCTYPE HTML>
<HTML>
<HEAD>
<META CHARSET="utf-8">
<SCRIPT SRC="http://d3js.org/d3.v3.min.js"></SCRIPT>
<SCRIPT>
function draw(data) {
"use strict";
d3.select("body")
.append("ul")
.selectAll("li")
.data(data)
.enter()
.append("li")
.text( function(d){
return d.name + ": " + d.status;
}
);
}
</SCRIPT>
<TITLE>MTA Data</TITLE>
</HEAD>
<BODY>
<H1>MTA Availability Data</H1>
<SCRIPT>
d3.json("{{ url_for( 'static', filename='service_status.json') }}",draw); // <---- BIG PROBLEM
</SCRIPT>
</BODY>
</HTML>
I am using Windows 7, Google Chrome, and Python 2.7.
If the JSON file is not going to change, then you should put it in the static directory and use
from flask import url_for
url_for('static', filename='service_status.json')
For this to work, also change the path in the JavaScript to '/static/service_status.json'
Static files like your json document, are by default served from a different directory from the templates - by default 'static'
You dont need to use the url_for call in your view, you can use it in your template:
d3.json("{{ url_for('static', filename='service_status.json') }}",draw);
So to summarise: 1) Move your json document in to the static folder (a folder called static along side your templates folder, by default), and 2) use the url_for call in your template to get the correct URI for your json document.
If you want to use a folder other than static, you can change that by passing static_folder to the Flask object contructor
You seem to be getting a 304 status code as you mentioned in earlier comments. I see that your JSON has the following date/time:
"Date": [
"12/15/2011"
],
"Time": [
" 7:35AM"
],
I am not 100% sure but this might help:
http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#if-modified-since
Basically, it says that
"This request header is used with GET method to make it conditional: if the requested document has not changed since the time specified in this field the document will not be sent, but instead a Not Modified 304 reply.
Format of this field is the same as for Date:"
So, may be you can check the timestamp on the JSON and probably just do a fresh save ?

Categories