Home Backend Development Python Tutorial Cookie setting and acquisition using web.py cookie

Cookie setting and acquisition using web.py cookie

Oct 17, 2016 pm 02:42 PM

The previous article talked about the first page of web.py, hello word. Let’s continue to delve into web.py programming and talk about the cookie settings of web.py.


I believe that people who have learned web programming are familiar with cookies. It plays a very important role in web programming. User login, verification code, session (based on cookies), language selector, identity recognition, etc. all have cookies. So how to set cookies in web.py?


In fact, setting cookies in web.py is very simple. web.py has already thought of this for us and provided a very simple and useful function:

setcookie(name, value, expires="", domain=None, secure=False)
Copy after login

Parameter details:

name (string) - The name of the cookie, saved by the browser and sent to the server.

value (string) -The value of the cookie, corresponding to the name of the cookie.

expires (int) - Cookie expiration time. This is an optional parameter. It determines how long the cookie is valid. In seconds. It must be an integer and never a string. Optional parameter. If this parameter is not written, it will be permanently valid by default.

domain (string) - The valid domain of the cookie - the cookie is valid within this domain. In general, to be available within a certain site, the parameter value should be written as the domain of the site (such as .webpy.org), not the host name of the site owner (such as wiki.webpy.org). The optional parameter

secure (bool) - If True, this cookie is required to be transmitted only over HTTPS. Optional parameters


For example:

#设置website的值为www.pythontab.com,有效期60秒
web.setcookie("website", "www.pythontab.com", 60)
Copy after login

Example


Use web.setcookie() to set cookies, as follows:

class CookieSet:
    def GET(self):
        i = web.input(age='25')
        web.setcookie('age', i.age, 3600)
        return "Age set in your cookie"
Copy after login


Call the above using GET method The class will set a cookie named age with a default value of 25 (actually, the default value 25 is assigned to i.age in web.input, thereby indirectly assigning the cookie, rather than directly assigning it to the cookie in the setcookie function) . This cookie will expire in one hour (i.e. 3600 seconds).


The third parameter of web.setcookie() - "expires" is an optional parameter, which is used to set the cookie expiration time. If it is a negative number, the cookie will expire immediately. If it is a positive number, it indicates how long the cookie is valid, in seconds. If this parameter is empty, the cookie will never expire.


Getting Cookies


Overview

There are many ways to get the value of Cookie. The difference lies in how to deal with it when the cookie cannot be found.


Method 1 (If the cookie is not found, return None):

Get

#通过设置的cookie的名字获取cookie,例如website
#web.cookies().get("website") 
web.cookies().get(cookieName)
Copy after login

through the get method


Method 2 (If the cookie is not found, throw an AttributeError exception ):

#先把cookie对象赋值给一个变量,然后通过cookie的名字获得
#例如:foo.website
foo = web.cookies()
foo.cookieName
Copy after login


Method 3 (if the cookie cannot be found, you can set a default value to avoid throwing an exception):

#该方法最大的特点就是可以设置cookie的默认值
foo = web.cookies(cookieName=defaultValue)
#如果不存在该cookieName,就会返回设置的默认cookie
foo.cookieName
Copy after login


If you want to confirm whether the cookie value exists,

You can do this:

class CookieGet:
    def GET(self):
        try:
             return "Your website name is: " + web.cookies().website
        except:
             #抛出异常处理
             return "Cookie 不存在."
Copy after login


or

class CookieGet:
    def GET(self):
        #先进行赋值
        website = web.cookies().get('website')
        if age:
            return "Your website name is: %s" % website
        else:
            return "Cookie 不存在."
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles