Skip to content

Instantly share code, notes, and snippets.

@najeira
Created July 16, 2014 12:08
Show Gist options
  • Save najeira/26e6e788fa7a6943ebec to your computer and use it in GitHub Desktop.
Save najeira/26e6e788fa7a6943ebec to your computer and use it in GitHub Desktop.
Live coding
# -*- coding: utf-8 -*-
import os
import datetime
import jinja2
import webapp2
from google.appengine.api import users
from google.appengine.ext import ndb
class Page(ndb.Model):
title = ndb.StringProperty(indexed=False)
body = ndb.StringProperty(indexed=False)
user_id = ndb.StringProperty(indexed=False)
updated = ndb.DateTimeProperty(indexed=True)
created = ndb.DateTimeProperty(indexed=False)
@property
def id(self):
return self.key.id()
class BaseHandler(webapp2.RequestHandler):
def render(self, _template_name, **kwds):
kwds.setdefault("params", self.request.params)
t = Jinja2.get_template(_template_name)
s = t.render(**kwds)
self.response.headers["Content-Type"] = "text/html; charset=UTF-8"
self.response.write(s)
class MainHandler(BaseHandler):
def get(self):
q = Page.query()
q.order(-Page.updated)
pages = q.fetch(10)
self.render("list.html", pages=pages)
class PageShowHandler(BaseHandler):
def get(self, num):
page = Page.get_by_id(int(num))
self.render("show.html", page=page)
class BasePageEditHandler(BaseHandler):
def get_values(self):
title = self.request.get("title")
body = self.request.get("body")
if not title:
raise ValueError(u"タイトルを入力してください")
if len(title) > 10:
raise ValueError(u"タイトルは10文字以下にしてください")
if not body:
raise ValueError(u"本文を入力してください")
if len(body) > 140:
raise ValueError(u"本文は140文字以下にしてください")
return title, body
class PageCreateHandler(BasePageEditHandler):
def get(self):
self.render("create.html")
def post(self):
try:
title, body = self.get_values()
except ValueError as ex:
self.render("create.html", error=ex.message)
return
now = datetime.datetime.utcnow()
page = Page(
title=title,
body=body,
updated=now,
created=now,
)
key = page.put()
self.redirect("/page/" + str(key.id()))
class PageEditHandler(BasePageEditHandler):
def get(self, num):
page = Page.get_by_id(int(num))
self.render("edit.html", page=page)
def post(self, num):
page = Page.get_by_id(int(num))
try:
title, body = self.get_values()
except ValueError as ex:
self.render("edit.html", error=ex.message)
return
now = datetime.datetime.utcnow()
page.title = title
page.body = body
page.updated = now
page.put()
self.redirect("/page/" + num)
app = webapp2.WSGIApplication([
("/", MainHandler),
("/page/(\d+)", PageShowHandler),
("/edit/(\d+)", PageEditHandler),
("/create", PageCreateHandler),
], debug=True)
Jinja2 = jinja2.Environment(
loader=jinja2.FileSystemLoader(
os.path.join(os.path.dirname(__file__), "templates")),
extensions=['jinja2.ext.autoescape'],
autoescape=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment