Google App Engine應用示例:計算校驗位(Python)
剛好我以前學習Python的時候寫過一個計算身份證最后校驗位的小程序,我何不將其做成一個Web應用呢,使用表單接受輸入,計算后將結果通過HTML頁面返回給用戶。使用GAE(Google App Engine)來發布這個小的Web應用,如何融入框架呢?
相關閱讀:開始您的第一個Google App Engine應用
下面是這個web應用所有的代碼:
- import cgi
- import wsgiref.handlers
- from google.appengine.api import users
- from google.appengine.ext import webapp
- Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7,9, 10, 5, 8, 4, 2]
- IndexTable = {
- 0 : '1',
- 1 : '0',
- 2 : 'x',
- 3 : '9',
- 4 : '8',
- 5 : '7',
- 6 : '6',
- 7 : '5',
- 8 : '4',
- 9 : '3',
- 10 : '2'
- }
- class Cal():
- def calculate(self, identity):
- No = []
- sum = 0
- No = list(identity)
- for i in range(17):
- sum = sum + (int(No[i]) * Wi[i])
- Index = sum % 11
- return IndexTable[Index]
- class MainPage(webapp.RequestHandler):
- def get(self):
- self.response.out.write("""
- < html>
- < body>
- < form action="/sign" method="post">
- Your card number: < input type="text" name="id">
- < input type="submit" value="Got it">
- < /form>
- < /body>
- < /html>""")
- class Guestbook(webapp.RequestHandler):
- def post(self):
- form = cgi.FieldStorage()
- myid = form['id'].value
- cal = Cal();
- result = cal.calculate(myid);
- self.response.out.write('< html>< body>')
- self.response.out.write(result)
- self.response.out.write('< /body>< /html>')
- def main():
- application = webapp.WSGIApplication(
- [('/', MainPage),
- ('/sign', Guestbook)],
- debug=True)
- wsgiref.handlers.CGIHandler().run(application)
- if __name__ == "__main__":
- main()
這個程序中最關鍵的代碼就是main函數生成webapp.WSGIApplication實例這一句,這個類的構造函數接受了兩個參數,其中前面這個list類型的變量為不同的URL注冊了各自的handler,如果用戶輸入的是fuzhijie1985.appspot.com/,那么將觸發MainPage.get方法被執行,這個方法生成了一個表單,而表單的action="/sign",因此提交時將觸發Guestbook.post方法被執行,在這個方法內將計算身份證的校驗位,然后返回給用戶一個HTML,內容只有一個字符,那就是校驗位。另外需要注意的是Guestbook.get方法是如何從表單輸入框中獲得身份證號碼的,Python CGI的標準方法就是上面代碼那樣的。