How to display images in Flask when src is given by function? - python

Basically, i have a function that returns valid img sources (ex: https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png)
When i try to display that image on html using flask, the image won't appear but a small icon of a image will be there, if i right click the icon and click "Open in new tab" it shows me the image but it just won't work on the html
My flask code:
from flask import Flask, render_template, redirect, url_for, request
import LightHub # My other script that contains the function
app = Flask(__name__)
#app.route('/')
def index():
return render_template('server.html', source=LightHub.crawl())
app.run(debug=True)
My HTML code (in the templates folder):
<html>
<head>
<title>Random Lightshot</title>
<meta charset="utf-8" />
</head>
<body>
<div class="prints" align="middle">
<img src="{{source}}" align="middle">
</div>
</body>
</html>
output: https://imgur.com/IGY0mnY

When I try this,
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
return render_template('server.html', source='https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png')
it works.
That probably means that LightHub.crawl() is not returning what you think it is. I believe you can verify that by running something like this:
assert LightHub.crawl() == 'https://image.prntscr.com/image/5P0nCp55SKe-WJTKjhCwsg.png'
I suspect that if you add that assert to your function, you'll find that it fails.

Related

Display image as background in Flask

I am giving my first steps on flask applications.
I would like to know how to show this image as a background and the html text on top?
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def home():
return "<h1>Welcome to the API Service</h1><p>This site is a prototype API for displaying dashboards: quick_report, crime_locator.</p>"
app.run()
The most elegant way to solve it, using the templates.
First step is to create a static and templates directory, like this:
--static
|
-- image.png
-- templates
|
-- index.html
--app.py
index.html
<style>
body {
background-image: url("/static/image.png");
}
</style>
<body>
<h1>Welcome to the API Service</h1>
<p>This site is a prototype API for displaying dashboards: quick_report,crime_locator.</p>
</body>
app.py
import flask
app = flask.Flask(__name__, static_folder="static")
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def home():
return flask.render_template('index.html')
app.run()

Python 3.8.5 Flask giving internal server error with WSGI application when template is called using render_template in VS Code - 500 server error [duplicate]

This question already has answers here:
Flask raises TemplateNotFound error even though template file exists
(13 answers)
Closed 2 years ago.
I have been following a YouTube tutorial made by Corey Schafer using Flask. I have reached the 2nd tutorial about using html templates, but that is the only place I have reached. This is the program I am running called hello.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
app.run()
This is the HTML file I have been using, called home.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<div>
<p>{{ message }}</p>
</div>
</body>
</html>
Whenever I try to run my code, I always get the error jinja2.exceptions.TemplateNotFound: template.html. I've tried to look at all possible solutions, but none have seemed to work. How could I fix this? I'm on a Windows 64-bit machine.
By default un Flask, the template folder is templates/. If home.html is in the same directory as app.py, you need to set template_folder.
Here is how to fix your app.py:
from flask import Flask, render_template
app = Flask(__name__, template_folder='./')
#app.route('/')
def home():
return render_template('home.html')
app.run()
To use the default template location (which is recommended), this is the file structure you would need to have:
app.py
templates
└── home.html

Display image on HTML page using flask

I am trying to display an image from a list of JPEG images into an HTML page.
I tried to use the following code on flask :
from flask import Flask, render_template, request
from Daily_runs import func,func_2
import os
import glob
app = Flask(__name__)
#app.route('/')
def index():
return render_template('Input.html')
#app.route('/hello', methods=['POST'])
def hello():
path = request.form['path']
func(path)
func_2()
images = glob.glob(os.path.join(path,'*.jpg'))
image = os.path.abspath(images[0])
return render_template('Image.html', user_image = image)
HTML template code :
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src={{user_image)}} alt="User Image">
</body>
</html>
The images does not get displayed instead only the alt text is displayed.
Tried various other methods listed in this forum but could not succeed.
Can anyone help on this ?
Have you tried putting the Jinja code within quotes in the html file?
i.e:
<img src="{{ user_image }}" alt="User Image">
Also, it could just be a typo here, but there is an extra ")" in the image tag (removed above) which could be causing your issue.
To display images stored locally with flask and render_template, you must ensure that you save the desired images in a static/images folder in the parent directory of your application:
your_project_folder
| - static/
- images/
- your_imagename.jpg
| -templates
- Image.html
-main_app_file.py
Now, in your route:
import os
#app.route('/hello', methods=['POST'])
def hello():
path = request.form['path']
func(path)
func_2()
image = [i for i in os.listdir('static/images') if i.endswith('.jpg')][0]
return render_template('Image.html', user_image = image)
In Image.html:
<img src='/static/images/{{user_image}}' alt="User Image">

