Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 2 additions & 0 deletions flask_postgresql_app/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
FLASK_ENV=development
DATABASE_URL=postgresql://flaskuser:password@db:5432/flaskdb
18 changes: 18 additions & 0 deletions flask_postgresql_app/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

FROM python:3.9-slim


WORKDIR /usr/src/app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy the rest of the working directory contents
COPY . .

EXPOSE 5000

# env
ENV FLASK_APP=app.py

CMD ["flask", "run", "--host=0.0.0.0"]
81 changes: 81 additions & 0 deletions flask_postgresql_app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# User Management API


## Overview

This is a Flask-based web application that uses PostgreSQL as its database. The project is containerized using Docker and Docker Compose for easy deployment and management.
The endpoints available will be:

1. `GET /` - Home Route
2. `GET /users` - List all users
3. `POST /users` - Create a new user
4. `PUT /users/<id>` - Update a user
5. `DELETE /users/<id>/` - Delete a user



## Setup Instructions

1. Clone the repository and navigate to project directory.
```bash
git clone https://github.com/keploy/samples-python.git
cd samples-python/flask_postgresql_app
```
2. Install Keploy.
```bash
curl --silent -O -L https://keploy.io/install.sh && source install.sh
```
3. Build and run the Docker containers:
```bash
docker compose up --build
```
4. Access the application:
Once the containers are running, the Flask app will be available at:
```bash
http://localhost:5000
```
5. Capture the testcases.
```bash
keploy record -c "docker compose up" --container-name "flask_web_app"
```
6. Generate testcases by making API calls.
### Home Route
# GET /
```bash
curl -X GET http://localhost:5000
```
```bash
# Retrieves a list of all users.
# GET /users
curl -X GET http://localhost:5000/users \
```
```bash
# Create a new user by providing a name.
# POST /users
curl -X POST http://localhost:5000/users -H "Content-Type: application/json" -d '{"name": "Harsh"}'

```
```bash
# Retrieve a user by their ID.
# GET /users/<id>
curl -X GET http://localhost:8000/users/<id>/ \

```
```bash
# Update the name of a user by their ID.
# PUT /users/<id>
curl -X PUT http://localhost:5000/users/<id> -H "Content-Type: application/json" -d '{"name": "Updated Name"}'
```
```bash
# Delete a user by their ID
# DELETE /
curl -X DELETE http://localhost:5000/users/<id>
```
```bash
Replace `<id>` with the actual ID of the item you want to retrieve, update, or delete.

## Run the testcases
```bash
keploy test -c "docker compose up" --container-name "flask_web_app"
```

77 changes: 77 additions & 0 deletions flask_postgresql_app/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)

def __init__(self, name):
self.name = name

# Create the database tables
@app.before_request
def create_tables():
db.create_all()

# Home route
@app.route('/', methods=['GET'])
def home():
return jsonify({"message": "Welcome to the User Management API!"}), 200

# GET all users
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'id': user.id, 'name': user.name} for user in users])

# POST a new user
@app.route('/users', methods=['POST'])
def add_user():
name = request.json.get('name')
if not name:
return jsonify({"error": "Name is required."}), 400
user = User(name=name)
db.session.add(user)
db.session.commit()
return jsonify({"message": f"User {name} added.", "id": user.id}), 201

# PUT to update a user
@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
user = User.query.get(id)
if user is None:
return jsonify({"error": "User not found."}), 404

name = request.json.get('name')
if name:
user.name = name
db.session.commit()
return jsonify({"message": f"User {id} updated."})

return jsonify({"error": "Name is required."}), 400

# DELETE a user
@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
user = User.query.get(id)
if user is None:
return jsonify({"error": "User not found."}), 404

db.session.delete(user)
db.session.commit()
return jsonify({"message": f"User {id} deleted."})

if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
23 changes: 23 additions & 0 deletions flask_postgresql_app/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
services:
web:
build: .
container_name: flask_web_app
ports:
- "5000:5000"
environment:
- DATABASE_URL=postgresql://flaskuser:password@db:5432/flaskdb
- FLASK_APP=app.py # Ensure Flask app is specified
- FLASK_ENV=development
command: flask run --host=0.0.0.0 # Ensure Flask runs with the correct host
depends_on:
- db

db:
image: postgres:13
container_name: flask_db
environment:
POSTGRES_DB: flaskdb
POSTGRES_USER: flaskuser
POSTGRES_PASSWORD: password
ports:
- "5432:5432"
61 changes: 61 additions & 0 deletions flask_postgresql_app/keploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
path: ""
appId: 0
appName: flask_postgresql_app
command: docker compose up --build
templatize:
testSets: []
port: 0
dnsPort: 26789
proxyPort: 16789
debug: false
disableTele: false
disableANSI: false
containerName: flask_postgresql_app
networkName: ""
buildDelay: 30
test:
selectedTests: {}
globalNoise:
global: {}
test-sets: {}
delay: 5
host: ""
port: 0
apiTimeout: 5
skipCoverage: false
coverageReportPath: ""
ignoreOrdering: true
mongoPassword: default@123
language: ""
removeUnusedMocks: false
fallBackOnMiss: false
jacocoAgentPath: ""
basePath: ""
mocking: true
ignoredTests: {}
disableLineCoverage: false
disableMockUpload: true
useLocalMock: false
updateTemplate: false
record:
filters: []
recordTimer: 0s
configPath: ""
bypassRules: []
generateGithubActions: false
keployContainer: keploy-v2
keployNetwork: keploy-network
cmdType: native
contract:
services: []
tests: []
path: ""
download: false
generate: false
driven: consumer
mappings:
servicesMapping: {}
self: ""
inCi: false

# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
2 changes: 2 additions & 0 deletions flask_postgresql_app/keploy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

/reports/
Loading