{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "layout: post\n", "title: Sprint 5 Personal Blog\n", "description: personal blog for sprint 5\n", "permalink: /sprint5/\n", "comments: true\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Purpose of Group Program\n", "\n", "The purpose of this program is to create a chat application that incorporates several features, such as:\n", "\n", "- Sending and receiving messages.\n", "- Censoring inappropriate content in messages.\n", "- Storing messages and their metadata in a database.\n", "- Managing and viewing chat history.\n", "\n", "This program provides a foundation for collaborative and interactive communication, with an emphasis on ethical behavior through content moderation.\n", "\n", "---\n", "\"Chats\n", "\n", "# Purpose of Individual Features\n", "\n", "Each individual feature contributes to a specific aspect of the chat program:\n", "\n", "- **Message Input/Output**: Handling user-generated messages and ensuring that they are stored and returned properly.\n", "- **Censorship Feature**: Filtering out inappropriate words to ensure the messages remain appropriate.\n", "- **Database Integration**: Managing the messages in the database, allowing for operations such as creating, reading, updating, and deleting messages.\n", "\n", "---\n", "\n", "# Input/Output: Demonstrating API Requests\n", "\n", "Let's demo how we can interact with our chat application using **API requests**. We will use both the **frontend** and **Postman** to show how messages are sent, stored, and retrieved from the backend.\n", "\n", "### Frontend API Request Example\n", "\n", "This HTML form collects user input and sends a POST request to the Flask backend. The backend will process the message, censor inappropriate content, and store it in the database.\n", "\n", "```html\n", "
\n", " \n", " \n", "
\n", "\n", "\"Chatroom\n", "\n", "\n", "\n", "```\n", "\n", "### **What happens here?**\n", "- The user inputs a message, and when the form is submitted, the JavaScript fetches the message and sends it as a JSON body to the Flask backend.\n", "- The backend processes the message, censors any inappropriate content, and stores the message in the database.\n", "\n", "---\n", "\n", "# Postman API Request Example\n", "\n", "In Postman, we can test the **POST** request to the `/chat` endpoint.\n", "\n", "**Method**: `POST` \n", "**URL**: `http://localhost:8887/chat` \n", "\n", "**Body (JSON format)**:\n", "\n", "```json\n", "{\n", " \"message\": \"This is an inappropriate message.\",\n", " \"user_id\": 1\n", "}\n", "```\n", "\n", "\"Censored\n", "\n", "\n", "The backend will process the message, censor any inappropriate content, and respond with a JSON object.\n", "\n", "**API Response (JSON format)**:\n", "\n", "```json\n", "{\n", " \"message\": \"Message sent successfully\",\n", " \"original_message\": \"This is an inappropriate message.\",\n", " \"censored_message\": \"This is an ************ message.\"\n", "}\n", "```\n", "\n", "### **What happens here?**\n", "- We test the API in Postman by sending a POST request with a message to the `/chat` endpoint.\n", "- The API processes the message, returns a success message, and includes both the original and censored versions of the message.\n", "\n", "---\n", "\n", "# Database Operations: Using db_init, db_restore, db_backup\n", "\n", "To demonstrate how the database handles data creation and recovery, we use functions such as **db_init**, **db_restore**, and **db_backup**.\n", "\n", "### **db_init**: Create Tester Data\n", "\n", "This function initializes the database and adds test data to the `censor` table.\n", "\n", "```python\n", "# db_init.py\n", "def db_init():\n", " \"\"\"Create the database and add tester data\"\"\"\n", " with app.app_context():\n", " db.create_all()\n", " \n", " c1 = Censor(name='John Doe', uid='johndoe123', submission_text='Test message', censored_text='Test message', submission_date=date.today(), flagged_words='')\n", " db.session.add(c1)\n", " db.session.commit()\n", "```\n", "\n", "### **db_restore**: Restore Data to Original State\n", "\n", "This function drops all tables and calls `db_init` to restore the original state of the database.\n", "\n", "```python\n", "# db_restore.py\n", "def db_restore():\n", " \"\"\"Restore the database to the original state\"\"\"\n", " with app.app_context():\n", " db.drop_all()\n", " db_init()\n", "```\n", "\n", "### **db_backup**: Back Up Data\n", "\n", "This function allows us to back up the current state of the database.\n", "\n", "```python\n", "# db_backup.py\n", "def db_backup():\n", " \"\"\"Backup the current database state\"\"\"\n", " with app.app_context():\n", " # Your backup logic here (e.g., export database to a file)\n", " pass\n", "```\n", "\n", "---\n", "\n", "# Working with Lists and Dictionaries\n", "\n", "We use **lists** and **dictionaries** to store and manipulate data in our API and database.\n", "\n", "### **List of Rows**: Fetching Multiple Records\n", "\n", "In the database, each record is represented as a row, and when we retrieve multiple records, they are returned as a list of rows. For example:\n", "\n", "```python\n", "chats = MusicChat.query.all()\n", "```\n", "\n", "This query returns all chat records as a list of rows, and we can iterate over this list to display each message.\n", "\n", "### **Dictionaries for Columns**: Structuring Data\n", "\n", "When fetching a specific record, each record is returned as a dictionary where the column names are the keys, and the column values are the corresponding values. For example:\n", "\n", "```python\n", "chat_data = chat.read() # Returns a dictionary\n", "```\n", "\n", "Each message will be represented as a dictionary, which allows us to easily format the data for API responses.\n", "\n", "---\n", "\n", "# Formatting Response Data (JSON)\n", "\n", "The response data from the API is formatted as JSON to ensure compatibility with frontend applications and other services. For example:\n", "\n", "```python\n", "@app.route('/chat', methods=['GET'])\n", "def get_all_chats():\n", " chats = MusicChat.query.all()\n", " return jsonify([chat.read() for chat in chats]), 200\n", "```\n", "\n", "This endpoint returns a list of all chat messages, formatted as JSON.\n", "\n", "---\n", "\n", "# Queries from Database: Extracting Python Lists\n", "\n", "Queries from the database return Python lists, which can be used to display or process data. For example:\n", "\n", "```python\n", "chat_history = MusicChat.query.filter(\n", " (MusicChat._user_id == user1) | (MusicChat._user_id == user2)\n", ").all()\n", "```\n", "\n", "This query returns a list of chat messages between two users, which is then processed and returned as a JSON response.\n", "\n", "---\n", "\n", "# Working with Columns: CRUD Operations\n", "\n", "The `Censor` class is designed to handle CRUD operations for database records. Each method (create, read, update, delete) interacts with the columns of the `censor` table.\n", "\n", "### **Create Method**\n", "\n", "```python\n", "def create(self, inputs=None):\n", " try:\n", " db.session.add(self)\n", " db.session.commit()\n", " return self\n", " except IntegrityError:\n", " db.session.rollback()\n", " return None\n", "```\n", "\n", "The `create` method adds a new record to the database.\n", "\n", "### **Read Method**\n", "\n", "```python\n", "def read(self):\n", " data = {\n", " \"id\": self.id,\n", " \"name\": self.name,\n", " \"uid\": self.uid,\n", " \"submission_text\": self.submission_text,\n", " \"censored_text\": self.censored_text,\n", " \"submission_date\": self.submission_date,\n", " \"flagged_words\": self.flagged_words\n", " }\n", " return data\n", "```\n", "\n", "The `read` method retrieves the data from the database and returns it as a dictionary.\n", "\n", "### **Update Method**\n", "\n", "```python\n", "def update(self, inputs):\n", " self.submission_text = inputs.get(\"submission_text\", self.submission_text)\n", " self.censored_text = inputs.get(\"censored_text\", self.censored_text)\n", " self.flagged_words = inputs.get(\"flagged_words\", self.flagged_words)\n", " db.session.commit()\n", "```\n", "\n", "The `update` method updates specific columns of a record in the database.\n", "\n", "### **Delete Method**\n", "\n", "```python\n", "def delete(self):\n", " db.session.delete(self)\n", " db.session.commit()\n", "```\n", "\n", "The `delete` method removes a record from the database.\n", "\n", "\"Chats\n", "\n", "\n", "---\n", "\n", "# Algorithmic Code for API Requests\n", "\n", "We will now demonstrate the code for handling an API request. This includes the use of **sequencing**, **selection**, and **iteration** within the code.\n", "\n", "### **Handling API Request**\n", "\n", "```python\n", "@app.route('/chat', methods=['POST'])\n", "def send_message():\n", " data = request.json\n", " message = data[\"message\"]\n", " user_id = data[\"user_id\"]\n", "\n", " # Censor the message before saving it\n", " censored_message = censor_message(message)\n", " chat = MusicChat(message=message, censored_message=censored_message, user_id=user_id)\n", " chat.create()\n", "\n", " return jsonify({\n", " \"message\": \"Message sent successfully\",\n", " \"original_message\": message,\n", " \"censored_message\": censored_message\n", " }), 200\n", "```\n", "\n", "\n", "### **What happens here?**\n", "- This code listens for a **POST** request at the `/chat` endpoint, processes the message, and stores it in the database after censoring.\n", "- The sequence of actions involves receiving the data, selecting the relevant message field, and iterating over the database to store the information.\n", "\n" ] } ], "metadata": { "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }