• python3 cookie


    最近再次学习python,本来就是一个菜鸟,我按照 Python CGI编程 发现读cookie 读取不了,后来发现它这种写的方式也不怎么靠谱。

    Python中Cookie模块(python3中为http.cookies)提供了一个类似字典的特殊对象SimpleCookie,其中存储并管理着称为Morsel的cookie值集合。
    每个Morsel都有name,value以及可选属性(expires,path,domain,comment,max-age,secure,version,httponly)。
    SimpleCookie可使用output()方法创建以HTTP报头形式表示的cookie数据输出,用js_output()方法生成包含javascript代码的字符串。

    写cookie:

    import http.cookies
    import datetime
    import random
    
    expiration = datetime.datetime.now() + datetime.timedelta(days=30)
    cookie = http.cookies.SimpleCookie()
    cookie["session"] = random.randint(1,1000000000)
    cookie["session"]["domain"] = ""
    cookie["session"]["path"] = "/"
    cookie["session"]["expires"] = expiration.strftime("%a, %d-%b-%Y %H:%M:%S PST")
    
    print("Content-Type:text/html")
    #print ("Set-Cookie: name='test';expires=Wed, 28 Aug 2016 18:30:00 GMT")
    print(cookie.output())
    print()
    
    print("""
    <html>
    <head><meta charset=gb2312></head>
    <body><h1>Cookie Set OK!</h1>
    <a href='/cookie_get.py'>get Cookie</a>
    </body>
    </html>
    """)

    读cookie:

    import os
    import http.cookies
    
    print("Conten-Type:text/html")
    print()
    print ("""
    <html>
    <head>
    <meta charset="gb2312">
    <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
    <h1>读取cookie信息</h1>
    """)
    if 'HTTP_COOKIE' in os.environ:
        cookie_string=os.environ.get("HTTP_COOKIE")
        print(cookie_string)
        c=http.cookies.SimpleCookie()
        c.load(cookie_string)
        try:
            data=c["session"].value
            print("cookie session:"+data+"<br>")
        except KeyError:
           print ("cookie 没有设置或者已过去<br>")
    print ("""
    </body>
    </html>
    """)
  • 相关阅读:
    pip 的简单安装与基本使用
    macOS(OS X)安装与配置 Homebrew
    命令行媒体处理工具 FFmpeg
    修正 FreeBSD 字体锯齿问题
    在 Linux 环境直接复移动硬盘上的 GRUB
    命令行视频下载工具 youget 和 youtubedl
    20不努力,30做助理(转载)
    树、森林和二叉树的转换
    百度地图和solr展示资源和附近等功能的实现 二
    加密Web项目中数据库配置文件中的密码
  • 原文地址:https://www.cnblogs.com/majiang/p/8611810.html
Copyright © 2020-2023  润新知