Why does this image not displaying (broken image icon)? - python

I am trying to display an image that I saved to Datastore with DisplayImage handler below but I only see a broken image link. Do you know why? Thanks!
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
...
class ImageUpload(webapp.RequestHandler):
def get(self):
...
self.response.out.write("""
<form action="/imagesave" enctype="multipart/form-data" method="post">
<div><label>firm name:</label> <input type="text" name="firm_name" size=40></div>
<div><input type="file" name="img" /></div>
<div><input type="submit" value="Upload image"></div>
</form>
""")
class ImageSave(webapp.RequestHandler):
def post(self):
homepage = HomePage()
thumbnail = self.request.get("img")
firm_name = self.request.get("firm_name")
homepage.thumbnail = db.Blob(thumbnail)
homepage.firm_name = firm_name
homepage.put()
self.redirect("/imageupload")
class ImageResize(webapp.RequestHandler):
def post(self):
q = HomepageImage.all()
q.filter("firm_name", "mta")
qTable = q.get()
if qTable:
qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32))
db.put(qTable)
else:
self.response.out.write("""firm not found""")
self.redirect("/imageupload")
class DisplayImage(webapp.RequestHandler):
def get(self):
query = HomePage.all()
query.filter("firm_name", "mta")
result = query.get()
self.response.out.write("""firm name: %s""" % result.firm_name)
self.response.out.write("""<img src="img?img_id=%s"></img>""" %
result.key())
...

To serve an image from blobstore, use get_serving_urlor if you have a blobproperty you can have a look at my old code that used to serve my blobproperties from an image class back before when there was no blobstore:
class Image(db.Model):
name = db.StringProperty()
desc = db.StringProperty()
owner = db.UserProperty()
secret = db.StringProperty()
full = db.BlobProperty()
full_ext = db.StringProperty()
small = db.BlobProperty()
small_ext = db.StringProperty()
thumb = db.BlobProperty()
thumb_ext = db.StringProperty()
published = db.BooleanProperty()
added = db.DateTimeProperty(auto_now_add=True)
modified = db.DateTimeProperty(auto_now=True)
def thumb_name(self):
return '%s.%s' % (self.key(), self.thumb_ext)
def small_name(self):
return '%s_small.%s' % (self.key(), self.small_ext)
def full_name(self):
return '%s_full.%s' % (self.key(), self.full_ext)
class UploadImage(webapp.RequestHandler):
def post(self, key):
im = db.get(db.Key(key))
if not im:
self.error(404)
return
if self.request.POST['id'] != im.secret:
self.error(400)
return
file_data = self.request.POST['file'].file.read()
if self.request.POST['size'] == '100x100':
im.thumb = file_data
a = 'small'
elif self.request.POST['size'] == '500x500':
im.small = file_data
a = 'full'
if im.small and im.thumb:
im.published = True
im.save()
logging.info("%s updated %s" % (im.key(), a) )
self.response.out.write("ok")
mimetypes = {
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
'tiff': 'image/tiff',
'tif': 'image/tiff',
'gif': 'image/gif',
'png': 'image/png',
}
class ServeImage(webapp.RequestHandler):
def get(self, key, sz, ext):
im = db.get(db.Key(key))
if not im:
self.error(404)
return
if sz == '.':
d = im.thumb
elif sz == '_small.':
d = im.small
elif sz == '_full.':
d = im.full
else:
raise Exception('wrong sz %r' % sz)
if not d:
d = im.full
else:
self.response.headers.add_header("Expires", "Thu, 01 Dec 2014 16:00:00 GMT")
self.response.headers["Content-Type"] = mimetypes[ext]
self.response.out.write(d)

This question was answered by systempuntoout in my followup question. He noted that I was pointing the image source to a not defined wrong img route.
The correct link should point to /image like this:
<img src="/image?img_id=%s"></img>

Related

After importing variable from view.py into. No dropdown appearing in forms

