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

时间:2009-09-10 14:57:02

标签: python google-app-engine

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

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:2)

类似,完成了GAE项目样板:https://github.com/dustingetz/vanity-redirect

答案 2 :(得分:1)

github上有一个django应用程序,github.com / nileshk / url-shortener。我把它分叉,使它更像是一个包罗万象的网站,http://github.com/voidfiles/url-shortener