As a beginner in Python and App Engine I once again have to ask for your assistance. For some time I've been working with the book "Code in the Cloud" to learn the very basics of using App Engine. The thing is I have not been very successful so far. While most of the issues I have had stemmed from UTF-8 encoding/decoding, this time I have problems with making queries to Datastore.
To learn the basics I recreated the code for a simple chat service available in chapter IV of the aforesaid book. The key elements are:
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import datetime
from google.appengine.ext import db
#START: ChatMessage
class ChatMessage(db.Model):
user = db.StringProperty(required=True)
timestamp = db.DateTimeProperty(auto_now_add=True)
message = db.TextProperty(required=True)
def __str__(self):
return "%s (%s): %s" % (self.user, self.timestamp, self.message)
#END: ChatMessage
Above, I defined the datamodel for a message
class ChatRoomPage(webapp.RequestHandler):
def get(self):
self.response.headers["Content-Type"] = "text/html"
self.response.out.write("""
<html>
<head>
<title>AppEngine Chat Room</title>
</head>
<body>
<h1>Welcome to AppEngine Chat Room</h1>
<p>(Current time is %s)</p>
""" % (datetime.datetime.now()))
messages = db.GqlQuery("SELECT * From ChatMessage ORDER BY time")
for msg in messages:
self.response.out.write("<p>%s</p>" % msg)
self.response.out.write("""
<form action="/talk" method="post">
<div><b>Name:</b>
<textarea name="name" rows="1" cols="20"></textarea></div>
<p><b>Message</b></p>
<div><textarea name="message" rows="5" cols="60"></textarea></div>
<div><input type="submit" value="Send ChatMessage"/></div>
</form>
</body>
</html>
""")
# END: MainPage
In the block above I create UI and performe a GQL query for data I posted.
Lastly:
class ChatRoomPoster(webapp.RequestHandler):
def post(self):
chatter = self.request.get("name")
msgtext = self.request.get("message")
msg = ChatMessage(user=chatter, message=msgtext)
msg.put()
self.redirect('/')
I create the handler to send the collected data into Datastore.
Having consulted the book line by line, as well as Google tutorial, and a number of threads on this website, I still can't figure out, why the code does not work properly. Basically, the chat won't display past messages. My guess is I am doing something wrong with accessing the stored data, as the program does not throw any exception - I am missing an identifier or something like that. Perhaps I am again missing something very obvious.
I would really appreciate your help. Thank you in advance.