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.
Related
I am a beginner in Django and Python. I am creating a Payroll project whose calculations are done using a function from models.py. The user must input the variables through templates and save it to sql. Then search for the employee (through templates again) and output his payroll details. That is the time when I want to use the calculation function.
Data from the database is working and is outputted by the templates. As for the calculated data, it simply isn't showing.
I have been trying to use the function to no avail and I've searched for 3 days already. I am at lost at what to do now.
models.py
from django.db import models
#Class in model.py acts as a table in database
class Add_Employee(models.Model):
name = models.CharField (max_length = 150, default = '', null = False)
position = models.CharField (max_length = 150, default = '', null = False)
email = models.EmailField (max_length = 150, default = '', null = False)
address = models.CharField (max_length = 500, default = '', null = False)
basic_pay = models.FloatField(default=None)
overtime_hours = models.IntegerField(default=None)
allowance = models.FloatField(default=None)
days_leave = models.IntegerField(default=None)
other_deductions = models.FloatField(default=None)
#Django admin page; the table will show the name
def __str__(self):
return '{}{}'.format(self.name, self.position, self.email, self.address)
def salary_calculation(self):
#Earnings
self.overtime_hours_pay = self.overtime_hours * 64
self.gross_income = self.basic_pay + self.overtime_hours + self.allowance
#Deductions
self.days_leave = self.days_leave * 512
self.pagibig = self.basic_pay * 0.01
self.gsis = self.basic_pay * 0.09
self.withholdingtax = self.basic_pay * 0.15
self.philhealth = self.basic_pay * 0.0275 / 2
self.total_deductions = self.days_leave + self.pagibig + self.gsis + self.withholdingtax + self.philhealth
#Net Pay
self.net_pay = self.gross_income - self.total_deductions
print ("Calculated.") #this was never outputted from all the times i tried.
return (self)
views.py
#Code for form submission and redirect back to employer page again
def add_employee_form_submit(request):
print ("Form is successfully submitted.") #print can only be seen on the terminal, not the browser
#create local variable for each variable entered using the form
name = request.POST["name"]
address = request.POST["address"]
email = request.POST["email"]
position = request.POST["position"]
basic_pay = request.POST["basic_pay"]
overtime_hours = request.POST["overtime_hours"]
allowance = request.POST["allowance"]
days_leave = request.POST["days_leave"]
other_deductions = request.POST["other_deductions"]
#assigning the local variable into the database fields
employee_info = Add_Employee(name = name, address = address, email = email, position = position, basic_pay = basic_pay, overtime_hours = overtime_hours, allowance = allowance, days_leave = days_leave, other_deductions = other_deductions )
#save the entire stuff
employee_info.save()
return render(request, 'employer.html')
def search_employee_form_submit(request):
if request.method == "POST":
search_id = request.POST['search_id']
if search_id:
employee_match = Add_Employee.objects.filter( pk = search_id ) #pk is primary key
if employee_match:
return render (request, 'employee.html', {'Search': employee_match})
else:
messages.error(request, 'No results found.')
else:
return HttpResponseRedirect('employee/')
return render(request, 'employee.html')
employee.html (template for query and result viewing)
<h1>Employee Payroll</h1>
<br><br>
<h2>Enter your ID:</h2>
<form action="/search_employee_form_submit/", method="post"> <!--it will use 'search_employee_form_submit' url after submitting form-->
{% csrf_token %} <!-- added for privacy reasons/security-->
<br>
<input type = "text" name="search_id" placeholder="Enter employee id">
<br><br>
<input type="submit" value="search employee">
</form>
<br><br>
<!-- Code for when your search has results / employee -->
{% if Search %}
{% for k in Search %}
Name:
{{ k.name }} <br>
Position:
{{ k.position }} <br>
Email:
{{ k.email }} <br>
..... etc (this part is working)
Overtime Hour Pay:
{{ k.overtime_hours_pay }}<br>
Gross Income:
{{ k.gross_income }}<br><br>
..... etc (calculated data = doesnt show result)
{% endfor %}
Pardon me for the long post as I have no idea where I am missing something.
First of all, you are referencing fields that do not exist in the model, such as overtime_hours_pay and gross-income. If you do self.someFieldName on a model instance, that field should be defined or inherited in the model. So this is wrong:
self.overtime_hours_pay = self.overtime_hours * 64
You could either
Add those fields in the model definition
Remove the self part and make them normal variables. Which would look like:
def salary_calculation(self):
overtime_hours_pay = self.overtime_hours * 64
gross_income = self.basic_pay + self.overtime_hours + self.allowance
self.days_leave = self.days_leave * 512
pagibig = self.basic_pay * 0.01
gsis = self.basic_pay * 0.09
withholdingtax = self.basic_pay * 0.15
philhealth = self.basic_pay * 0.0275 / 2
total_deductions = self.days_leave + pagibig + gsis + withholdingtax + philhealth
net_pay = gross_income - total_deductions
return net_pay
After doing that, you could calculate net_pay in the view.
...
if employee_match:
# calculation
net_pay = employee_match.salary_calculation()
# then pass this to the template
return render (request, 'employee.html', {'Search': employee_match, 'net_pay': net_pay})
else:
messages.error(request, 'No results found.')
Below is the form in quiz.html file.
I don't know how to get the value from a clicked button after submitting the form and writing in /testform.
<html>
<form method="post" action="/testform">
Q1. where are you from?<br>
<input type = "radio" name = "q_1" value ="a">Iraklio</br>
<input type = "radio" name = "q_1" value = "b">Patra</br>
<input type = "radio" name = "q_1" value = "c">Athens</br>
<input type = "submit" value = "submit" >
</form>
</html>
Python script:
import webapp2
import jinja2
templateLoader = jinja2.FileSystemLoader( searchpath="./")
templateEnv = jinja2.Environment( loader=templateLoader )
class quiz(webapp2.RequestHandler):
def get(self):
TEMPLATE_FILE = "quiz.html"
template = templateEnv.get_template( TEMPLATE_FILE )
x = template.render()
self.response.write(x)
class test(webapp2.RequestHandler):
def post(self):
ans = self.request.get('value')
print ans
self.response.write(ans)
app = webapp2.WSGIApplication([('/',quiz),('/testform',test)]
,debug = True)
def main():
from paste import httpserver
httpserver.serve(app, host='127.0.0.1', port='8080')
if __name__ == '__main__':
main()
My objective was:
to print in a subpage (/testform) the letter of the clicked button after submitting the post form.
My mistake was that in : ans = self.request.get('value') , i had to replace 'value' with 'q_1'.Then it worked fine.!!
p.s. https://webapp2.readthedocs.io/en/latest/guide/request.html
I have this error
MultiValueDictKeyError at /registroEstudianteMayor/"'Acudiente'" ",
I searched a lot for an answer to this error but I couldn't find any.
I have this controller:
def post(self, request, *args, **kwargs):
generos = parametros['generos']
tiposDocumento = parametros['tiposDocumento']
zonas = parametros['zonas']
#Toma de datos
numeroDocumento = request.POST['numeroDocumento']
tipoDocumento = request.POST['tipoDocumento']
contrasena = request.POST['contrasena']
contrasena2 = request.POST['contrasena2']
correoElectronico = request.POST['correoElectronico']
nombres = request.POST['nombres']
apellidos = request.POST['apellidos']
fechaNacimiento = request.POST['fechaNacimiento']
genero = request.POST['genero']
direccion = request.POST['direccion']
barrio = request.POST['barrio']
telefonoFijo = request.POST['telefonoFijo']
telefonoCelular = request.POST['telefonoCelular']
seguridadSocial = request.POST['seguridadSocial']
#Toma de datos particulares
nombreAcudiente = request.POST['Acudiente']
telefonoAcudiente = request.POST['telefonoAcudiente']
foto = request.FILES['foto']
cedula = request.FILES['cedula']
#Inicializo datos opcionales
zona = ""
comuna = ""
grupoEtnico = ""
condicion = ""
enviarInfoAlCorreo = False
#Inicializo Datos Opcionales particulares
desempeno = ""
lugar = ""
#Tomo los datos opcionales
if request.POST['zona']: zona = request.POST['zona']
if request.POST['comuna']: comuna = request.POST['comuna']
if request.POST['grupoEtnico']: grupoEtnico = request.POST['grupoEtnico']
if request.POST['condicion']: condicion = request.POST['condicion']
if "enviarInfoAlCorreo" in request.POST.keys(): enviarInfoAlCorreo = True
#tomo datos opcionales particulares
if request.POST['Labor']: desempeno = request.POST['Labor']
if request.POST['Lugar']: lugar = request.POST['Lugar']
#Validaciones
errorNumeroDocumento = (User.objects.filter(username=numeroDocumento) or not re.match("^([0-9]{8,20})$",numeroDocumento))
errorTipoDocumento = (tipoDocumento not in (parametros["tiposDocumento"]))
errorContrasena = (request.POST["contrasena"]!=request.POST["contrasena2"])
errorCorreoElectronico = (User.objects.filter(email=correoElectronico) or not re.match(r"^[A-Za-z0-9\._-]+#[A-Za-z0-9]+\.[a-zA-Z]+$", correoElectronico))
errorFechaNacimiento = not fechaCorrecta(fechaNacimiento)
errorGenero = (genero not in (parametros["generos"]))
errorTelefonos = (not re.match("^([0-9]{7,12})$",telefonoFijo) or not re.match("^([0-9]{7,12})$",telefonoCelular) or not re.match("^([0-9]{7,12})$",telefonoAcudiente))
if (errorContrasena or errorNumeroDocumento or errorTipoDocumento or errorCorreoElectronico or errorFechaNacimiento or errorGenero or errorTelefonos):
return render_to_response('Generales/registroEstudianteMayor.html', locals(), context_instance = RequestContext(request))
#Guardar usuario
usuario = User.objects.create_user(id=User.objects.all().count() + 1, username=numeroDocumento, email=correoElectronico, password=contrasena)
usuario.first_name = nombres
usuario.last_name = apellidos
usuario.save()
#Guardo estudiante
estudiante = Estudiante(user = usuario, tipoDocumento = tipoDocumento, fechaNacimiento = fechaNacimiento, genero = genero, direccion = direccion, barrio = barrio, zona = zona, comuna = comuna,
telefonoFijo = telefonoFijo, telefonoCelular = telefonoCelular, grupoEtnico = grupoEtnico, condicion = condicion, seguridadSocial = seguridadSocial, enviarInfoAlCorreo = enviarInfoAlCorreo)
estudiante.save()
#Guardo datos particulares del Mayor
datosMayor = DatosFamiliaMayor(idEstudiante= user, nombreContacto= nombreAcudiente, telefonoContacto= telefonoAcudiente,
desempeno= desempeno, lugar= lugar, cedula= cedula, foto= foto)
datosMayor.save()
return inicioControl(request, registerSuccess=True)
and the part of the view being affected is:
<label class="control-label col-md-4" for="acud">Nombre Acudiente:</label>
<div class= "col-md-8">
<input type="text" name="Nomacud" requiered="true" value="{{Acudiente}}" class="form-control" id="nomacud">
</div>
</div>
<div class="form-group" id="TelAcudiente">
<label class="control-label col-md-4" for="Acudtel">Telefono Acudiente:</label>
<div class="col-md-8">
<input type="text" name="Telacud" requiered="true" value="{{telefonoAcudiente}}" class="form-control" id="telacud">
</div>
</div>
In TelefonoAcudiente the error is the same.
You don't have a field called Acudiente in your view; you have one called Nomacud instead.
Really though you should be using Django forms for all this.
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()
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>