什么是最简单的URL缩短应用程序,可以在python中为Google App Engine编写?

Chr*_*ris 13 python google-app-engine

像bit.ly这样的服务非常适合缩短您想要包含在推文和其他对话中的URL.什么是最简单的URL缩短应用程序,可以在python中为Google App Engine编写?

Nic*_*son 29

这听起来像是一个挑战!

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app

class ShortLink(db.Model):
  url = db.TextProperty(required=True)

class CreateLinkHandler(webapp.RequestHandler):
  def post(self):
    link = ShortLink(url=self.request.POST['url'])
    link.put()
    self.response.out.write("%s/%d" % (self.request.host_url, link.key().id())

  def get(self):
    self.response.out.write('<form method="post" action="/create"><input type="text" name="url"><input type="submit"></form>')

class VisitLinkHandler(webapp.RequestHandler):
  def get(self, id):
    link = ShortLink.get_by_id(int(id))
    if not link:
      self.error(404)
    else:
      self.redirect(link.url)

application = webapp.WSGIApplication([
    ('/create', CreateLinkHandler),
    ('/(\d+)', VisitLinkHandler),
])

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
Run Code Online (Sandbox Code Playgroud)