radio buttons and webapp2 - python

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

Related

I have a issue about execute in python flask

I am new in build python api. I want to get the data depend on date.
https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask#what-is-an-api
I am following this link to code my api but I don't know what can I do in execute.
This is my python code:
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config["DEBUG"] = True
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'MyDB'
app.config['MYSQL_charset'] ='utf8'
mysql = MySQL(app)
#app.route('/',methods = ['GET','POST'])
def index():
if request.method == "POST":
details = request.form
firstday = details['firstday']
lastday = details['lastday']
cur = mysql.connection.cursor()
cur.execute("select * from transaction join transaction_item on transaction.id = transaction_item.transaction_id join customer on customer.id = transaction.customer_id where transaction_datetime <= lastday and transaction_datetime >= firstday VALUES (%s, %s)", (firstday, lastday))
mysql.connection.commit()
cur.close()
return 'success'
return render_template('index.html')
if __name__ == '__main__':
app.run()
This is my HTML code:
<HTML>
<BODY bgcolor="cyan">
<form method="POST" action="">
<center>
<H1>Enter your details </H1> <br>
first_transaction_datetime <input type = "text" name= "firstday" /> <br>
last_transaction_datetime <input type = "text" name= "lastday" /> <br>
<input type = "submit">
</center>
</form>
</BODY>
</HTML>
When you are sending requests to a back-end it does not fill out the form an easy way to do it would be to add the query values in the URL
http://127.0.0.1:5000/?firstName=<firstName>&lastName=<lastName>
then your python code would look something like this.
#app.route('/',methods = ['GET','POST'])
def index():
firstName = request.args.get('firstName')
lastName = request.args.get('lastName')
if request.method == "POST":
# Do stuff here

python flask with json

I am trying to get user's input and return the details as json.
But I get an error and I can't find why.
Hers is my python code:
from flask import Flask, request, render_template,jsonify
import json
#app.route('/user_input')
def user_input():
return render_template('user-input.html')
#app.route('/user_input',methods = ['POST'])
def result():
NAME = request.form['Book_Name']
PAGE = request.form['Page']
TEXT = request.form['Text']
TOPIC = request.form['Topic']
pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
dictionaryToJson = json.dumps(pythonDictionary)
return jsonify(dictionaryToJson)
and my HTML file:
<html>
<body>
<form action = "http://localhost:5000/result" method = "POST">
<p>Book Name <input type = "text" name = "Book_Name" /></p>
<p>Page <input type = "text" name = "Page" /></p>
<p>Text <input type = "text" name = "Text" /></p>
<p>Topic <input type ="text" name = "Topic" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
How can I return the values properly?
You are dumping the dict twice as jsonify also does json.dumps() (it also sets the correct response headers for you in addition which is why you should use it instead of json.dumps():
dictionaryToJson = json.dumps(pythonDictionary)
return jsonify(dictionaryToJson)
Do this:
from flask import Flask, request, render_template,jsonify
import json
#app.route('/user_input')
def user_input():
return render_template('user-input.html')
#app.route('/user_input',methods = ['POST'])
def result():
NAME = request.form['Book_Name']
PAGE = request.form['Page']
TEXT = request.form['Text']
TOPIC = request.form['Topic']
pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
return jsonify(pythonDictionary )
0) Do not use uppercase for vars. Uppercase is always for constants.
1) Use routes with "/" at the end to avoid additional redirects which flask does:
#app.route('/user_input/', methods = ['POST'])
2) Use the same route and the same function to get what you need:
from flask import Flask, request, render_template, jsonify
def json_response(status_code, data):
res = jsonify(data)
res.status_code = status_code
return res
app = Flask(__name__)
#app.route('/user_input/', methods=["GET", "POST"])
def user_input():
if request.method == "GET":
return render_template('user-input.html')
else:
python_dictionary = {'bookName': request.form.get('Book_Name'),
'page': request.form.get('Page'),
'text': request.form.get('Text'),
'topic': request.form.get('Topic')}
return json_response(200, python_dictionary)
app.run()
3) And yes, you don't need to use json.dumps(pythonDictionary) before passing dictionary to jsonify
4) Consider to use request.form.get('key') rather than request.form['key'] because get() function returns None if there is no such key:value instead of raising key error exception.

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

GAE - Error: "The method POST is not allowed for this resource"

I'm trying to understand how to edit or update a model. I have tried several scenarios which sometimes give an error message: 405 Method Not Allowed - The method POST is not allowed for this resource. Below is my code:
The Python Models:
import os
import webapp2
import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext.webapp import template
class MessageModel(db.Model):
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class Message(webapp2.RequestHandler):
def get(self):
doRender(self,'message.htm')
def post(self):
m = MessageModel()
m.content = self.request.get('content')
m.put()
self.redirect('/view')
class View(webapp2.RequestHandler):
def get(self):
que = db.Query(MessageModel)
messageview_list = que.fetch(999)
doRender(self,
'view.htm',
{'messageview_list': messageview_list })
class Edit(webapp2.RequestHandler):
def get(self):
doRender(self,'edit.htm')
def post(self):
updated_content = self.request.get('content')
content_query = db.GqlQuery("SELECT * "
"FROM MessageModel "
"ORDER BY date DESC LIMIT 1")
messageview_list = content_query.fetch(1)
m = MessageModel()
m.content = self.request.get(updated_content)
m.put()
doRender(self,
'edit.htm',
{'messageview_list': messageview_list })
class Main(webapp2.RequestHandler):
def get(self):
doRender(self,'index.htm')
def doRender(handler, tname = 'index.htm', values = { }):
temp = os.path.join(
os.path.dirname(__file__),
'templates/' + tname)
if not os.path.isfile(temp):
return False
newval = dict(values)
newval['path'] = handler.request.path
outstr = template.render(temp, newval)
handler.response.out.write(outstr)
return True
app = webapp2.WSGIApplication([('/', Main),
('/message', Message),
('/view', View),
('/edit', Edit)],
debug=True)
The HTML Form:
{% for messageview in messageview_list %}
<form method="post" action="/edit">
<p>
<textarea name="message" rows="3" cols="60" MAXLENGTH=60>
{{ messageview.content }}</textarea>
<br>
<input type="submit" value="Update"/>
</p>
</form>
{% ifnotequal error None %}
<p>
{{ error }}
</p>
{% endifnotequal %}
{% endfor %}
I am assuming the indentation is due to copy/paste, but make sure that the post() and get() functions are actually indented inside of your class.
In your form, you have <textarea name="message" rows="3" cols="60" MAXLENGTH=60>, but in your def post() you use updated_content = self.request.get('content'), which is looking for the content keyword in the request. Also, your edit doesn't look like it is doing what you want it to do. In order to edit an entity, the basic outline of the process is 1.) Retrieve the entity (so do as you do, query using some parameter); 2.) Modify the properties of the entity however you want; and 3.) put() the entity back in the datastore.
From your code, it looks like you are retrieving the last entity entered into the datastore, but then creating a new model instead of editing that one (assuming that is what you want to do - not quite sure if that is accurate :) ). If you are looking to modify the entity that is returned, this should work:
def post(self):
updated_content = self.request.get('message')
content_query = db.GqlQuery("SELECT * "
"FROM MessageModel "
"ORDER BY date DESC LIMIT 1")
# Your query will always return just one entity (due to the LIMIT),
# but you can use get() here instead of fetch(1)
latest_model = content_query.get()
# Update the model's content property
latest_model.content = updated_content
latest_model.put()
# Assuming you want to output that model, you'd output it now
doRender(self,
'edit.htm',
{'messageview_list': latest_model })

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()

Categories

Resources