Request handler not working in GoogleAppEngine WSGI application - python

I am new to web development. I have written the following python code to get input in a form and send it to '/testform'
import webapp2
form="""
<form action="/testform">
<input name="q">
<input type="submit">
</form>
"""
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(form)
class TestHandler(webapp2.RequestHandler):
def get(self):
q=self.request.get("q")
self.response.out.write(q)
app = webapp2.WSGIApplication([
('/', MainHandler),('/testform',TestHandler)
], debug=True)
But when I am opening the file in my browser, nothing is being displayed. Why is it so?

Related

flask + ngrok - redirect doesn't work

I've got the following app:
server.py
#app.route('/')
def main():
return render_template('index.html')
#app.route('/login')
def login():
return 'hey'
index.html
<body>
<form action="http://localhost:5000/login" , method="post">
<input type="submit" value="submit">
</body>
Now I run ngrok:
ngrok http 5000
After typing address (generated by ngrok) into web browser I can see index.html page with button, but when I press the button it redirects me to http://localhost:5000/login where I can see: "connection refused".
My question is how to set ngrok and flask server the way they can communicate?
P.S. I've put only a part of my code just for better reading
Btw, I've figured out how to make it other way. After running command:
ngrok http 5000
I get ngrok address thanks to this python script:
import json
import os
def get_ngrok_address():
os.system("curl http://localhost:4040/api/tunnels > tunnels.json")
with open('tunnels.json') as data_file:
datajson = json.load(data_file)
return dict(zip(['http', 'https'], [i['public_url'] for i in datajson['tunnels']]))
It just gets json object and converts it to python dict:
'http' -> ngrok_http_address
'https' -> ngrok_https_address
Before server start I pass generated address to all html templates e.x.:
<body>
<form action="{{ ngrok_address }}/login", method="post">
<input type="submit" value="submit">
</body>
What happens if you add the POST method to the login route
#app.route('/login', methods=['POST'])
def login():
return 'hey'
and change the form action to
<body>
<form action="/login", method="post">
<input type="submit" value="submit">
</body>
hm?
Try to change your host of application.
app.run(host='0.0.0.0')
and then run the command ngrok http 5000
also add POST method for the your route.
#app.route('/login', methods=['POST'])
def login():
return 'hey'
Try Flask-PyNgrok to use ngrok as flask application extension.

Python Tornado XSRF cookie issue with Chrome

I am new to Tornado and I am trying to build a very simple login form with xsrf cookie.
Code as below:
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
def post(self):
self.write("You ahve submitted the form.!")
class App(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
]
settings = dict(xsrf_cookies=True)
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == "__main__":
app = App()
server = tornado.httpserver.HTTPServer(app)
server.listen(7001)
tornado.ioloop.IOLoop.current().start()
The form is also very simple:
<html>
<head><title>Text XSRF</title></head>
<body>
<form method="post">
{% module xsrf_form_html() %}
{% raw xsrf_form_html() %}
Username:<input type="text" name="username">
Password:<input type="password" name="pwd">
<input type="submit" value="submit">
</form>
</body>
</body>
</html>
I am adding to the host file a domain:
127.0.0.1 xsrf.test.com
And when I open Chrome and type in hxxp://xsrf.test.com:7001, I can see the login form, but when sending the POST request I get a
403 (XSRF cookie does not match POST argument)
However, if I hit hxxp://localhost:7001, I can submit the form as expected. IE and Safari works fine for both domains. So I am wondering is there anything I did wrong to make this work using "xsrf.test.com" in Chrome?
I did check Chrome->Settings->Content Settings->Cookies->Allow local data to be set is properly selected.

Google App Engine link redirection

In my application, I have a form, and when I submit the entered data, the page should be redirected to another link, which has it's own handler.
Here's the python code for the same:
import os
import webapp2
import jinja2
from google.appengine.ext import db
import urllib2
import re
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))
class MainPage(Handler):
def get(self):
self.render("formrss.html")
def post(self):
x = self.request.get("rssquery")
if x:
self.redirect("/extract")
class ExtractFeeds(Handler):
def get(self):
self.write("ok")
app = webapp2.WSGIApplication([('/', MainPage),
('/extract', ExtractFeeds)], debug=True)
formrss.html
<html>
<head>
<title>Live Quora Feed</title>
</head>
<body>
<form>
Search:<input type = "text" name = "rssquery"><br>
<input type = "submit">
</form>
</body>
</html>
Now, when I submit the form data, instead of redirecting to the /extract link and displaying 'ok', the form page gets reloaded and the url is of the form '/?rssquery=(entered_data)'.
I can't seem to figure out what the problem could be here.
You are not using post on your form!
<form method="POST">
Search:<input type = "text" name = "rssquery"><br>
<input type = "submit">
</form>
This handler
def post(self):
x = self.request.get("rssquery")
if x:
self.redirect("/extract")
is bound to the post and with no post happening it was running the GET

Google Appengine I dont want to redirect page

I know this is simple but I couldn't succeed.
I add data to database but I click the button my page is going to another page. Because I write redirect line. But if I don't write my process doesn't work. My codes are these:
main.py
class AddWord(webapp2.RequestHandler):
def post(self):
word = Word()
word.name = self.request.get("content")
word.put()
query_params = {'you added': word.name }
self.redirect('/?' + urllib.urlencode(query_params))
application = webapp2.WSGIApplication([
('/', MainPage),
('/add', AddWord),
], debug=True)
my index.html
<body>
<form action="/add?" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Send Word"></div>
</form>
When I write my word to textarea and click to button I don't want to go anywhere, but I couldn't handle form action parameter and the others. Please can you tell me what I must do? Thanks.
Just make the same rendering on your def get() into your def post() and apply the same variables to recreate the page with new messages.

Getting a Blobstore key

I am reading about the Blobstore in Google App Engine. The code below is from the sample documentation. After the user selects a file to upload and clicks Submit, how do I get the key into a javascript variable? I can show it on a page, but I only want to keep it for later use. Obviously, I am new to Web programming.
#!/usr/bin/env python
#
import os
import urllib
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
upload_url = blobstore.create_upload_url('/upload')
self.response.out.write('<html><body>')
self.response.out.write('<form action="%s" method="POST" enctype="multipart/form-data">' % upload_url)
self.response.out.write("""Upload File: <input type="file" name="file"><br> <input type="submit"
name="submit" value="Submit"> </form></body></html>""")
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]
self.response.out.write('<html><body>')
self.response.out.write(str(blob_info.key()))
self.response.out.write('</body><html>')
def main():
application = webapp.WSGIApplication(
[('/', MainHandler),
('/upload', UploadHandler),
], debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
You could do something like this:
self.response.out.write("""
<html>
<script>
var blobKey = "%s";
</script>
<body>
...
</body>
</html>""" % (blob_info.key(),)

Categories