I want to make a webpage with Flask which enables me to search images according to some keywords and return two relevant images in the webpage.
And, assume the keyword is 'Steve jobs' and these images that are related to 'Steve jobs' will be scraped by Google Search and stored in a file called 'Steve jobs'.
But I still cannot display images from my file and return a blank page.
hello.py
#app.route("/about",methods=['GET', 'POST'])
def about():
...
DIR = os.path.join(os.getcwd())
DIR = os.path.join(DIR, query.split()[0])
...
def show_index():
for i,(img,Type) in enumerate(ActualImages[:2]):
try:
req = urllib.request.Request(img, headers=header)
raw_img = urllib.request.urlopen(req).read()
cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1
print(cntr)
if len(Type)==0:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+".jpg"),'wb')
else:
f = open(os.path.join(DIR,image_type + "_"+ str(cntr)+"."+Type),'wb')
f.write(raw_img)
f.close()
except Exception as e:
print('>>> Could not load: '+img)
print(e)
return f
return render_template('about.html', f = f)
about.html
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<img src="{{f}}" alt="f">
</body>
</html>
A typical HTML image tag looks like so:
<img src="/path/image.gif" alt="My Image"/>
As you can see, the src attribute contains a URL telling the browser where to find the image. It will go off and download the image from there. It doesn't contain the image itself. Your code appears to be trying to load the image file's content into the HTML, and that won't work.
(Note - it is possible to directly embed images into HTML, but it's pretty unusual, so I won't talk about that.)
Given that, what you need to is to put the images somewhere, and serve and refer to them as per the answer to How do i link to images not in Static folder in flask.
Related
I'm trying to convert a HTML file to BytesIO so that I don't need to write the file in the filesystem and get it from memory instead. I've read this about converting image to BytesIO however I can't apply it to HTML file.
I'm using Flask as my framework.
What i have tried:
buffer = io.BytesIO()
merged_df.to_html(buffer, encoding = 'utf-8', table_uuid = 'seasonality_table')
buffer.seek(0)
html_memory = base64.b64encode(buffer.getvalue())
return render_template('summary_01.html', html_data = html_memory.decode('utf-8'))
then in the HTML code which I want to output the html file:
<img id="picture" src="data:html;base64, {{ html_data }}">
Error message I got =
TypeError: expected str, bytes or os.PathLike object, not _io.BytesIO
First: using <img> to display HTML is totally wrong idea.
Tag <img> is only for images like PNG, JPG, etc.
You can get directly HTML using to_html() without filename
html = merged_df.to_html(table_id='seasonality_table')
and send this as HTML
return render_template('summary_01.html', html_data=html)
and you need safe to display it as HTML
{{ html_data | safe }}
BTW:
If you want to put data as file for downloading then you should use <a> instead of <img> and it may need application/octet-stream instead of html to start downloading it.
html = merged_df.to_html(table_id='seasonality_table')
html = base64.b64encode(html.encode('utf-8')).decode('utf-8')
return render_template('summary_01.html', html_data=html)
DOWNLOAD
Minimal working example
from flask import Flask, render_template_string
import pandas as pd
import base64
app = Flask(__name__)
#app.route('/')
def index():
data = {
'A': [1,2,3],
'B': [4,5,6],
'C': [7,8,9]
}
df = pd.DataFrame(data)
html = df.to_html(table_id='seasonality_table')
html_base64 = base64.b64encode(html.encode()).decode()
return render_template_string('''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
{{ html_data | safe }}
DOWNLOAD
</body>
</html>''', html_data=html, html_base64=html_base64)
if __name__ == '__main__':
#app.debug = True
#app.run(threaded=False, processes=3)
#app.run(use_reloader=False)
app.run()
I have written bunch of code but it is not rendering the chart inside HTML for some reason. Program however runs and creates an image in Static folder. Can someone tell me how I can pass this "image" in Jinja2 in in HTML in order to view it in HTML?
Flask code:
#app.route('/', methods=['GET', 'POST'])
def index():
image = False
from flask import Flask, render_template, request
if request.method == 'POST':
a = int(request.form['a'])
x = np.linspace(-20, 20, 20)
y = a * x
plt.plot(x,y)
plt.savefig('C:/Users/name/PycharmProjects/qtcalc1/static/image.png')
image = url_for('static', filename = image)
print(image)
plt.show()
return render_template('graphtry.html', image = image)
Note view function code is indented well on my end. I need solution for how to render this image in my HTML file graphtry.html using Jinja2. My current HTML code is as follows:
<img src ="{{image}}" >
When you write
image = url_for('static', filename = image)
the value of image variable in the argument is False (from line 3). You have to pass the actual filename, that is in this example: image.png.
image = url_for('static', filename='image.png')
And also, remove the extra space after src attribute:
<img src="{{image}}" />
Below is the code
urls.append('http://google.com')
urls.append('http://stacoverflow.com')
whole = """<html>
<head>
<title>output -</title>
</head>
<body>Below are the list of URLS
%s // here I want to write both urls.
</body>
</html>"""
for x in urls:
print x
f = open('myfile.html', 'w')
f.write(whole)
f.close()
So this is the code for saving the file in HTML format. But I can't find the way to get the contents of for loop into HTML file. In other words, I want to write a list of indexes elements i.e. http://google.com, http://stackoverflow.com into my HTML file. As you can see that I have created myfile.html as HTML file, So I want to write both URLs which are in the list of indexes into my HTML file
Hope this time I better explain?
How can I? Would anyone like to suggest me something? It would be a really big help.
Try below code:
urls.append('http://google.com')
urls.append('http://stacoverflow.com')
whole = """<html>
<head>
<title>output -</title>
</head>
<body>Below are the list of URLS
%s
</body>
</html>"""
f = open('myfile.html', 'w')
f.write(whole % ", ".join(urls))
f.close()
Using
Framework -- Flask
Language -- html ,python
Steps:
passing the name of file to be generated from template
desired file name is generated using a backend server which is an image
generated image is copied/replaced in static folder
template shows the image on webpage
but if 2 images are generated of same name ,template doesn't show the recent image
here is the code snippet :
template - <img src="{{ url_for('static',filename=file) }}" style="float:center" width="300" height="200" alt="image not found">
code that replaces the file static folder :
def copyFileAndFindUrl(path):
IMAGE_DIR='img/gol/'
STATIC_DIR='./static/'
url_file = ""
#get basename of path:-->45:67.jpg
base_name = getBaseName(path)
print "baseName:",base_name
#base_name = 'temp.jpg'
#concat -> "img/" + baseFileName
url_file = IMAGE_DIR + base_name #"img/56:67.jpg"
print "url file:",url_file
#copy(path,concat);return error
dest_file = STATIC_DIR + url_file
print "destination file:",dest_file
if os.path.exists(dest_file):
os.remove(dest_file)
print "removed:",dest_file
print "checking after re:",os.path.exists(dest_file)
ret = copyToStatic (path,dest_file)
if ret :
url_file = ''
return ret,url_file
#return concated file to display in webform
return ret,url_file
please let me know ,why after replacing the files ,recent image is not shown!!!
I want to generate a html template to a pdf file using pisa. I believe I have all the packages I need but I seem to be having problems doing so. Here is my view below so
far what I have done.
EDIT: Here is my latest url, views & template.
url.py
(r'^index/render_pdf/(?P<id>\d+)/$', render_pdf),
views.py
def fetch_resources(uri, rel):
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html, id):
invoice_items_list = Invoice_Items.objects.filter(pk=id)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
In a template, I have this tag.
<a href="{% url c2duo.views.render_pdf invoices.pk %}">
I dont know how much this will help, but this is the function i use to render the pdf:
def fetch_resources(uri, rel):
"""
Callback to allow pisa/reportlab to retrieve Images,Stylesheets, etc.
`uri` is the href attribute from the html link element.
`rel` gives a relative path, but it's not used here.
"""
path = os.path.join(settings.MEDIA_ROOT, uri.replace(settings.MEDIA_URL, ""))
return path
def render_pdf (html):
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), dest=result, link_callback=fetch_resources)
return result
Just for fun, try this instead:
def render_to_pdf(template_src, context_dict):
html = "<html><head><title>Title</title></head><body><h1>Hello</h1></body></html>"
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html), result)
if not pdf.err:
return http.HttpResponse("" % (repr(result.getvalue())))
else:
raise Exception("The error was %s" % pdf.err)
If you still encounter an error, I'm guessing the error might be in pisa. Are you sure it's up to date?