Sobes.tech
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:

  1. Client (browser) sends a request to the server.
  2. Server responds with a Set-Cookie header containing data.
  3. Browser stores the cookie and sends it in the Cookie header 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.