URL短縮APIをリリース

火曜日, 2月 15th, 2011 by

URL短縮サービスに、APIを実装しました!!!
使い方はとっても簡単、”http://b.php5.jp/?url=”の後ろに短縮したいURLをつけるだけ!!!
※url=の後ろはURLエンコード推奨

短縮元URL

1
http://www.yahoo.co.jp

短縮用のAPI呼び出し 

1
http://b.php5.jp/?url=http://www.yahoo.co.jp

実行 → http://b.php5.jp/?url=http://www.yahoo.co.jp

短縮例

1
http://php5.jp/l

ソースコード

とりあえず乗っけときます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.ext import webapp,db
from google.appengine.ext.webapp import util
from google.appengine.api import users

class MyHandler(webapp.RequestHandler):
  def write(self, str):
    self.response.out.write(str)

class MainHandler(MyHandler):
  def get(self, pageStr):
    if self.request.get('url'):
      try:
        url = URL(url = self.request.get('url'))
        url.num = getNextNum()
        url.put()
        self.response.out.write("http://php5.jp/%s" % nencode(url.num))
      except Exception:
        self.response.out.write('error')
      return
    if pageStr == '' or pageStr[0] == '_':
      printHeader(self)
      max_num = MAXNUM.get_by_key_name('URL')
      if max_num == None:
        total = 0
      else:
        total = max_num.max_num
      if pageStr == "_urlerror":
        self.write(u"""<div class="err">正しいURLを入力してください。</div>""")
      self.write(u"""
      <div class="msg-small">URLを入力して短縮ボタンを押してください。<br/>確認ボタンでURLを確認できます。</div><br/>
      <div class="msg-small">ログインすると、短縮URLを一覧表示できます。</div><br/><br/>
      <form method="post" action="/"><input type="hidden" name="phpMyAdmin" value="cfc2644bd9c947213a0141747c2608b0" />
        <input type="text" name="url" id="url" value="http://"/>
        <input type="button" value="確認" onclick="window.open(document.getElementById('url').value)"/>
        <input type="submit" value="短縮"/>
      </form> 短縮したURLの総数: %d"""
% total)
      printFooter(self)
    else:
      url = URL.all().filter("num = ", ndecode(pageStr)).get()
      if url == None:
        self.redirect("/")
      else:
        url.count = url.count + 1 if url.count else 1
        url.put()
        self.redirect(url.url)
  def post(self, dummy):
    try:
      url = URL(url = self.request.get('url'))
      url.num = getNextNum()
      url.put()
      self.redirect("/thanks/%s" % nencode(url.num))
    except Exception:
        self.redirect('_urlerror')

def printHeader(self):
  self.response.out.write(u"""<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head><title>URL短縮君</title>
<link rel="stylesheet" href="/css/style.css" type="text/css"/>
<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-20XXXXXX-X']);
  _gaq.push(['_trackPageview']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>
</head>
<body><a href="/?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0"><img src="/img/logo.png" border="0"/></a>"""
)
  if users.get_current_user() == None:
    self.write(u"""<div>[ <a href="/?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">TOP</a> ] [ <a href="%s?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">Googleアカウントでログイン</a> ]</div><br><br>""" % users.create_login_url("/"))
  else:
    self.write(u"""<div>[ <a href="/?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">TOP</a> ] [ <a href="/_urllist?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">短縮したURLを確認</a> ] [ <a href="%s?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0">ログアウト</a> ]</div><br>""" % users.create_logout_url("/"))

def printFooter(self):
  self.response.out.write(u"""<br><br>Powered By <a href="http://php6.jp/python">python練習帳</a></body></html>""")

class ThanksHandler(MyHandler):
  def get(self, code):
    printHeader(self)
    self.write(u"""<br/><span class="msg">短縮URL:</span><input type="text" size="20" value="http://php5.jp/%(code)s"/>
    <input type="button" value="確認" onclick="window.open('http://php5.jp/%(code)s')"/>"""
% {'code':code})
    printFooter(self)
class URLListHandler(MyHandler):
  def get(self):
     printHeader(self)
     self.write(u"""<div class="msg-small">あなたが作成した短縮URL</div><br>""")
     self.write(u"<center><table width=500><tr><th>短縮URL</th><th>オリジナルURL</th><th>利用回数</th></tr>")
     for url in URL.all().filter('user = ',users.get_current_user()):
       self.write("""<tr><td width="200">http://php5.jp/%x</td><td border="300"><a href="%s?phpMyAdmin=cfc2644bd9c947213a0141747c2608b0" target="_blank">%s</a></td><td>%d</td></tr>""" % (url.num, url.url, url.url, url.count))
     self.write("</table></center>")
     printFooter(self)
     
def getNextNum():
  def procedure():
    num = MAXNUM.get_by_key_name('URL')
    if num is None:
      num = MAXNUM(key_name = 'URL')
    num.max_num = num.max_num + 1
    num.put()
    return num.max_num
  return db.run_in_transaction(procedure)

alnum = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJELMNOPQRSTUVWXYZ"

def nencode(num, chars = alnum):
  str = ""
  while num != 0:
    str = chars[num % len(chars)] + str
    num = num - num % len(chars)
    num = num / len(chars)
  return str

def ndecode(str, chars = alnum):
  num = 0
  for char in str:
    num = num * len(chars)
    num = num + chars.index(char)
  return num

class URL(db.Model):
  url = db.URLProperty()
  num = db.IntegerProperty()
  count = db.IntegerProperty(default = 0)
  user = db.UserProperty(auto_current_user_add = True)

class MAXNUM(db.Model):
  max_num = db.IntegerProperty(default = 0)

def main():
  application = webapp.WSGIApplication([
    ('/thanks/(.*)', ThanksHandler),
    ('/_urllist', URLListHandler),
    ('/(.*)', MainHandler)
  ], debug=True)
  util.run_wsgi_app(application)

if __name__ == '__main__':
  main()

Facebook comments:

comments

Leave a Reply


Get Adobe Flash player
single