I am looking for a way different possible image source in my html code, depending on result of a python function.
Exemple if:
state = isOnline()
is a function that can say if a device is online or not, it returns:
True
then I would obtain
IMG_URL = imgSource(state)
would return the source for online image
static 'project\img\true.jpg'
which I would then through my views.py used as:
def device(request):
return render(request, 'device.html', {'IMG_URL': IMG_URL})
and then I could use this variable in my html code.
<img src="{% IMG_URL %}" alt="Post">
I hope you guys will be capable to help me, thanks !
You can use something like:
def device(request):
# this could be generated in any number of ways, but this is a simple one
IMG_URL = 'http://example.com/online_image.jpg' if is_online() else '/local/img/offline_image.jpg'
return render(request, 'device.html', {'IMG_URL': IMG_URL})
There are some ideas for checking if you're online or not here.
Related
Background: I'm new to html and fastAPI and not sure about the right terminology for the questions I have. I know how to insert a image in html by doing following:
<img scr="create_image" alt="">
and then on python side I can write something like below to create and insert the image
#app.route("/create_image")
def image():
# create a image
return image
Question: I'm trying to do something similar for insert a table into html but not sure what code to write on the html end, but something similar like below
<table scr="create_table" alt=""> # its definitely wrong, but this is the idea.
on the python side, I'm planning to do following:
#app.route("/create_table")
def table():
df = pd.DataFrame({"col1":[1,2],"col2":[3,4]})
return df.to_html()
the following code in html file will serve the purpose
<iframe src="create_table"></iframe>
I am trying to create a very simple one-page Flask application for a python script that I have. The script requires multiple user inputs in a for-loop with the number of loops being user input as well.
Here is the code in my script to make it more clear:
def shared_books():
import requests as re
from bs4 import BeautifulSoup
import time
num_lists = int(input('Enter the number of lists you would like to search:'))
urls = []
page_counts = []
for i in range(num_lists):
urls.append(input(f'Enter the url for list {i + 1}:'))
page_counts.append(int(input(f'Enter the number of pages for list {i + 1}:')))
I want a simple HTML that will ask the user for the number of lists, then the URL and page count for each list as is shown in my function. Then it will run the entire function.
The HTML code I have right now is super simple and I don't want much else outside of the input parts:
<html>
<head>
<title>Goodreads-App</title>
</head>
<body>
<h1>Welcome to my app!</h1>
<<p>This app will allow you to see books that are
shared between multiple lists on goodreads</p>
</body>
</html>
Please let me know how I can set up this application!
Firstly, I suggest you take a look at the Flask docs. You are doing it right in terms of having a view function, but the input() python keyword doesn't work like that in Flask. Instead, you should render an html template which you can then put your form input field into. Here is an example:
from flask import Flask, render_template
#flask initialising stuff, read docs for info
#app.route("/home")
def home():
return render_template("home.html")
Flask runs on your computer's local server "localhost", which is not publicly accessible. It conventionally runs on port 5000, which gives the name "localhost:5000".
When someone visits "localhost:5000/home", flask will look for a file called "home.html" in a pre-designated templates folder – the default is a directory called "templates" which you should put your html files into.
So if this is your "home.html" file:
<html>
<head>
<title>Goodreads-App</title>
</head>
<body>
<h1>Welcome to my app!</h1>
<p>This app will allow you to see books that are
shared between multiple lists on goodreads</p>
</body>
</html>
When you load the page associated with a specific function, it will return a template which is rendered as html. The above should look something like this:
And that is how to start.
Thank you for the answers! I haven't quite solved the previous issue but have approached it from a different angle which is working now! I will potentially post again if I don't solve it.
I am using flask forms to do what I was trying.
I would like to use a class Track to have a function playsound() and this should play the sound on a html template.
This is my class :
class Track:
def __init__(self, name, path):
self.name = name
self.path = path
def playsound(self):
# does something
Now I know that I will need javascript and ajax as well probably. But I'm still new to the concept and I would like to see how I would go about achieving that. The sound file should play onload and should simply be invoked when you type:
songname = Track('name', 'music/filename.ogg')
#app.route('/playSong')
def playSong():
return songname.play()
If there is no way this can be done in this way, or there is a much better way, I'd be happy to be enlightened. Thanks in advance!
You can keep the src of in HTML as
<audio controls>
<source src="http://127.0.0.1:5000/a" type="audio/wav"/>
</audio>
where http://127.0.0.1:5000/a is the url which send_file the audio
python code :
#app.route('/a')
def returnAudioFile():
path_to_audio_file = pwd+"\\question_folder\\audio.wav" #audio from project dir
return send_file(
path_to_audio_file,
mimetype="audio/wav",
as_attachment=True,
attachment_filename="test.wav")
If I understood the question correctly, you should put an <audio> HTML element in your template and go from there. Flask will only serve the rendered template, it can't play the sound directly.
I'm trying to learn Flask and making a small app. So at first, I tested without a css file by using: (delay() gets the result from generator)
return Response(stream_template('login.html', data=delay()))
It works fine for me then now i want to implement new css, let's called it style.css and i put it in the static folder. In the html file I have:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"/>
The code will probably won't work as there is a problem with context and response, but it will work fine as a static return:
return render_template('login.html')
My Question is it it anyway that I can both have the generator to work (the delay() function) with the CSS in the static folder? I just spent couple hours on this problem but couldn't find an answer yet.
My stream_template:
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
# uncomment if you don't need immediate reaction
##rv.enable_buffering(5)
return rv
Thanks a lot
Quoting from the documentation:
Note that when you stream data, the request context is already gone the moment the function executes. Flask 0.9 provides you with a helper that can keep the request context around during the execution of the generator: ...
In your case, your code probably should be:
return Response(stream_with_context(stream_template('login.html', data=delay())))
or
return Response(stream_template('login.html', data=stream_with_context(delay())))
I am trying to render html output that is generated by a python google maps library that involves JS code in it. I am passing the part that shows google map with the html_map variable, and as follows:
html = t.render(Context({'html_map':html_map}))
return HttpResponse(html)
However, instead of showing the map, the page shows js code(i.e., directly prints it). The image below shows this:
How can I solve this?
html = t.render(Context({'html_map':html_map}))
return HttpResponse(html)
use in template:
{{ htm_map|safe }}