I am using Django forms in in forms I need a variable from views.py named 'layer_id'. So I get it like
self.form = labelModelForm(layer_id=self.layer.id)
and used in forms.py like
class labelModelForm(forms.ModelForm):
model = Labels_tool_
def __init__(self, *args , **kwargs):
layer_id = kwargs['layer_id']
apn= forms.ModelChoiceField(queryset=Field.objects.filter(layer=layer_id).values_list('name', flat=True) ,empty_label="(Choose field)")
So now when I run program no dropdown list appear. Where I am wrong ? As layer_id I am getting is correct in form in view.py
My View.py file is
def ImportLabelView(self):
urlItems =self.request.path.split('/')
i = urlItems.index('layers')
self.form = labelModelForm(layer_id=self.layer.id)
if self.request.method == 'POST':
self.layer = Layer.objects.filter(id=urlItems[i + 1],map=self.map.id).first()
layerid= self.layer.id
labmapid=self.map.id
OwnerName = self.request.POST.get('owner_name')
MailingAddrOne = self.request.POST.get('mailing_addr_One')
mailingaddrTwo = self.request.POST.get('mailing_addr_Two')
ApN = self.request.POST.get('apn')
situsaddrTwo = self.request.POST.get('situs_addr_Two')
situsaddrOne = self.request.POST.get('situs_addr_One')
if Labels_tool_.objects.filter(map_id_labels=labmapid ,layer_id_labels=layerid).exists():
Labels_tool_.apn = Labels_tool_.objects.filter(map_id_labels = labmapid , layer_id_labels = layerid).update(apn=ApN)
Labels_tool_.owner_name = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(owner_name=OwnerName)
Labels_tool_.mailing_addr_One = Labels_tool_.objects.filter(map_id_labels=labmapid,
layer_id_labels=layerid).update(mailing_addr_One=MailingAddrOne)
Labels_tool_.mailing_addr_Two = Labels_tool_.objects.filter(map_id_labels=labmapid,
layer_id_labels=layerid).update(mailing_addr_Two=mailingaddrTwo)
Labels_tool_.situs_addr_One = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(situs_addr_One=situsaddrOne)
Labels_tool_.situs_addr_Two = Labels_tool_.objects.filter(map_id_labels=labmapid, layer_id_labels=layerid).update(situs_addr_Two=situsaddrTwo)
else:
labels_tool = Labels_tool_()
labels_tool.apn = self.request.POST.get('apn')
labels_tool.owner_name = self.request.POST.get('owner_name')
labels_tool.mailing_addr_One= self.request.POST.get('mailing_addr_One')
labels_tool.mailing_addr_Two= self.request.POST.get('mailing_addr_Two')
labels_tool.situs_addr_One = self.request.POST.get('situs_addr_One')
labels_tool.situs_addr_Two = self.request.POST.get('situs_addr_Two')
labels_tool.map_id_labels = self.map.id
labels_tool.layer_id_labels = self.layer.id
labels_tool.save()
# self.form = self.layer.form(self.request.POST)
return self.redirect('mapport.maps.layers.importlabel', self.map.id, self.layer.id)
return self.render('mapport/maps/layers/Labels_detail.html')
And template file is
<form action="" method="post" id="label_form">{% csrf_token %}
<div id="field1"><p id="apn_text">APN: </p> {{ form.apn}}</div>
Models are like
class pdftabel_tool_(models.Model):
apn = models.CharField(null=True, blank=False, max_length=255)
Now where I am making mistake that value from view.py is correct but not dropdown showing ?
You need to set self.fields, not self.initial.
You should define the field in the normal way at class level, then modify the queryset in the init method.
class labelModelForm(forms.ModelForm):
apn = forms.ModelChoiceField(queryset=Field.objects.none())
def __init__(self, *args, **kwargs):
layer_id = kwargs.pop('layer_id', None)
super(labelModelForm, self).__init__(*args, **kwargs)
self.fields['apn'].queryset = Field.objects.filter(layer=layer_id)

Google App Engine: Extracting the value of the radio button chosen

