search
HomeBackend DevelopmentPython TutorialCookie setting and acquisition using web.py cookie

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)

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)

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"


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)

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


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


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 不存在."


or

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


Statement
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
How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

How does the homogenous nature of arrays affect performance?How does the homogenous nature of arrays affect performance?Apr 25, 2025 am 12:13 AM

The impact of homogeneity of arrays on performance is dual: 1) Homogeneity allows the compiler to optimize memory access and improve performance; 2) but limits type diversity, which may lead to inefficiency. In short, choosing the right data structure is crucial.

What are some best practices for writing executable Python scripts?What are some best practices for writing executable Python scripts?Apr 25, 2025 am 12:11 AM

TocraftexecutablePythonscripts,followthesebestpractices:1)Addashebangline(#!/usr/bin/envpython3)tomakethescriptexecutable.2)Setpermissionswithchmod xyour_script.py.3)Organizewithacleardocstringanduseifname=="__main__":formainfunctionality.4

How do NumPy arrays differ from the arrays created using the array module?How do NumPy arrays differ from the arrays created using the array module?Apr 24, 2025 pm 03:53 PM

NumPyarraysarebetterfornumericaloperationsandmulti-dimensionaldata,whilethearraymoduleissuitableforbasic,memory-efficientarrays.1)NumPyexcelsinperformanceandfunctionalityforlargedatasetsandcomplexoperations.2)Thearraymoduleismorememory-efficientandfa

How does the use of NumPy arrays compare to using the array module arrays in Python?How does the use of NumPy arrays compare to using the array module arrays in Python?Apr 24, 2025 pm 03:49 PM

NumPyarraysarebetterforheavynumericalcomputing,whilethearraymoduleismoresuitableformemory-constrainedprojectswithsimpledatatypes.1)NumPyarraysofferversatilityandperformanceforlargedatasetsandcomplexoperations.2)Thearraymoduleislightweightandmemory-ef

How does the ctypes module relate to arrays in Python?How does the ctypes module relate to arrays in Python?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool