Make static HTML directory accessible with CherryPy and file-protocol - python

I have a WEB application with some static WEB page (the documentation). I'd like the documentation (written in html) to be accessible from the application running under cherrypy, but also as static files that we can open without running the WEB server ...
class AppServer( JFlowServer ):
#cherrypy.expose
def index(self, **kwargs):
return " ".join( open(os.path.join(WEB_DIR, "index.html" )).readlines() )
#cherrypy.expose
def test(self, **kwargs):
return " ".join( open(os.path.join(WEB_DIR, "test.html" )).readlines() )
this works fine, but as I do have multiple pages, from cherrypy the link should be "/test" where in the static mode I have "/test.html". I wanted to make cherrypy maps the URL but I couldn't find a way to do so ...
thanks for your help,
Jerome

You can achieve it with staticdir tool and using relative URLs in your documentation. The latter will allso access from both http:// and file:// protocols.
Here's how it can look like.
.
├── app.py
└── docs
├── a.html
├── b.html
└── index.html
app.py
#!/usr/bin/env python3
import os
import cherrypy
path = os.path.abspath(os.path.dirname(__file__))
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8,
},
'/docs' : {
'tools.staticdir.on' : True,
'tools.staticdir.dir' : os.path.join(path, 'docs'),
'tools.staticdir.index' : 'index.html',
'tools.gzip.on' : True
}
}
class App:
#cherrypy.expose
def index(self):
return '''Some dynamic content<br/>See docs'''
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
docs/index.html
<!DOCTYPE html>
<html>
<head>
<title>Docs index</title>
</head>
<body>
<p><a href='/'>Back to home page</a> (not relevant from file://)</p>
<p><a href='a.html'>See A</a></p>
<p><a href='b.html'>See B</a></p>
</body>
</html>
docs/a.html
<!DOCTYPE html>
<html>
<head>
<title>A page</title>
</head>
<body>
<p><a href='index.html'>Back to index</a></p>
<p><a href='b.html'>See B</a></p>
</body>
</html>
docs/b.html
<!DOCTYPE html>
<html>
<head>
<title>B page</title>
</head>
<body>
<p><a href='index.html'>Back to index</a></p>
<p><a href='a.html'>See A</a></p>
</body>
</html>

Related

how can i show css animation in my html using flask?

im a begginer here , struggling with basic stuff
I have my flask:
from flask import Flask , render_template , send_file , send_from_directory
import os
app = Flask(__name__)
#PRIMERA FUNCION
#app.route('/')
def index():
return render_template('prueba.html')
and i have my html :
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - The Arrow</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<!-- partial:index.partial.html -->
<div class="arrow-1"></div>
<!-- partial -->
</body>
</html>
when I open the html file on browser it shows the css ,
but when I run flask css doesnt show and I cant figure out why!!!
I have try this
#app.route('/css/<path:filename>')
def css_file(filename):
file_path = os.path.join('css', filename)
return send_file(file_path)
and i also thought it was a problem of my folder layout but I already tried re arrange folders
Flask has different ways to do this, but the convention is to put static assets (like CSS) in the static directory (which should be at the root of your project) and link them in with Jinja and the url_for() function. so in your case it would look like this:
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>CodePen - The Arrow</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
More explained in the Flask docs

Implementing css with html file does not work

I'm a beginner in using html and css files and have been stuck with the following problem for a while.
I made these files but I cannot get the css implemented in the html file:
app.py
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app.route('/')
def index():
greeting = "hello there!"
return render_template('index.html', greeting=greeting)
if __name__ == "__main__":
app.run()
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>epic website</title>
<meta name="description" content="">
<meta name="viewport" conent="width=device-width">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Sup, {{ greeting }}</h1>
<p>Praisethelord<p>
<p class ="x">basinga</p>
</body>
</html>
style.css
h1 {
color:pink;
font-size: 12px;
}
p {
color:yellow;
font-size: 1px;
}
.x {
color:brown;
}
When I open the browser it does use the html file but without the css file (for some reason I cannot show pictures).
When I press f12 to check what's going on, it gives me the following errors:
Failed to load resource: the server responded with a status of 404 (NOT FOUND)style.css:1
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
Any idea what I am doing wrong? I have a feeling it has something to do with the directories, but I have been playing around with it for a while and cannot seem to figure it out.
You have to add a static file folder and it should in the same directory.Css files are added to it
from flask import Flask, app
app =Flask(__name__,static_url_path='',static_folder='static')
Consider to use this structure:
project_folder
| ---------- config.py
| ---------- app.py
| ---------- .flaskenv
| ---------- app/
| ---------- routes.py
| ---------- __init__.py
| ---------- models.py
| ---------- templates/
| ---------- index.html
| ---------- static/
| ------ css/
| ------ styles.css
Your routes go to rotues.py, templates will found in templates sub-folder, all styles will be in css sub-folder.
Initialize your application in __init__.py You do not need to use this on this file:
# ...
if __name__ == "__main__":
app.run()
Because your top-level file app.py will act as the entry point of your application. Eventually, you will have this kind of application:
# __init__.py
from flask import Flask
app = Flask(__name__)
from app import routes, models
# routes.py
from app import app
from flask import render_template
#app.route('/')
def index():
greeting = "hello there!"
return render_template('index.html', greeting=greeting)
# app.py
from app import app
Templates will be in index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>epic website</title>
<meta name="description" content="">
<meta name="viewport" conent="width=device-width">
<!-- Dynamic link to styles.css -->
<link type="text/css" rel="stylesheet" href="{{ url_for('static', filename = 'css/styles.css') }}">
</head>
<body>
<h1>Sup, {{ greeting }}</h1>
<p>Praisethelord<p>
<p class ="x">basinga</p>
</body>
</html>
To run your app, pass flask's environment variables in .flaskenv:
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=True
Run flask run in your terminal to start your server.

Serving css files when serving html from render_template in Flask [duplicate]

This question already has answers here:
How to serve static files in Flask
(24 answers)
Closed 2 years ago.
I want to serve .HTML files that link to a styles.CSS file using <link rel='stylesheet'> in my web-app using render_template() function in Flask. It will run as a local-app using FlaskWebGUI library in Python.
File structure:
flaskGUI ---
templates ---
index.html
styles.css
flaskapp.py
flaskapp.py code:
from flask import Flask, render_template
from flaskwebgui import FlaskUI
app = Flask(__name__)
ui = FlaskUI(app)
#app.route("/")
def index():
return render_template("index.html")
ui.run()
index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Index</title>
</head>
<body>
<h1>Index</h1>
<p>This is an HTML file served up by Flask</p>
</body>
</html>
styles.css code:
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
Expected: Powder-blue background, Blue 'Index' text, red paragraph text.
Actual Result: White background, black text.
The standard way to serve static files is to put them in the static folder, not the templates folder, then use url_for('static', filename='styles.css') to link to it.
Alternatively, use send_from_directory to serve it with a custom route.
#app.route("/styles.css")
def styles():
return send_from_directory("templates", "styles.css")

Load an HTML page into an HTML frame using Flask

As of title, I'm trying to load an HTML page into an HTML frame using Flask.
When I open the frameset.html page on a Firefox tab (substituting {{src}} with index.html of course), the frameset behaves correctly.
However, whenever I run the python code, the loaded HTML page is correctly divided between the frames, but there is no trace of the index.html page in any of it.
main.py
from flask import Flask, render_template, request
app = Flask(__name__)
page = 'index.html'
#app.route('/')
def home():
return render_template('frameset.html', src=page)
app.run()
frameset.html
<html>
<frameset rows="10%,80%,*">
<frame src=''>
<frameset cols='20%,40%,40%'>
<frame src=''>
<frame src='{{src}}'>
<frame src='' name="output">
</frameset>
<frame src=''>
</frameset>
</html>
index.html
<html>
<head>
<title>HOME</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<style type="text/css">
.container {
max-width: 500px;
padding-top: 100px;
}
</style>
</head>
<body>
<div class="container">
GENO stats
</html>
How can I solve this problem? The code I wrote here is just to test the functionality of the framesets.
create another route at #app.route('index.html') rendering index.html the template, make sure the index.html file is in the templates folder
like this:
#app.route('/index.html')
def index():
return render_template('index.html')
resources need to be served from either the templates folder or the static folder in flask, you can't have a resource and have it automatically served as that would be incredibly insecure, since any user then will have access to your entire server by simply changing the link.

serving an image with python and flask not working [duplicate]

This question already has answers here:
Link to Flask static files with url_for
(2 answers)
Closed 6 years ago.
I reduced the code for this to, I think, minimum while trying to get it to work:
The python:
#!/usr/bin/env python
from functools import wraps
from flask import Flask, render_template, session, request, redirect, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
#app.route('/')
def index():
return render_template('index_test.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
The html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
The image is in the static folder.
And it gives this error:
"GET /bulboff.gif HTTP/1.1" 404
when the page is accessed.
I've tried several things like setting the Flask default paths, without the url_for, etc, but, still no image.
What am I missing?
According to the flask document:
To generate URLs for static files, use the special static endpoint
name:
url_for('static', filename='style.css')
The file has to be stored on the filesystem as static/style.css.
In your case, use <img src="{{ url_for('static', filename='bulboff.gif') }}">
If You put image in the static folder, You should use something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<img src="{{ url_for('index') }}static/bulboff.gif"/>
<p>"{{ url_for('index') }}" <p>
</body>
</html>
Alternatively, You could change application's code and add following:
#app.route('/bulboff.gif')
def bulboff():
return open('static/bulboff.gif').read()
<img src="{{url_for('static', filename='bulboff.gif')}}" />
Try that. Your filename could be a path from the static folder. So like if you have filename = \some\path\img.png it will look for the img in static\some\ath\img

Categories