Junior — Middle
Could you explain how cookies work and their role in web applications?
sobes.tech AI
Answer from AI
A cookie is a small piece of data sent by a web server and stored on the client's browser, which is sent back to the server with subsequent requests.
Principle of operation:
- Client (browser) sends a request to the server.
- Server responds with a
Set-Cookieheader containing data. - Browser stores the cookie and sends it in the
Cookieheader with future requests.
Role in web applications:
- Sessions: storing session identifiers to maintain state.
- Personalization: remembering user settings.
- Tracking: analytics and advertising.
In Python, working with cookies is often handled by frameworks like Flask or Django, which automate cookie management. Example of setting a cookie in Flask:
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
resp = make_response('Hello, world!')
resp.set_cookie('username', 'user123')
return resp
Thus, cookies enable storing and transmitting small data between client and server, providing state and personalization in web applications.