Google App Engine應(yīng)用示例:計(jì)算校驗(yàn)位(Python)
剛好我以前學(xué)習(xí)Python的時(shí)候?qū)戇^一個(gè)計(jì)算身份證最后校驗(yàn)位的小程序,我何不將其做成一個(gè)Web應(yīng)用呢,使用表單接受輸入,計(jì)算后將結(jié)果通過HTML頁面返回給用戶。使用GAE(Google App Engine)來發(fā)布這個(gè)小的Web應(yīng)用,如何融入框架呢?
相關(guān)閱讀:開始您的第一個(gè)Google App Engine應(yīng)用
下面是這個(gè)web應(yīng)用所有的代碼:
- 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()
這個(gè)程序中最關(guān)鍵的代碼就是main函數(shù)生成webapp.WSGIApplication實(shí)例這一句,這個(gè)類的構(gòu)造函數(shù)接受了兩個(gè)參數(shù),其中前面這個(gè)list類型的變量為不同的URL注冊了各自的handler,如果用戶輸入的是fuzhijie1985.appspot.com/,那么將觸發(fā)MainPage.get方法被執(zhí)行,這個(gè)方法生成了一個(gè)表單,而表單的action="/sign",因此提交時(shí)將觸發(fā)Guestbook.post方法被執(zhí)行,在這個(gè)方法內(nèi)將計(jì)算身份證的校驗(yàn)位,然后返回給用戶一個(gè)HTML,內(nèi)容只有一個(gè)字符,那就是校驗(yàn)位。另外需要注意的是Guestbook.get方法是如何從表單輸入框中獲得身份證號碼的,Python CGI的標(biāo)準(zhǔn)方法就是上面代碼那樣的。