Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scaffolding of a FLASK app for WhatsApp analytics #5

Merged
merged 22 commits into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
6c1ee3a
scaffolding fastapi app for whatsapp analytics
Sachinbisht27 Apr 13, 2024
dd9f22e
merged requirements files
Sachinbisht27 Apr 15, 2024
a42c908
created database conectivity to the app
Sachinbisht27 Apr 15, 2024
94f9f2f
added logger in the application
Sachinbisht27 Apr 15, 2024
0e9aa9f
added logger in the application
Sachinbisht27 Apr 15, 2024
701d27f
Updated CI checks for the better coding standards
Sachinbisht27 Apr 15, 2024
bb309cd
Fixed error: Invalid base class 'Base'.
Sachinbisht27 Apr 15, 2024
a21de5f
Updated gitignore
Sachinbisht27 Apr 15, 2024
8bbf271
Added migrations for maintaining the database schemas through automation
Sachinbisht27 Apr 15, 2024
d45eac2
Added migrations for maintaining the database schemas through automation
Sachinbisht27 Apr 15, 2024
fb8ed03
Upgraded the packages to the latest
Sachinbisht27 Apr 15, 2024
d6652a5
Updated return messages
Sachinbisht27 Apr 16, 2024
8848671
Updating FastAPI to Flask
Sachinbisht27 Apr 17, 2024
21773af
upgrded fastapi app to flask app
Sachinbisht27 Apr 18, 2024
a51fef1
upgrded fastapi app to flask app
Sachinbisht27 Apr 18, 2024
88188c6
upgrded fastapi app to flask app
Sachinbisht27 Apr 18, 2024
23bd540
added flask migration
Sachinbisht27 Apr 18, 2024
63abb51
added more pre-commit hooks
Sachinbisht27 Apr 18, 2024
aef62ff
updated readme.md
Sachinbisht27 Apr 18, 2024
db8d89e
updated readme.md
Sachinbisht27 Apr 18, 2024
c48fa2b
updated suggested chages
Sachinbisht27 Apr 18, 2024
5c47b4b
updated suggested chages
Sachinbisht27 Apr 18, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
DB_USER=
DB_PASSWORD=
DB_NAME=
DB_HOST=
DB_PORT=
16 changes: 16 additions & 0 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: pre-commit

on:
pull_request:
push:
branches: [main]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add develop branch as well

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated


jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.9'
- uses: pre-commit/[email protected]
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.pyc
__pycache__/

# Environments
.env
.venv
env/
venv/
14 changes: 14 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-json
- id: check-yaml
- id: check-merge-conflict
- id: check-added-large-files
Comment on lines +5 to +10
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few more hooks which can be helpful for our usecase

  1. flake8 - Purpose: Runs the Flake8 code linter to check for PEP 8 violations and other style issues.
  2. black - Purpose: Applies the Black code formatter to format Python code according to PEP 8 standards.
  3. isort - Purpose: Sorts import statements in Python files according to PEP 8 guidelines.
  4. mypy - Purpose: Runs the MyPy static type checker to find type errors in Python code.
  5. docformatter - Purpose: Formats docstrings in Python files to adhere to PEP 257 guidelines.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a few more hooks in the pre-commit config.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was it helpful so far? @Sachinbisht27

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, @Satendra-SR. For the code formatting and increasing readability of the code.

- repo: https://github.com/psf/black
rev: 22.3.0
hooks:
- id: black
42 changes: 40 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,41 @@
### WhatsApp Webhook Analytics
### WhatsApp Webhook Analytics

Handling and processing Incoming webhook request configured at Glific.
Handling and processing Incoming webhook request configured at Glific.

## Installation

### Prerequisite
1. pyenv
2. python 3.12

### Steps
1. Clone the repository
```sh
git clone https://github.com/DostEducation/whatsapp-webhook-analytics.git
```
2. Switch to project folder and setup the vertual environment
```sh
cd whatsapp-webhook-analytics
python -m venv venv
```
3. Activate the virtual environment
```sh
source ./venv/bin/activate
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's include Windows command as well. I believe we have different commands to active in MacOS vs Windows.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added command for win-os

```
4. Install the dependencies:
```sh
pip install -r requirements-dev.txt
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's merge requirements-dev.txt and requirements.txt and use requirements.txt instead as there are only one additional package we are using in requirements-dev.txt

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merged

```
5. Set up your .env file by copying .env.example
```sh
cp .env.example .env
```
6. Add/update variables in your `.env` file for your environment.
7. Run the following command to get started with pre-commit
```sh
pre-commit install
```
8. Start the server by following command
```sh
functions_framework --target=handle_payload --debug
```
1 change: 1 addition & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from app.mixins import *
1 change: 1 addition & 0 deletions app/helpers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from app.helpers.db_helper import *
9 changes: 9 additions & 0 deletions app/helpers/db_helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config import SQLALCHEMY_DATABASE_URL

engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
db = SessionLocal()
10 changes: 10 additions & 0 deletions app/mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from pydantic import BaseModel, Field
from datetime import datetime


class TimestampMixin(BaseModel):
created_on: datetime = Field(default_factory=datetime.now)
updated_on: datetime = Field(default_factory=datetime.now)

class Config:
orm_mode = True
1 change: 1 addition & 0 deletions app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from app.models.webhook_transaction_log import *
25 changes: 25 additions & 0 deletions app/models/webhook_transaction_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from app import TimestampMixin
from pydantic import BaseModel
from sqlalchemy import Column, Integer, Text, Boolean
from sqlalchemy.orm import declarative_base

Base = declarative_base()


class WebhookTransactionLog(Base):
__tablename__ = "webhook_transaction_log"

id = Column(Integer, primary_key=True)
payload = Column(Text)
processed = Column(Boolean, nullable=False)
attempts = Column(Integer, nullable=False, default=0)


class WebhookTransactionLogSchema(BaseModel):
payload: str
processed: bool
attempts: int
timestamps: TimestampMixin

class Config:
orm_mode = True
1 change: 1 addition & 0 deletions app/services/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from app.services.webhook_transaction_log_service import *
33 changes: 33 additions & 0 deletions app/services/webhook_transaction_log_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import json
from app.helpers import db
from app import models


class WebhookTransactionLogService:
def create_new_webhook_log(self, jsonData):
try:
data = json.dumps(jsonData)
new_webhook_log = models.WebhookTransactionLog(
payload=data,
processed=False,
attempts=0,
)
db.add(new_webhook_log)
db.commit()
return new_webhook_log
except Exception as e:
print(
f"Error while creating new webhook log. Webhook: {jsonData}. Error message: {e}"
)
finally:
db.close()

def mark_webhook_log_as_processed(self, webhook_log):
try:
webhook_log.processed = True
db.add(webhook_log)
db.commit()
except Exception as e:
print(f"Error while marking webhook log as processed. Error message: {e}")
finally:
db.close()
14 changes: 14 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os

# Database configuration
POSTGRES = {
"user": os.environ.get("DB_USER"),
"password": os.environ.get("DB_PASSWORD"),
"database": os.environ.get("DB_NAME"),
"host": os.environ.get("DB_HOST"),
"port": os.environ.get("DB_PORT"),
}

SQLALCHEMY_DATABASE_URL = (
"postgresql://%(user)s:%(password)s@%(host)s:%(port)s/%(database)s" % POSTGRES
)
27 changes: 27 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from fastapi import FastAPI
from agraffe import Agraffe
from app.services import WebhookTransactionLogService

app = FastAPI()


def handle_payload(request):
if request.method == "POST":
try:
jsonData = request.get_json()
if jsonData:
handle_webhook(jsonData)
except Exception as e:
print(f"Error: {e}")
return jsonData
else:
return "System does not accepts GET request"


def handle_webhook(jsonData):
transaction_log_service = WebhookTransactionLogService()
webhook_log = transaction_log_service.create_new_webhook_log(jsonData)
transaction_log_service.mark_webhook_log_as_processed(webhook_log)


handler = Agraffe.entry_point(app)
4 changes: 4 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Includes dev dependencies on top of requirements.txt
-r requirements.txt
functions-framework==3.5.0
pre-commit==3.5.0
7 changes: 7 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
agraffe==0.7.0
fastapi==0.70.0
psycopg2-binary==2.9.1
pydantic==1.9.0
sqlalchemy==1.4.26
uvicorn==0.15.0
setuptools==69.2.0
Loading