I'm building an application which allows users to create surveys and vote on the questions of the surveys. Now, the answers to those questions will be stored in the datastore so that I can analyze the results in the end. However, I am unable to figure out a way to extract the value of the radio button chosen by the user. Each question has three options, all of whom represented by a radio button.
Here's the code:
main.py
import os
import webapp2
import jinja2
from google.appengine.ext import db
from random import randint
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
#databases
class Survey(db.Model):
vam_id = db.StringProperty()
subject = db.StringProperty(required = True)
description = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
q1 = db.TextProperty(required = True)
o11 = db.TextProperty(required = True)
o12 = db.TextProperty(required = True)
o13 = db.TextProperty(required = True)
q2 = db.TextProperty(required = True)
o21 = db.TextProperty(required = True)
o22 = db.TextProperty(required = True)
o23 = db.TextProperty(required = True)
q3 = db.TextProperty(required = True)
o31 = db.TextProperty(required = True)
o32 = db.TextProperty(required = True)
o33 = db.TextProperty(required = True)
q4 = db.TextProperty(required = True)
o41 = db.TextProperty(required = True)
o42 = db.TextProperty(required = True)
o43 = db.TextProperty(required = True)
q5 = db.TextProperty(required = True)
o51 = db.TextProperty(required = True)
o52 = db.TextProperty(required = True)
o53 = db.TextProperty(required = True)
class Votes(db.Model):
vam_id = db.StringProperty(required = True)
q1_opt = db.TextProperty(required = True)
q2_opt = db.TextProperty(required = True)
q3_opt = db.TextProperty(required = True)
q4_opt = db.TextProperty(required = True)
q5_opt = db.TextProperty(required = True)
class MainPage(Handler):
def get(self):
self.render("homepage.html")
class NewSurvey(Handler):
def get(self):
self.render("newsurvey.html")
def post(self):
vam_id = str(randint(1, 500))
subject = self.request.get("title")
description = self.request.get("description")
q1 = self.request.get("q1")
o11 = self.request.get("o11")
o12 = self.request.get("o12")
o13 = self.request.get("o13")
q2 = self.request.get("q2")
o21 = self.request.get("o21")
o22 = self.request.get("o22")
o23 = self.request.get("o23")
q3 = self.request.get("q3")
o31 = self.request.get("o31")
o32 = self.request.get("o32")
o33 = self.request.get("o33")
q4 = self.request.get("q4")
o41 = self.request.get("o41")
o42 = self.request.get("o42")
o43 = self.request.get("o43")
q5 = self.request.get("q5")
o51 = self.request.get("o51")
o52 = self.request.get("o52")
o53 = self.request.get("o53")
a = Survey(vam_id = vam_id, subject = subject, description = description, q1 = q1,
o11 = o11, o12 = o12, o13 = o13, q2 = q2,
o21 = o21, o22 = o22, o23 = o23, q3 = q3,
o31 = o31, o32 = o32, o33 = o33, q4 = q4,
o41 = o41, o42 = o42, o43 = o43, q5 = q5,
o51 = o51, o52 = o52, o53 = o53)
a.put()
class Existing(Handler):
def get(self):
surveys = Survey.all()
self.render("existingsurvey.html", surveys = surveys)
class PermaSurvey(Handler):
def get(self):
vam = self.request.get("vam_id")
su = Survey.all().filter("vam_id =", vam).get()
self.render("perma.html", su = su)
def post(self):
vam = self.request.get("vam_id")
q1_opt = self.request.get("q1")
q2_opt = self.request.get("q2")
q3_opt = self.request.get("q3")
q4_opt = self.request.get("q4")
q5_opt = self.request.get("q5")
v = Votes(vam_id = vam, q1_opt = q1_opt, q2_opt = q2_opt, q3_opt = q3_opt,
q4_opt = q4_opt, q5_opt = q5_opt)
v.put()
app = webapp2.WSGIApplication([('/', MainPage),
('/new', NewSurvey),
('/existing', Existing),
('/perma', PermaSurvey)], debug=True)
perma.html
<html>
<head>
<title>Perma Survey</title>
</head>
<body>
<form method = "post">
{% block content %}
<h2>{{su.subject}}</h2>
<p>{{su.description}}</p>
<br>
{{su.q1}}
<br>
<input type="radio" name="q1">{{su.o11}}<br>
<input type="radio" name="q1">{{su.o12}}<br>
<input type="radio" name="q1">{{su.o13}}
<hr>
{{su.q2}}
<br>
<input type="radio" name="q2">{{su.o21}}<br>
<input type="radio" name="q2">{{su.o22}}<br>
<input type="radio" name="q2">{{su.o23}}
<hr>
{{su.q3}}
<br>
<input type="radio" name="q3">{{su.o31}}<br>
<input type="radio" name="q3">{{su.o32}}<br>
<input type="radio" name="q3">{{su.o33}}
<hr>
{{su.q4}}
<br>
<input type="radio" name="q4">{{su.o41}}<br>
<input type="radio" name="q4">{{su.o42}}<br>
<input type="radio" name="q4">{{su.o43}}
<hr>
{{su.q5}}
<br>
<input type="radio" name="q5">{{su.o51}}<br>
<input type="radio" name="q5">{{su.o52}}<br>
<input type="radio" name="q5">{{su.o53}}
<hr>
<br>
<input type = "submit">
{% endblock %}
</form>
</body>
</html>
Now, no matter what options I select from the three listed ones, the value that's stored in the datastore is 'on', indicating that a radio button from the radio button group is selected. How can I store the actual choices that were chosen by the user into the datastore ?
You have not assigned any values to your form elements. I think you want:
<input type="radio" name="q3" value="{{su.o31}}" />{{su.o31}}<br>
Now, you can retrieve it's value. Since you're already using jinja, I suggest you use the WTForms package to make this all easier.

