Junior — Middle
What is the main role and purpose of cookies in web applications?
sobes.tech AI
Answer from AI
Cookies in web applications are used to store small data on the client side (in the browser). The main roles of cookies:
- Sessions and Authentication: allow storing user information between requests, such as session identifiers, to avoid re-login on each request.
- Personalization: save user settings, interface language, themes, and other preferences.
- Tracking and Analytics: help collect data on user behavior on the site to improve the service.
Cookies are sent by the server in HTTP headers and automatically returned by the browser on subsequent requests to the same domain, enabling the server to "recognize" the user.
Example of using cookies in Python with Flask:
from flask import Flask, request, make_response
app = Flask(__name__)
@app.route('/')
def index():
username = request.cookies.get('username')
if username:
return f'Hello, {username}!'
resp = make_response('Setting cookie')
resp.set_cookie('username', 'Ivan')
return resp