GAE/python中利用memcache代替Session实现用户登录验,gaememcache,app.yamlappl


app.yaml

application: memcachetestversion: 1runtime: pythonapi_version: 1handlers:  - url: /.*  script: mymch.py

login.html

<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Login</title></head><body><!-- 表单 开始 --><form action="/" method="post">  <label>请输入登录密码:</label>  <br />  <input name="txtPassword" type="password" />  <br />  <input name="btnSubmit" type="submit" /></form><!-- 表单 结束 --></body></html>

main.html

<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>memcache test</title></head><body><h1>欢迎登录</h1></body></html>

nav.html

<HTML><HEAD><TITLE> New Document </TITLE></HEAD><BODY><SCRIPT LANGUAGE="JavaScript"> self.location='/';</SCRIPT></BODY></HTML>

mymch.py

#!/usr/bin/env python# -*- coding: utf-8 -*-'''@Author: renmin.ycs@gmail.com@Version: @Date: @Note: '''import osimport cgiimport timefrom google.appengine.ext.webapp import templatefrom google.appengine.ext import webappfrom google.appengine.ext.webapp.util import run_wsgi_appfrom google.appengine.api import memcache#-----------------------------------------------------class MainPage(webapp.RequestHandler):    #----------------------------------    def get(self):        if memcache.get('user') is not None:            ## 已经登录            tempValues = {}            path = os.path.join(os.path.dirname(__file__), 'main.html')             self.response.out.write(template.render(path, tempValues))                    else:            ## 还未登录            tempValues = {}            path = os.path.join(os.path.dirname(__file__), 'login.html')             self.response.out.write(template.render(path, tempValues))    #----------------------------------    def post(self):        ## 处理登录请求        sPassword = cgi.escape(self.request.get('txtPassword'))        if len(sPassword) >= 3:            ## 密码正确            memcache.add('user','ok',10)        else:            pass        path = os.path.join(os.path.dirname(__file__), 'nav.html')         self.response.out.write(template.render(path, {}))#------------------------------------------------------application = webapp.WSGIApplication([('/', MainPage)], debug = True)#-----------------------------------------------------def main():    run_wsgi_app(application)#------------------------------------------------------if __name__ == "__main__":    main()

评论关闭