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
Related
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
I work with the Python flask, HTML, and local JSON file to display the JSON data from a local JSON file in the HTML. Once the flask reads a local JSON file, it is sent to index.html with jsonify. After then, using that data I want to display the information.
I can the JSON data in the flask side, but have struggled with displaying it in the HTML. Could you let me know what I missed?
flask code
import os
from flask import Flask, render_template, abort, url_for, json, jsonify
import json
import html
app = Flask(__name__)
# read file
with open('./data/file.json', 'r') as myfile:
data = myfile.read()
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=jsonify(data))
app.run(host='localhost', debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>House</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous"
/>
<script>
var jsonfile ={{jsonfile}};
</script>
</head>
<body>
<div class="container">
{{jsonfile}}
</div>
</body>
</html>
Your issue is the use of the jsonify method. If you read the documentation of jsonify it returns a Response object and not a string. So you will get something like this for jsonify(data)
<Response 2347 bytes [200 OK]>
You could remove jsonify and use json.dumps instead, as follows:
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=json.dumps(data))
This works for me.
What Rahul P is correct and the reason you are getting unexpected results is because you are using jsonify when you should be using json.dumps(data).
If you want you want to use the json inside of the script tag can I suggest making the following changes?
app.py
import os
from flask import Flask, render_template, abort, url_for
import json
import html
app = Flask(__name__)
# read file
with open('./data/file.json', 'r') as myfile:
data = myfile.read()
#app.route("/")
def index():
return render_template('index.html', title="page", jsonfile=json.dumps(data))
if __name__ == '__main__':
app.run(host='localhost', debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>House</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous"
/>
</head>
<body>
<div class="container"></div>
<script>
const jsonfile = JSON.parse({{jsonfile|tojson}});
console.log(jsonfile);
document.querySelector(".container").innerHTML = JSON.stringify(jsonfile, null, 2);
</script>
</body>
</html>
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")
I am building a simple website and I am trying to get an image onto the page using Flask. All i get is the broken image symbol on the page tho.
Here is the server code...
from flask import Flask, render_template, url_for
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def homePage():
return render_template("HomePage.html")
if __name__ == "__main__":
app.run(debug=True)
And here is HomePage.html...
<!DOCTYPE html>
<style>
</style>
<html>
<head>
</head>
<body>
<img href="{{ url_for('static', filename='testing.png') }}" />
</body>
</html>
<script>
</script>
My file structure is as followed...
-Web
-static
-testing.png
-templates
-HomePage.html
server.py
Now, if i actually inspect through chrome, I can see the img tag gets converted to
<img href="/static/testing.png">
and if I right click this in chrome and open it in a new tab the image appears, But is still doesn't show on my web page.
For img tag use src attribute rather than href attribute.
In HomePage.html change the following line:
<img href="{{ url_for('static', filename='testing.png') }}" />
to
<img src="{{ url_for('static', filename='testing.png') }}" />
Reference:
MDN's documentation on img tag attributes
This question already has answers here:
Strange SQLAlchemy error message: TypeError: 'dict' object does not support indexing
(8 answers)
Closed 4 years ago.
I'm trying to make a web app that has a search button that searches a postgres table.
I'm getting the error:
TypeError: 'dict' object does not support indexing
My code is as follows:
app.py
from flask import Flask, render_template, request
from sqlalchemy import create_engine
app = Flask(__name__)
db_string = "postgres://xi:x#x:5432/xx"
db = create_engine(db_string)
#app.route('/', methods=['GET', 'POST'])
def homepage():
if request.method == 'POST':
jn = request.form['jobnumber']
result_set = db.execute("SELECT cost FROM public.options where optionno = (f'%jn%')").fetchall()
return render_template('main.html', test=result_set, jn=jn)
else:
return render_template('main.html')
if __name__ == "__main__":
app.run(debug=True)
and my HTML is:
main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>xxx</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
<p>xxx</p>
<form method="POST" id="jobnumber">
<input name="jobnumber" type="textbox" placeholder="jobnumber">
</form>
<table>
<td>
{{test}}
</td>
</table>
</body>
</html>
Any help will be hugely appreciated.
SQLAlchemy has a text function for converting string to sqlalchemy text object which appears to correctly escape the SQL for you.
You need to import
`from sqlalchemy import text'
And you need to remove f from the query and also change = to like or ilike
i.e.
res = db.execute(text("SELECT cost FROM public.options where optionno like ('%jn%')")).fetchall()