Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Session ajax
- gae python post form tutorial
- #################################################
- http://olivecodex.blogspot.in/2013/09/ajax-with-jquery-and-google-app-engine.html?m=1
- Navigate to localhost/static.html
- static.html to something we can manipulate:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
- <title>Ajax With Jquery</title>
- <!-- Grab the JQuery API from the Google servers -->
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
- <!-- Our own JQuery code to do the AJAX-y stuff -->
- <script type="text/javascript" charset="utf-8">
- $(document).ready(function(){
- // This will run when the item of class 'button' is clicked
- $(".button").click(function() {
- // Grabs the text input
- var name = $("input#txtValue").val();
- var dataString = 'txtValue='+ name;
- // This creates the AJAX connection
- $.ajax({
- type: "POST",
- url: "/tutorial",
- data: dataString,
- success: function(data) {
- $('#display').html(data.text);
- }
- });
- return false;
- });
- });
- </script>
- </head>
- <body>
- <form name="contact" method="post" action="">
- <label for="txtValue">Enter a value : </label>
- <input type="text" name="txtValue" value="" id="txtValue">
- <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
- </form>
- <div id="display">
- </div>
- </body>
- </html>
- Our JavaScript now sends some data to an external URL (in this case /tutorial) and inserts the returned data into the display div. Now all we need to do is code our Python script....
- Our Python webapp
- Create a file called tutorial.py and add the following code:
- # The webapp2 framework
- import webapp2
- # The JSON library
- import json
- # Our JSON handler class
- class JsonPage(webapp2.RequestHandler):
- # The POST handler
- def post(self):
- # Our POST Input
- txtinput = self.request.get('txtValue')
- # Create an array
- array = {'text': txtinput}
- # Output the JSON
- self.response.headers['Content-Type'] = 'application/json'
- self.response.out.write(json.dumps(array))
- # URL map the JSON function
- app = webapp2.WSGIApplication([('/tutorial', JsonPage)], debug=True)
- Now we just need to edit app.yaml so it can serve up our tutorial script:
- application: almightynassar
- version: 1
- runtime: python27
- api_version: 1
- threadsafe: no
- handlers:
- - url: /(.*).html
- static_files: \1.html
- upload: (.*).html
- - url: /(.*)
- script: tutorial.app
- ############################################
- http://www.brianbolton.me/2012/11/20/Basic-CRUD-app-for-Python-and-Google-App-Engine.html
- Basic CRUD app for Python and Google App Engine
- 20 Nov 2012
- I wrote a very basic CRUD app for Google App Engine in Python. It's a basic sample on how to add, edit, delete, and list a single entity in GAE. I didn't see anything like this on the web when I was learning GAE. I hope this helps you.
- You need python 2.7 installed and Google App Engine installed to get up and running. I ran into one issue on Windows where nothing worked until I specified the version of python in GAE. I didn't have this issue on Mac OS X.
- basiccrud.py
- import webapp2
- import cgi
- import datetime
- import urllib
- from google.appengine.ext import db
- from google.appengine.api import users
- #blog###################################################
- class BlogPost(db.Model):
- title = db.StringProperty()
- content = db.StringProperty()
- date = db.DateTimeProperty(autonowadd=True)
- def BlogPostKey():
- return db.Key.frompath('Blog','defaultblog')
- def BlogById(id):
- return BlogPost.getbyid(id,parent=BlogPostKey())
- #PAGES#################################################
- class MainPage(webapp2.RequestHandler):
- def get(self):
- self.response.write(
- '<html>'
- '<body>'
- '<a href="/AddPost">AddPost</a>')
- BlogPosts = db.GqlQuery("select * from BlogPost order by date desc limit 10")
- self.response.write('<ul>')
- for post in BlogPosts:
- self.response.write('<li>{title} at {date} key: ' \
- '{key}<a href="/EditPost?id={key}">Edit</a></li>'
- .format(title=post.title,date=post.date,key=post.key().id()))
- self.response.write('</ul>')
- self.response.write('</body></html>')
- class AddPost(webapp2.RequestHandler):
- def get(self):
- self.response.write(
- '<html>'
- '<body>'
- '<form action="/AddPost" method="POST">'
- 'TITLE:<input type=text name=title value=""/>'
- '<br>CONTENT:<input type=text name=content value=""/>'
- '<br><input type=submit text="submit"/>'
- '</form>'
- '</body>'
- '</html>')
- def post(self):
- title = self.request.get('title')
- content = self.request.get('content')
- newpost = BlogPost(parent=BlogPostKey())
- newpost.title = title
- newpost.content = content
- newpost.put()
- self.redirect('/')
- class EditPost(webapp2.RequestHandler):
- def get(self):
- id = int(self.request.get('id'))
- newpost = BlogById(id)
- self.response.write(
- '<html>'
- '<body>'
- '<form action="/EditPost" method="POST">'
- '<input type="hidden" value="{id}" name="id">'
- 'TITLE:<input type=text name=title value="{title}"/>'
- '<br>CONTENT:<input type=text name=content value="{content}"/>'
- '<br><input type=submit value="Save"/>'
- '</form>'
- '<form action="/DeletePost" method="POST">'
- '<input type="hidden" value="{id}" name="id">'
- '<br><input type=submit value="delete"/>'
- '</form>'
- '</body>'
- '</html>'
- .format(title=newpost.title,
- content=newpost.content,id=newpost.key().id()))
- def post(self):
- title = self.request.get('title')
- content = self.request.get('content')
- id = int(self.request.get('id'))
- newpost = BlogById(id)
- newpost.title = title
- newpost.content = content
- newpost.put()
- self.redirect('/')
- class DeletePost(webapp2.RequestHandler):
- def post(self):
- id = int(self.request.get('id'))
- newpost = BlogById(id)
- newpost.delete()
- self.redirect('/')
- app = webapp2.WSGIApplication([('/', MainPage),
- ('/AddPost',AddPost),
- ('/EditPost',EditPost),
- ('/DeletePost',DeletePost)],
- debug=True)
- app.yaml
- application: basiccrud
- version: 1
- runtime: python27
- api_version: 1
- threadsafe: true
- handlers:
- - url: /.*
- script: basiccrud.app
- ##########################@@@@@@@@@@@@@#############
- http://www.manejandodatos.es/2016/01/google-app-engine-with-python-webapp2-in-action/
- Create a configuration file, called appengine_config.py, with this code:
- from gaesessions import SessionsMiddleware
- from gaesessions import
- def webapp_add_wagi_middleware(app):
- app = SessionsMiddleware(app, cookie_key="qwertywewaawasdpdfsdfkllddlkeerrer")
- return app
- First, let’s store some info in the session variable by calling the post method. Now, We can add the restriction of having at least 5 characters, and if not, a message will be shown:
- def post(self):
- session = get_current_session()
- count = session[self.contador]
- nombre = self.request.get("nombre")
- # Guardo la info en Sesion
- session[self.nombre] = nombre
- session[self.mens] = ''
- if len(nombre) < 5:
- session[self.mens] = 'Nombre demasiado corto!'
- self.redirect(root)
- mensaje = ('Hola ... %s, Has entrado %d veces' % (nombre, count))
- self.response.out.write(mensaje)
- session[self.contador] = 0
- #For retrieving this info, you need to use the get method:
- def get(self):
- session = get_current_session()
- nombre = session.get(self.nombre, '')
- count = session.get(self.contador) + 1
- session[self.contador] = count
- self.response.write(html % (count, nombre))
- #!/usr/bin/env python
- # Manejandodatos.es
- # Probando Google App Engine con Python
- #
- import webapp2
- from gaesessions import get_current_session
- import cgi
- root = '/'
- html = """
- <html lang="es">
- <head><title>Probando Google App Engine for Python</title></head>
- <body>
- <h1>Probando Google App Engine for Python</h1>
- Cargado %d veces %s
- <form method="post">
- <label for="nombre">Nombre</label>
- <input name="nombre" id="nombre" type="text" value="%s" />
- <input type="submit" value="Enviar">
- </form>
- </body>
- </html>
- """
- class MainHandler(webapp2.RequestHandler):
- contador = 'count'
- nombre = 'nombre'
- mens = 'mensaje'
- def post(self):
- session = get_current_session()
- count = session[self.contador]
- nombre = self.request.get("nombre")
- # Guardo la info en Sesion
- session[self.nombre] = nombre
- if len(nombre) < 5:
- session[self.mens] = 'Nombre demasiado corto!'
- self.redirect(root)
- mensaje = ('Hola ... %s, Has entrado %d veces' % (nombre, count))
- self.response.out.write(mensaje)
- session[self.contador] = 0
- def get(self):
- session = get_current_session()
- nombre = cgi.escape(session.get(self.nombre, ''), quote=True)
- count = session.get(self.contador, 0) + 1 # El contador es INTERNO y no necesita control de ESCAPE
- session[self.contador] = count
- mensaje = cgi.escape(session.get(self.mens, ''), quote=True)
- self.response.write(html % (count, mensaje, nombre))
- app = webapp2.WSGIApplication([(root, MainHandler)], debug=True)
- ####################################################
Add Comment
Please, Sign In to add comment