Activity 39: Python Flask Cookie

Implementation of a Flask application that handles cookies using both POST and GET methods as per the Activity 39 requirements.

Implementing Cookies in Flask

Step 1: Set Up Your Flask Project

  1. Create a New Project Folder:

      mkdir nicolas_python_flask_cookies
      cd nicolas_python_flask_cookies
    
  2. Set Up a Virtual Environment:

      python -m venv venv
      venv\Scripts\activate  # For Windows users
      pip install Flask
    
  3. 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

  1. Run the Flask Application: Execute the following command in your terminal:

      python app.py
    
  2. 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"
    

  3. 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