How To Get Blob Key with Python?

I am having difficulties in storing and then retrieving the blobstore key. It looks like I am able to get the database row key # instead of the blob key#....
1) I am not sure how to store the key
2) Also, I am not sure how the data currently gets stored into the UserPhoto datastructure
set up
3) How do I retrieve the Blob's key related to the current user, so I can display a link to i?
any help would be greatly appreciated.
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext import db
import urllib
class UserPhoto(db.Model):
user = db.StringProperty()
user1 = db.EmailProperty()
blob_prop = blobstore.BlobKey
blob_key = blobstore.BlobReferenceProperty()
class MainPage(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
upload_url = blobstore.create_upload_url('/upload')
existing_data = "<br>"
if user:
data = UserPhoto.all()
#filter data by user e-mail
results = data.filter("user1 = ", user.email())
for dt in results:
existing_data +='<a href="/serve/%s' % dt.key() + '">'
existing_data += '%s' % dt.key() + '<br>'
self.response.out.write(
'<div align=center>Hello %s <a align="center" href="%s">Sign out</a><br>Is administrator: %s' %
(user.nickname(), users.create_logout_url("/"), users.is_current_user_admin())
+'<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url+
"""<br>Upload File: <input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form>
<br>"""+existing_data + "</div>"
)
#the code below is used for testing...purposes only...
for b in blobstore.BlobInfo.all():
self.response.out.write('<li>' + str(b.filename) + '')
else:
self.redirect(users.create_login_url(self.request.uri))
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
upload_files = self.get_uploads('file') # 'file' is file upload field in the form
blob_info = upload_files[0]
user = users.get_current_user()
if user:
data = UserPhoto()
data.user1 = users.get_current_user().email()
data.blob_key = str(blob_info.key())
# data.user2[0] = self.get_uploads()
data.blob_prop = blob_info.key()
data.put()
#self.redirect('/serve/%s' % blob_info.key())
self.redirect('/')
class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, photo_key):
blob_key = str(urllib.unquote(photo_key))
if not blobstore.get(photo_key):
self.error(404)
else:
#self.send_blob(photo_key)
#self.send_blob('/serve/%s' % photo_key)
self.send_blob(blobstore.BlobInfo.get(blob_key), save_as=True)
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, resource):
resource = str(urllib.unquote(resource))
blob_info = blobstore.BlobInfo.get(resource)
self.send_blob(blob_info)
application = webapp.WSGIApplication([('/', MainPage),
('/upload', UploadHandler),
('/serve/([^/]+)?', ServeHandler),
('/view_photo/([^/]+)?', ViewPhotoHandler)
],debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
You're asking for the UserPhoto entity key when you construct the output, not the blobstore reference within that entity. It should be:
existing_data +='<a href="/serve/%s">' % dt.blob_key

How to display an image in GAE datastore?

I read the tutorial and all the sources I could find about displaying an image saved in datastore and still I could not make it work. I appreciate any help. This is my previous question.
The code below, for /displayimage shows broken link for the image; and for /image it gives BadKeyError: Invalid string key . According to Nick Johnson reply here I must be passing an empty string for img_id but logging.info in /display image shows this key: (((result.key():)))) agpkZXZ-dGluZy0xcg8LEghIb21lUGFnZRjOCAw. Thanks for your help.
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
class ImageUpload(webapp.RequestHandler):
def get(self):
...
self.response.out.write("""
<form action="/imagesave" enctype="multipart/form-data" method="post">
<div><label>firm name:</label> <input type="text" name="firm_name" size=40></div>
<div><input type="file" name="img" /></div>
<div><input type="submit" value="Upload image"></div>
</form>
""")
class ImageSave(webapp.RequestHandler):
def post(self):
homepage = HomePage()
thumbnail = self.request.get("img")
firm_name = self.request.get("firm_name")
homepage.thumbnail = db.Blob(thumbnail)
homepage.firm_name = firm_name
homepage.put()
self.redirect("/imageupload")
class ImageResize(webapp.RequestHandler):
def post(self):
q = HomepageImage.all()
q.filter("firm_name", "mta")
qTable = q.get()
if qTable:
qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32))
db.put(qTable)
else:
self.response.out.write("""firm not found""")
self.redirect("/imageupload")
class DisplayImage(webapp.RequestHandler):
def get(self):
...
query = HomePage.all()
query.filter("firm_name", "mta")
result = query.get()
self.response.out.write("""firm name: %s""" % result.firm_name)
#self.response.out.write("""<img src="img?img_id=%s"></img>""" %
#chenged this line as systempuntoout's comment to:
self.response.out.write("""<img src="/image?img_id=%s"></img>""" %
result.key())
#but I still get the same error
class Image(webapp.RequestHandler):
def get(self):
...
#I am adding the next line to show that "img_id" is an empty string.
#why "img_id" empty here?
img_id = self.request.get("img_id")
logging.info("""**************************img_id: %s**************************""" % img_id)
#**************************img_id: **************************
homepage = db.get(self.request.get("img_id"))
if homepage.thumbnail:
self.response.headers['Content-Type'] = "image/jpg"
self.response.out.write(homepage.thumbnail)
else:
self.response.out.write("no image")
application = webapp.WSGIApplication(
[
("/imageresize",ImageResize),
("/imageupload", ImageUpload),
("/displayimage", DisplayImage),
("/imagesave", ImageSave),
("/image", Image),
],
debug=True
)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
You are pointing the image source to a not defined wrong img route .
The correct link should point to /image like this:
<img src="/image?img_id=%s"></img>
I've tested your code with my correction and it works nicely:
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
class HomePage(db.Model):
thumbnail = db.BlobProperty()
firm_name = db.StringProperty()
class ImageUpload(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<form action="/imagesave" enctype="multipart/form-data" method="post">
<div><label>firm name:</label> <input type="text" name="firm_name" size=40></div>
<div><input type="file" name="img" /></div>
<div><input type="submit" value="Upload image"></div>
</form>
""")
class ImageSave(webapp.RequestHandler):
def post(self):
homepage = HomePage()
thumbnail = self.request.get("img")
firm_name = self.request.get("firm_name")
homepage.thumbnail = db.Blob(thumbnail)
homepage.firm_name = firm_name
homepage.put()
self.redirect("/imageupload")
class ImageResize(webapp.RequestHandler):
def post(self):
q = HomepageImage.all()
q.filter("firm_name", "mta")
qTable = q.get()
if qTable:
qTable.thumbnail = db.Blob(images.resize(self.request.get("img"), 32, 32))
db.put(qTable)
else:
self.response.out.write("""firm not found""")
self.redirect("/imageupload")
class DisplayImage(webapp.RequestHandler):
def get(self):
query = HomePage.all()
query.filter("firm_name", "mta")
result = query.get()
self.response.out.write("""firm name: %s""" % result.firm_name)
self.response.out.write("""<img src="/image?img_id=%s"></img>""" %
result.key())
class Image(webapp.RequestHandler):
def get(self):
img_id = self.request.get("img_id")
logging.info("""**************************img_id: %s**************************""" % img_id)
homepage = db.get(self.request.get("img_id"))
if homepage.thumbnail:
self.response.headers['Content-Type'] = "image/jpg"
self.response.out.write(homepage.thumbnail)
else:
self.response.out.write("no image")
application = webapp.WSGIApplication(
[
("/imageresize",ImageResize),
("/imageupload", ImageUpload),
("/displayimage", DisplayImage),
("/imagesave", ImageSave),
("/image", Image),
],
debug=True
)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()

App Engine, Python: problem updating datastore record

I need to update a record in the datastore, but instead of updated record I get always a new record.
My model:
class PageModel(db.Model):
title = db.StringProperty()
content = db.TextProperty()
reference = db.SelfReferenceProperty()
user = db.UserProperty(auto_current_user = True)
created = db.DateTimeProperty(auto_now_add = True)
modified = db.DateTimeProperty(auto_now = True)
type = db.StringProperty()
template = db.StringProperty()
position = db.IntegerProperty()
hidden = db.BooleanProperty()
historical = db.BooleanProperty()
My handler:
class EditHandler(webapp.RequestHandler):
def post(self):
if self.request.path[6:] == '':
page_id = 8
else:
page_id = int(self.request.path[6:]) # path: /edit/35
#id = self.request.get('id')
CP = PageModel.get_by_id(int(page_id))
key = CP.key()
title = self.request.get('title')
content = self.request.get('content')
type = self.request.get('type')
hidden = self.request.get('hidden')
#position = self.request.get('type')
reference = PageModel.get_by_id(int(self.request.get('reference')))
template = self.request.get('template')
if ".htm" not in template:
template = "index.htm"
#if title == '' or content == '':
#doRender(self,'create_page.htm',{'error' : 'Please fill in all fields'} )
#return
#edited_page = PageModel(key=CP.key, title=title, content=content, type=type, reference=reference, template=template)
edited_page = PageModel()
edited_page.key = CP.key()
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
There should be something wrong with edited_page.key = CP.key(), or what?!
Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.
edited_page = CP
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()

Categories

Resources