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>
Related
I have a django based web application; and I am using the Python wrappers of plotly to generate plots. When I try to use "ajax style" to fetch only the plot into a <div> </div> with a javascript call no plot is rendered. My situation is as follows:
<head>
<script>
async function generate_plot() {
const url = "/path/to/plot/generator/";
let response = await fetch(url);
let data = await response.text();
let element = document.getElementById('plot_div');
element.innerHTML = data;
}
</script>
</head>
<body>
<div id="plot_div"> </div>
...
</body>
At the /path/to/plot/generator/ endpoint there is a python function which looks like:
def plot_generator(request):
...
return plotly.offline.plot(fig, include_plotlyjs=False, output_type="div")
I am quite certain this is basically sound, because when I manually paste the return value from plot_generator() into <div id="plot_div"></div> the plot is displayed correctly, and also If I let the plot_generator() just return a dummy text like: This should have been a plot - the text is correctly displayed. But the plotly plot is not displayed in any way - the Firefox debug console shows no warnings/errors/anything ...
Something trivially wrong?
Update: When looking in the firefox console the plotly generated content seems to have arrived correctly in the browser/DOM.
I have a Python variable whose value is a string of text and would like to edit that value via Javascript.
I have no idea how to go about doing this.
Attempts:
function changeValue(val) {
val = 'new text';
}
<textarea placeholder="some text">{{ changeValue({{ result }}) }}</textarea>
<textarea placeholder="some text">
{{ result }}
</textarea>
What I want: I have some text (result) being added and would like to check if the text is empty. If so, I want to show the placeholder text.
The issue: Although I can check if the value is empty, when I try to print that result out it reads none
Thanks to all!
You do not need to call the JavaScript function from the HTML file. There are several approaches you can take:
1. Store the variable in HTML metadata:
<meta id="result_var" data-result={{result}}>
And then get the data in JavaScript:
result = document.getElementById("result_var").value;
2. Keep the variable in the tag where it's supposed to be and get it from there in JavaScript:
<textarea placeholder="some text" id="result-var"> {{result}} </textarea>
And then get it in JavaScript:
let result = document.getElementById("result-var");
3. Query it from your API: You can create a route in your Flask app that returns JSON data with the variable you need and then get that data to your JavaScript file by sending a request to your API.
4. Jinja format: I've seen solutions that involve just using the variable as if it was a jinja variable in JavaScript like this: let result = JSON.parse('{{ result | tojson }}');. But I haven't been able to get this working properly, not sure why.
I hope this helps!
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.
Hi all, im a bit new in Python.
So I have a confused issue for me. I need to store image in database, and after that I have to display each image on client side. Im using Flask for rest request.
So here I have my simpl marckup for submitind
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="image">Select image</label>
<input type="file" name='img' id='image'>
<input type="submit" id='upload_img'>
</form>
and here I get my request and save it to my DB
#app.route("/upload", methods=["POST"])
def upload_image():
# get current image file
img_file = request.files['img']
# get Content Type and File Name of current image
content_type = img_file.content_type
filename = img_file.filename
# save to GridFS my image
# fields <-- recive the id of just saved image
fields = db.FS.put(img_file, content_type=content_type, filename=filename)
# store the filename and _id to another database
# so here we can much morea easaly get image from our GridFS
db.Mongo['images'].insert({"filename": filename, "fields": fields})
return index(images=[])
My simple database model
class db(object):
URI = "mongodb://localhost:27017"
Mongo = None
FS = None
#staticmethod
def initialize():
client = pymongo.MongoClient(db.URI)
db.Mongo= client['gallery']
db.FS = GridFS(Database.DATABASE)
And all saves is successfully.
Retrive my image from DB and try to send it on clietn
#app.route('/get_all_images')
def get_image():
images = db.Mongo['gallery'].find({})
# try to get just a first image _id and fing it at GridFS files
image = db.FS.get(images[0]["fields"])
#send to the client
return index(images=image.read())
Here is markup for display image from the response
<div>
<img src="data:image/png;base64,{{images}}" alt="">
<div>{{images}}</div>
</div>
and finnaly I get something like this enter image description here
the response is look like this:
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00w\x00\x00\x00\x7f\x08\x06\x00\x00\x00\xd5j]\xe7\x00\x00\x00\x19tEXtSoftware\x00Adobe ImageReadyq\xc9e<\x00\x00\x03"iTXtXML:com.adobe.xmp\x00\x00\x00\x00\x00
The problam is that I cant figute out how to convert this byte format into real image..and display it on a web page directly from database.
I try to make several variants to solve this problam..but in some how my mind is blow up..and I really dont undestand how to work with it.
Thanks for your time :)
IF somebady have any idias or advice how can I show images from database into client side...
I did it! :)
I figured out how to fix this by myself.
Actually the problem was in my response...and in some case on client side too.
Because when I send request from the server, I send the data in byte format,
print(type(image.read()))
<class 'bytes'>
while at the client I suggested the something like binary string
<img src="data:image/png;base64,{{images}}" alt="">
There is my solution code:
import codecs
base64_data = codecs.encode(image.read(), 'base64')
image = base64_data.decode('utf-8')
And on the client I receive the string, which I paste into the img tag...and taddaaaa I got image from my database.
Thanks all who try to help me or figure out how to fix my issue.
I'm not sure that is the best practice, but it works.
P.S. sorry for my English :P
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 }}