Activity 40: Documentation of Python Flask Cookie
Documentation of Activity 39: Python Flask Cookies
What are Cookies?
Cookies are small pieces of data stored on the user's computer by the web browser while browsing a website. They are used to remember information about the user, such as login status, preferences, and items in a shopping cart. Cookies can be set with an expiration date, allowing them to persist between sessions or expire after a set period.
Importance of Cookies:
User Session Management: Cookies enable the server to remember users and their sessions, making it easier to maintain login states and preferences across different pages of a web application.
Personalization: Cookies can store user preferences, allowing web applications to customize the user experience based on past interactions, such as language settings or theme choices.
Tracking and Analytics: Cookies are often used for tracking user behavior on websites, which helps businesses gather data for analytics and improve their services.
Performance Improvement: By storing frequently accessed data in cookies, web applications can reduce server load and improve response times.
Step-by-Step Implementation of Activity 39
Step 1: Set Up Your Flask Project
Create a New Project Folder:
mkdir nicolas_python_flask_cookies cd nicolas_python_flask_cookies
Set Up a Virtual Environment:
python -m venv venv venv\Scripts\activate # For Windows users pip install Flask
Create the Main Application File: Create a file named
app.py
and add the following code:from flask import Flask, request, make_response, jsonify app = Flask(__name__) @app.route('/setcookies', methods=['POST']) def set_cookies(): # Get the cookie value from the POST request cookie_value = request.form.get('cookie_value') response = make_response(jsonify({"message": "Cookie has been set!"})) # Set the cookie response.set_cookie('my_cookie', cookie_value) return response @app.route('/getcookies', methods=['GET']) def get_cookies(): # Retrieve the cookie from the request cookie_value = request.cookies.get('my_cookie') if cookie_value: return jsonify({"cookie_value": cookie_value}) return jsonify({"message": "No cookie found!"}) if __name__ == '__main__': app.run(debug=True)
Step 2: Test Your Application
Run the Flask Application: Execute the following command in your terminal:
python app.py
Setting the Cookie: You can use a tool like Postman.
Set method to
POST
http://127.0.0.1:5000/setcookies -d "cookie_value=your_cookie_value_here"
Getting the Cookie: To retrieve the cookie, send a GET request:
http://127.0.0.1:5000/getcookies
Step 3: Initialize Git and Push to GitHub
git init
git add .
git commit -m "Initial commit for Python Flask cookie implementation"
git remote add origin https://github.com/MonetForProgrammingPurposes/nicolas_python_flask_cookies.git
git branch -M master
git push -u origin master