cookie_test

# -*- coding:gb2312 -*-
#!/usr/bin/python
# Filename: show_cookie.py
from flask import request
from flask import Flask
from flask import render_template
from flask import make_response

app = Flask(__name__)

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello~World~'

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

# ################################
# ##########################
@app.route('/cookie_test')
def cookie_test():
    username = request.cookies.get('username')
    # 使用 cookies.get(key) 代替 cookies[key] 避免
    # 得到 KeyError 如果cookie不存在
    return render_template('cookie_test.html',username = username)

@app.route('/cookie_set')
def cookie_set():
    resp = make_response(render_template('cookie_test.html'))
    resp.set_cookie('username', 'the username')
    return resp

if __name__ == '__main__':
    app.run(debug=True)

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> templates/cookie_test.html </title>
  <meta charset="UTF-8">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>
cookie_test.html<br>{{ username }}
 </body>
</html>

 

posted @ 2018-01-30 11:09  sky20080101  阅读(99)  评论(0)    收藏  举报