App Engine: map form data to url - python

How do I encode form data to the url when using the Google App Engine?
The code below produces a form where you enter some text. The text is then displayed on another page "/sign"
Instead of directing to /sign I would like to direct to /sign?message="hello"
Here is my code, from here: https://developers.google.com/appengine/docs/python/gettingstartedpython27/handlingforms)
import cgi
import webapp2
from google.appengine.api import users
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>""")
class Guestbook(webapp2.RequestHandler):
def post(self):
self.response.out.write('<html><body>You wrote:<pre>')
self.response.out.write(cgi.escape(self.request.get('content')))
self.response.out.write('</pre></body></html>')
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)

I'm not enterally sure what your trying to achieve. You might get more solid advice if you wrote about your intentions.
To get the result I think your describing you will need to use get instead of post. Get will alter the url. Here is the modified code:
import cgi
import webapp2
from google.appengine.api import users
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<form action="/sign">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>""")
class Guestbook(webapp2.RequestHandler):
def get(self):
self.response.out.write('<html><body>You wrote:<pre>')
self.response.out.write(cgi.escape(self.request.get('content')))
self.response.out.write('</pre></body></html>')
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
If your looking to learn more about webapp2 and the get and post method check out udacity CS253

Related

Referencing an HTML button to Python Script

My objective in this program is to store information in a database. My problem is that I'm trying to link a button from my HTML page by using a Python script. My instructor told us that it must be written in Python. Any Libraries that support Python 2.7 would work for me.
from google.appengine.api import images
from google.appengine.ext import ndb
from models import Note
import webapp2
import jinja2
import os
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))
class MainHandler(webapp2.RequestHandler):
def get(self):
template = jinja_env.get_template('./main.html')
self.response.out.write(template.render())
class InfoHandler(webapp2.RequestHandler):
def get(self):
note = Note(img = images.Image(photo.usr_img))
class Note(ndb.Model):
def get(self):
usr_img = ndb.BlobProperty()
desc = ndb.StringProperty()
app = webapp2.WSGIApplication([
('/', MainHandler),
], debug=True)
<html>
<head lang = "en">
<meta charset = "UTF-8">
<title>Title</title>
</head>
<body>
<div class = "container">
<h1>If this is an emergency, upload a photo and provide a short description.</h1>
<div id = "upload" >
<label for = "img">Upload image:</label>
<input type = "file" name = "pic" accept = "image/*"/>
<label for = "desc">Description:</label>
<input type = "text" />
<input type = "submit" href = "{{ submit_data }}"/>
</div>
</div>
</body>
</html>
I'm a noob in Python and I'm taking on a tough problem for class. Any suggestions or solutions?

Python Flask render_template returns HTML script instead of redirecting to the HTML page

I have a Python script that uses Flask web framework to let users ask a question and depending on some certain questions, the application should ask back some questions to the user on a second webpage. The answers to the questions are evaluated based on the questions and displayed on the initial webpage.
model.py
### Importing Flask ###
from flask import Flask, render_template, request, session, redirect, url_for
### Initializing Flask ###
app = Flask(__name__)
#app.route('/')
def index():
return render_template('init.html')
#app.route('/handle_data', methods = ['POST', 'GET'])
def handle_data():
### User Inputs Question ###
userQuestion = request.form['userQuestion']
def model():
message = "Depends on User"
if message == "Depends on User":
return render_template('user_information.html', userQuestion = userQuestion)
else:
message = "Your answer is ABC."
return message
message = model()
return render_template('init.html', userQuestion = userQuestion, message = message)
#app.route('/user_information', methods = ['POST', 'GET'])
def user_information():
userLevel = request.form['userLevel']
userDOJ = request.form['userDOJ']
userType = request.form['userType']
message = "Answer for Eligibility."
return render_template('init.html', userLevel = userLevel, userDOJ = userDOJ, userType = userType, message = message)
if __name__ == '__main__':
app.run()
These are my two HTML files:
init.html (initial webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
<!-- for-mobile-apps -->
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<br>
<p>Hi</p>
<form action="{{ url_for('handle_data') }}" method="post" class="agile_form">
<input type="text" name="userQuestion" placeholder="Ask your question..." required="">
<input type="submit" value="Submit">
</form>
<p>{{ message }}</p>
</div>
</div>
</body>
</html>
user_information.html (second webpage)
<!DOCTYPE html>
<html>
<head>
<title>Human Resources</title>
</head>
<body>
<div class="main">
<div class="w3_agile_main_grid">
<h2>Human Resource Portal</h2>
<form action="{{ url_for('user_information') }}" method="post" class="agile_form">
<!--<input type="text" name="userName" placeholder="Enter your name." required="">-->
<input type="text" name="userLevel" placeholder="What is your level?" required="">
<input type="text" name="userDOJ" placeholder="What is your date of joining?" required="">
<input type="text" name="userType" placeholder="Are you on sabbatical or specialist?" required="">
<input type="submit" value="Submit">
</form>
</div>
</div>
</body>
</html>
When I execute my script and enters a question, what I get is the HTML code for user_information.html as my answer which is not what I want.
Ouput after I click Submit:
https://ibb.co/cwhRpk
Expected output after I click Submit:
https://ibb.co/c7CFh5
https://ibb.co/dX9T25
I can get the desired output if I remove the model() construct but that will make my code inefficient because in my actual application I have to call model() multiple times with different parameters.
Can anyone please suggest me what approach should I take? I'm totally stuck in this part. Thanks, any help is appreciated!
Your nested model() function does not make any sense at all. It returns the result of render_template, which is a complete response including HTTP headers etc. If you try and insert that into another template, Jinja will be forced to try and convert it to a string, which gives the result you see.
This is not at all the way to compose templates. Jinja supports template inheritance; you should call render_template once only, using a child template that inherits from a common base.

How can I get data from html using python tornado

How can I get data (html input) using python-tornado.
python code is this:
import tornado.web
import tornado.ioloop
import tornado.httpserver
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
def post(self):
title = self.get_argument("title")
self.render("second.html")
app = tornado.web.Application([
(r"/", MainHandler),
])
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8080)
tornado.ioloop.IOLoop.instance().start()
and html source code is this:
<!Doctype html>
<html>
<body>
<form method="post"></form>
<div style="margin-bottom:5px">
<input name="title" type="text"/>
</div>
<div>
<input type="submit"/>
</div>
</form>
</body>
</html>
Try something like this guy has Stack Overflow
class MyHandler(tornado.web.RequestHandler):
def post(self):
name = self.get_argument("Name", "")
index = self.get_argument("Index","")
.... code for updating MongoDB