Simple sijax exapmle dont work

I'm learning Python and Flask, I have very little experience, but something that is impossible.
With the usual AJAX does not have any problems, but I decided to try sijax, and even a simple example does not work. I'm sure this is due to incorrect connection and initialization, because I did git clone from the official repository git hub, and everything worked.
In the three examples, sijax working and initialized in one-file application, I want to use in the blueprint
If i click on the Say Hi!
Traceback return : 127.0.0.1 - - [12/Sep/2016 14:19:56] "POST / HTTP/1.1" 400 -
app init.py
import os
from flask import (Flask,
redirect,
url_for,
session)
# from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect
from os import path
from .database import db
from werkzeug.contrib.fixers import ProxyFix
import flask_sijax
import hmac
from hashlib import sha1
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.wsgi_app = ProxyFix(app.wsgi_app)
db.init_app(app)
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'''
if app.debug == True:
try:
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
except:
pass
'''
with app.test_request_context():
db.create_all()
from .general import controllers as general
from .shop import controllers as shop
from .test import controllers as test
app.register_blueprint(shop.module)
app.register_blueprint(general.module)
app.register_blueprint(test.module)
flask_sijax.Sijax(app)
CsrfProtect(app)
#app.template_global('csrf_token')
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest()
#app.route('/')
def index():
return redirect(url_for('test.index'))
return app
test blueprint controllers.py
from flask import (render_template,
Blueprint,
g)
import flask_sijax
module = Blueprint('test',
__name__)
#flask_sijax.route(module, '/')
def index():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('test/hello.html')
template hello.html
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/sijax/sijax.js') }}"></script>
<script src="{{ url_for('static', filename='js/sijax/json2.js') }}"></script>
<script>{{ g.sijax.get_js()|safe }}</script>
</head>
<body>
Say Hi!
</body>
</html>
The reason was not working sijax, it was the fact that the {{csrf_token ()}} was not active
It is necessary to do so either: Say Hi!
Either connect to the html file:
<script type="text/javascript">
var csrfToken = "{{ csrf_token() }}"
</script>

Flask-webage background image doesnt work

Below is a simple html code
index.html
<html>
<head>
<title>Webpage</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet" >
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="sylesheet">
</head>
<body>
<style type=text/css>
background-image: url("static/images/back.png");
</style>
<p>Does the Image Work? </p>
</body>
</html>
This is my Flask code:
app.py
from flask import Flask, render_template
app = Flask(__name__, static_url_path="static", static_folder="static")
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()
I get this error when I tried to inspect the page:
GET http://127.0.0.1:5000/static/images/back.png-404(NOT FOUND)
I read through a couple of other forums, but couldn't find any solution to this problem. My images are in the following folder:
Flaskapp
templates
static
images
back.png
When I open the index.html file, it works perfect, but when I try to run the python file to run the server, the background image isnt seen.
Not really sure how to proceed.
put the static folder next to the flask app
/FlaskApp
-app.py
static/
images/
-back.png
templates/
-index.html
....
you should not have to even tell flask about it... it will just know
app.py
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/")
def main():
return render_template("index.html")
if __name__ == '__main__':
app.run()

Categories

Resources