simbha

gae session & ajax & ndb usage example

Jul 2nd, 2016
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.42 KB | None | 0 0
  1.  
  2. Session ajax
  3. gae python post form tutorial
  4.  
  5.  
  6. #################################################
  7. http://olivecodex.blogspot.in/2013/09/ajax-with-jquery-and-google-app-engine.html?m=1
  8.  
  9.  
  10. Navigate to localhost/static.html
  11.  
  12. static.html to something we can manipulate:
  13.  
  14. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  15. <html xmlns="http://www.w3.org/1999/xhtml">
  16. <head>
  17. <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
  18. <title>Ajax With Jquery</title>
  19.  
  20. <!-- Grab the JQuery API from the Google servers -->
  21. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
  22.  
  23. <!-- Our own JQuery code to do the AJAX-y stuff -->
  24. <script type="text/javascript" charset="utf-8">
  25. $(document).ready(function(){
  26. // This will run when the item of class 'button' is clicked
  27. $(".button").click(function() {
  28.  
  29. // Grabs the text input
  30. var name = $("input#txtValue").val();
  31.  
  32. var dataString = 'txtValue='+ name;
  33. // This creates the AJAX connection
  34. $.ajax({
  35. type: "POST",
  36. url: "/tutorial",
  37. data: dataString,
  38. success: function(data) {
  39. $('#display').html(data.text);
  40. }
  41. });
  42. return false;
  43. });
  44. });
  45. </script>
  46. </head>
  47.  
  48. <body>
  49. <form name="contact" method="post" action="">
  50. <label for="txtValue">Enter a value : </label>
  51. <input type="text" name="txtValue" value="" id="txtValue">
  52. <input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
  53. </form>
  54. <div id="display">
  55. </div>
  56. </body>
  57. </html>
  58.  
  59. 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....
  60.  
  61. Our Python webapp
  62. Create a file called tutorial.py and add the following code:
  63.  
  64. # The webapp2 framework
  65. import webapp2
  66.  
  67. # The JSON library
  68. import json
  69.  
  70. # Our JSON handler class
  71. class JsonPage(webapp2.RequestHandler):
  72. # The POST handler
  73. def post(self):
  74. # Our POST Input
  75. txtinput = self.request.get('txtValue')
  76.  
  77. # Create an array
  78. array = {'text': txtinput}
  79.  
  80. # Output the JSON
  81. self.response.headers['Content-Type'] = 'application/json'
  82. self.response.out.write(json.dumps(array))
  83.  
  84. # URL map the JSON function
  85. app = webapp2.WSGIApplication([('/tutorial', JsonPage)], debug=True)
  86.  
  87. Now we just need to edit app.yaml so it can serve up our tutorial script:
  88.  
  89. application: almightynassar
  90. version: 1
  91. runtime: python27
  92. api_version: 1
  93. threadsafe: no
  94.  
  95. handlers:
  96. - url: /(.*).html
  97. static_files: \1.html
  98. upload: (.*).html
  99.  
  100. - url: /(.*)
  101. script: tutorial.app
  102.  
  103.  
  104. ############################################
  105.  
  106. http://www.brianbolton.me/2012/11/20/Basic-CRUD-app-for-Python-and-Google-App-Engine.html
  107.  
  108.  
  109. Basic CRUD app for Python and Google App Engine
  110. 20 Nov 2012
  111.  
  112. 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.
  113.  
  114. 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.
  115.  
  116. basiccrud.py
  117. import webapp2
  118. import cgi
  119. import datetime
  120. import urllib
  121.  
  122. from google.appengine.ext import db
  123. from google.appengine.api import users
  124.  
  125. #blog###################################################
  126. class BlogPost(db.Model):
  127. title = db.StringProperty()
  128. content = db.StringProperty()
  129. date = db.DateTimeProperty(autonowadd=True)
  130.  
  131. def BlogPostKey():
  132. return db.Key.frompath('Blog','defaultblog')
  133.  
  134. def BlogById(id):
  135. return BlogPost.getbyid(id,parent=BlogPostKey())
  136.  
  137.  
  138. #PAGES#################################################
  139. class MainPage(webapp2.RequestHandler):
  140. def get(self):
  141. self.response.write(
  142. '<html>'
  143. '<body>'
  144. '<a href="/AddPost">AddPost</a>')
  145.  
  146. BlogPosts = db.GqlQuery("select * from BlogPost order by date desc limit 10")
  147.  
  148. self.response.write('<ul>')
  149.  
  150. for post in BlogPosts:
  151. self.response.write('<li>{title} at {date} key: ' \
  152. '{key}<a href="/EditPost?id={key}">Edit</a></li>'
  153. .format(title=post.title,date=post.date,key=post.key().id()))
  154.  
  155. self.response.write('</ul>')
  156. self.response.write('</body></html>')
  157.  
  158.  
  159. class AddPost(webapp2.RequestHandler):
  160. def get(self):
  161. self.response.write(
  162. '<html>'
  163. '<body>'
  164. '<form action="/AddPost" method="POST">'
  165. 'TITLE:<input type=text name=title value=""/>'
  166. '<br>CONTENT:<input type=text name=content value=""/>'
  167. '<br><input type=submit text="submit"/>'
  168. '</form>'
  169. '</body>'
  170. '</html>')
  171. def post(self):
  172. title = self.request.get('title')
  173. content = self.request.get('content')
  174. newpost = BlogPost(parent=BlogPostKey())
  175. newpost.title = title
  176. newpost.content = content
  177. newpost.put()
  178. self.redirect('/')
  179.  
  180. class EditPost(webapp2.RequestHandler):
  181. def get(self):
  182. id = int(self.request.get('id'))
  183. newpost = BlogById(id)
  184. self.response.write(
  185. '<html>'
  186. '<body>'
  187. '<form action="/EditPost" method="POST">'
  188. '<input type="hidden" value="{id}" name="id">'
  189. 'TITLE:<input type=text name=title value="{title}"/>'
  190. '<br>CONTENT:<input type=text name=content value="{content}"/>'
  191. '<br><input type=submit value="Save"/>'
  192. '</form>'
  193. '<form action="/DeletePost" method="POST">'
  194. '<input type="hidden" value="{id}" name="id">'
  195. '<br><input type=submit value="delete"/>'
  196. '</form>'
  197. '</body>'
  198. '</html>'
  199. .format(title=newpost.title,
  200. content=newpost.content,id=newpost.key().id()))
  201. def post(self):
  202. title = self.request.get('title')
  203. content = self.request.get('content')
  204. id = int(self.request.get('id'))
  205. newpost = BlogById(id)
  206. newpost.title = title
  207. newpost.content = content
  208. newpost.put()
  209. self.redirect('/')
  210.  
  211. class DeletePost(webapp2.RequestHandler):
  212. def post(self):
  213. id = int(self.request.get('id'))
  214. newpost = BlogById(id)
  215. newpost.delete()
  216. self.redirect('/')
  217.  
  218.  
  219. app = webapp2.WSGIApplication([('/', MainPage),
  220. ('/AddPost',AddPost),
  221. ('/EditPost',EditPost),
  222. ('/DeletePost',DeletePost)],
  223. debug=True)
  224. app.yaml
  225. application: basiccrud
  226. version: 1
  227. runtime: python27
  228. api_version: 1
  229. threadsafe: true
  230.  
  231. handlers:
  232. - url: /.*
  233. script: basiccrud.app
  234.  
  235. ##########################@@@@@@@@@@@@@#############
  236.  
  237.  
  238. http://www.manejandodatos.es/2016/01/google-app-engine-with-python-webapp2-in-action/
  239.  
  240. Create a configuration file, called appengine_config.py, with this code:
  241.  
  242.  
  243. from gaesessions import SessionsMiddleware
  244.  
  245. from gaesessions import
  246. def webapp_add_wagi_middleware(app):
  247. app = SessionsMiddleware(app, cookie_key="qwertywewaawasdpdfsdfkllddlkeerrer")
  248. return app
  249.  
  250.  
  251. 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:
  252.  
  253.  
  254. def post(self):
  255. session = get_current_session()
  256. count = session[self.contador]
  257. nombre = self.request.get("nombre")
  258. # Guardo la info en Sesion
  259. session[self.nombre] = nombre
  260. session[self.mens] = ''
  261. if len(nombre) < 5:
  262. session[self.mens] = 'Nombre demasiado corto!'
  263. self.redirect(root)
  264. mensaje = ('Hola ... %s, Has entrado %d veces' % (nombre, count))
  265. self.response.out.write(mensaje)
  266. session[self.contador] = 0
  267.  
  268.  
  269. #For retrieving this info, you need to use the get method:
  270.  
  271.  
  272. def get(self):
  273. session = get_current_session()
  274. nombre = session.get(self.nombre, '')
  275. count = session.get(self.contador) + 1
  276. session[self.contador] = count
  277. self.response.write(html % (count, nombre))
  278.  
  279.  
  280.  
  281.  
  282. #!/usr/bin/env python
  283. # Manejandodatos.es
  284. # Probando Google App Engine con Python
  285. #
  286. import webapp2
  287. from gaesessions import get_current_session
  288. import cgi
  289.  
  290. root = '/'
  291. html = """
  292. <html lang="es">
  293. <head><title>Probando Google App Engine for Python</title></head>
  294. <body>
  295. <h1>Probando Google App Engine for Python</h1>
  296. Cargado %d veces %s
  297. <form method="post">
  298. <label for="nombre">Nombre</label>
  299. <input name="nombre" id="nombre" type="text" value="%s" />
  300. <input type="submit" value="Enviar">
  301. </form>
  302. </body>
  303. </html>
  304. """
  305.  
  306. class MainHandler(webapp2.RequestHandler):
  307. contador = 'count'
  308. nombre = 'nombre'
  309. mens = 'mensaje'
  310. def post(self):
  311. session = get_current_session()
  312. count = session[self.contador]
  313. nombre = self.request.get("nombre")
  314. # Guardo la info en Sesion
  315. session[self.nombre] = nombre
  316. if len(nombre) < 5:
  317. session[self.mens] = 'Nombre demasiado corto!'
  318. self.redirect(root)
  319. mensaje = ('Hola ... %s, Has entrado %d veces' % (nombre, count))
  320. self.response.out.write(mensaje)
  321. session[self.contador] = 0
  322.  
  323. def get(self):
  324. session = get_current_session()
  325. nombre = cgi.escape(session.get(self.nombre, ''), quote=True)
  326. count = session.get(self.contador, 0) + 1 # El contador es INTERNO y no necesita control de ESCAPE
  327. session[self.contador] = count
  328. mensaje = cgi.escape(session.get(self.mens, ''), quote=True)
  329. self.response.write(html % (count, mensaje, nombre))
  330.  
  331. app = webapp2.WSGIApplication([(root, MainHandler)], debug=True)
  332.  
  333.  
  334.  
  335. ####################################################
Add Comment
Please, Sign In to add comment