2008-08-02 21:18:46
実際にアップロードするアプリケーションがHello World!ではあまりにも情けないので、今年二月に書いたPython練習帖:単語を数えるを使ってみることにした。wordcount0801というディレクトリを用意し、そこで、
import cgi
import re
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<body>
<form action="/result" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Count!"></div>
</form>
</body>
</html>""")
class Wordcount(webapp.RequestHandler):
def post(self):
self.response.out.write('<html><body>Result:<pre>')
content = cgi.escape(self.request.get('content'))
if len(content) < 10000:
noLine = re.sub('(\n)+', ' ', content)
sLine = re.sub('[.!:?]', ' ', noLine)
sLine2 = re.sub("[,\-']", ' ', sLine)
sLine3 = re.sub("[,';:]", '', sLine2)
sLine3 = re.sub('"', '', sLine3)
words = sLine3.split(' ')
words = [w for w in words if len(w) > 0]
wDict = {}
for w in words:
if wDict.has_key(w):
wDict[w] += 1
else:
wDict[w] = 1
keys = wDict.keys()
keys.sort()
optxt = ""
for key in keys:
optxt += key + ":" + str(wDict[key]) + "\n"
optxt += '\n There are a total of ' + str(len(wDict)) + ' words in this text.'
else:
optxt = 'Your text is too long for this application to count words'
self.response.out.write(optxt)
self.response.out.write('</pre></body></html>')
application = webapp.WSGIApplication(
[('/', MainPage),
('/result', Wordcount)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
というPythonのスクリプトを書いて、これをwordcount.pyとして保存する。次に、app.yamlというファイルを用意する。
application: wordcount0801 version: 1 runtime: python api_version: 1 handlers: - url: /.* script: wordcount.pyこれがローカル環境で動いたので、これが無事にアップロードできれば、http://wordcount0801.appspot.comで利用できるようになるはずだ。それはまた、次項で。