Flask submit form and show inserted values

I am completely new to python and Flask and I am trying to run in my computer the code showed in this page:
http://runnable.com/UhLMQLffO1YSAADK/handle-a-post-request-in-flask-for-python
This are the steeps I follow and the code:
1-I have installed Flask
2-Files
File app.py
# We need to import request to access the details of the POST request
# and render_template, to render our templates (form and response)
# we'll use url_for to get some URLs for the app on the templates
from flask import Flask, render_template, request, url_for
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
#app.route('/')
def form():
return render_template('form_submit.html')
# Define a route for the action of the form, for example '/hello/'
# We are also defining which type of requests this route is
# accepting: POST requests in this case
#app.route('/hello/', methods=['POST'])
def hello():
name=request.form['yourname']
email=request.form['youremail']
return render_template('form_action.html', name=name, email=email)
# Run the app :)
if __name__ == '__main__':
app.run(
host="0.0.0.0",
port=int("80")
)
File form_action.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
Hello <strong>{{name}}</strong> ({{email}})!
</div>
</div>
</div>
</body>
</html>
File form_submit.html
<html>
<head>
<title>Handle POST requests with Flask</title>
<link rel=stylesheet type=text/css href="style.css">
</head>
<body>
<div id="container">
<div class="title">
<h1>POST request with Flask</h1>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname">Please enter your name:</label>
<input type="text" name="yourname" /><br />
<label for="youremail">Please enter your email:</label>
<input type="text" name="youremail" /><br />
<input type="submit" value="Send" />
</form>
</div>
</div>
</div>
</body>
</html>
3-I run the py file:
sudo python app.py
[sudo] password for jose:
* Running on http://0.0.0.0:80/ (Press CTRL+C to quit)
When I open the browser I write:
file:///home/jose/Escritorio/python/app/form_submit.html
I insert the data in the 2 forms and I press Send and this is what happens:
URL: file:///home/jose/Escritorio/python/app/{{url_for('hello')}}
Web Page: File not found
What am I doing wrong?
0.0.0.0 means that you can access the flask website from outside of the website host. Use the host ip plus the port # you specified
http://:80/hello in your case. That should display the form_action.html you specified in your routes.
If you want save form data, your code didn't work. You must have a database or save in a file.

Google App Engine: include an image blob in html template

I have problem getting images displayed in the html template. I managed to store an image into the datastore. However, I don't know how to send it to an html file (or using an URL to display the image?). Please help and many thanks. The following is my code:
main.py
# -*- coding: utf-8 -*-
#!/usr/bin/env python2.7
import webapp2
import common
from google.appengine.ext import db
class Image(db.Model):
filename = db.StringProperty(required=True)
data = db.BlobProperty(required=True)
mimetype = db.StringProperty(required=True)
class Test(webapp2.RequestHandler):
def get(self):
common.render(self, 'test.html', {})
def post(self):
imgfile = self.request.POST['image']
img = Image(filename=imgfile.filename, data=imgfile.value, mimetype=imgfile.type)
img.put()
common.render(self, 'test.html', {'imgkey': img.key().id()})
app = webapp2.WSGIApplication([
("/.*", Test)],
debug=True)
test.html:
<htm>
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<p></p>Upload image: </p>
<form method="post" action="/test" enctype="multipart/form-data">
<input type="file" name="image" /><br />
<input type="submit" name="確定" />
</form>
{% if imgkey %}
Display:<br />
<img src="http://.../disp?key={{imgkey}}" /><br />
{% endif %}
</body>
</html>
Try something like this:
class ImageHandler(webapp2.RequestHandler):
def get(self, image_id):
image = Image.get(image_id)
self.response.headers['Content-Type'] = 'image/jpeg'
self.response.out.write(image.data)
Then in your mapping, you should a create an url for image handling e.g:
(r'/images/(.*)', ImageHandler)
In your HTML code you need to create the image tags as follows:
<img src="/images/{{img1.key}}" /><br />
<img src="/images/{{img2.key}}" /><br />

Categories