Skip to content

Commit f4aebd4

Browse files
authored
added sample app (#32)
* added sample app Signed-off-by: Harshjosh361 <[email protected]> * updated dependency, installed python dotenv Signed-off-by: Harshjosh361 <[email protected]> --------- Signed-off-by: Harshjosh361 <[email protected]>
1 parent 63a3aaa commit f4aebd4

File tree

16 files changed

+1882
-0
lines changed

16 files changed

+1882
-0
lines changed

flask_postgresql_app/.env

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
FLASK_ENV=development
2+
DATABASE_URL=postgresql://flaskuser:password@db:5432/flaskdb

flask_postgresql_app/Dockerfile

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
2+
FROM python:3.9-slim
3+
4+
5+
WORKDIR /usr/src/app
6+
7+
COPY requirements.txt ./
8+
RUN pip install --no-cache-dir -r requirements.txt
9+
10+
# Copy the rest of the working directory contents
11+
COPY . .
12+
13+
EXPOSE 5000
14+
15+
# env
16+
ENV FLASK_APP=app.py
17+
18+
CMD ["flask", "run", "--host=0.0.0.0"]

flask_postgresql_app/README.md

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# User Management API
2+
3+
4+
## Overview
5+
6+
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.
7+
The endpoints available will be:
8+
9+
1. `GET /` - Home Route
10+
2. `GET /users` - List all users
11+
3. `POST /users` - Create a new user
12+
4. `PUT /users/<id>` - Update a user
13+
5. `DELETE /users/<id>/` - Delete a user
14+
15+
16+
17+
## Setup Instructions
18+
19+
1. Clone the repository and navigate to project directory.
20+
```bash
21+
git clone https://github.com/keploy/samples-python.git
22+
cd samples-python/flask_postgresql_app
23+
```
24+
2. Install Keploy.
25+
```bash
26+
curl --silent -O -L https://keploy.io/install.sh && source install.sh
27+
```
28+
3. Build and run the Docker containers:
29+
```bash
30+
docker compose up --build
31+
```
32+
4. Access the application:
33+
Once the containers are running, the Flask app will be available at:
34+
```bash
35+
http://localhost:5000
36+
```
37+
5. Capture the testcases.
38+
```bash
39+
keploy record -c "docker compose up" --container-name "flask_web_app"
40+
```
41+
6. Generate testcases by making API calls.
42+
### Home Route
43+
# GET /
44+
```bash
45+
curl -X GET http://localhost:5000
46+
```
47+
```bash
48+
# Retrieves a list of all users.
49+
# GET /users
50+
curl -X GET http://localhost:5000/users \
51+
```
52+
```bash
53+
# Create a new user by providing a name.
54+
# POST /users
55+
curl -X POST http://localhost:5000/users -H "Content-Type: application/json" -d '{"name": "Harsh"}'
56+
57+
```
58+
```bash
59+
# Retrieve a user by their ID.
60+
# GET /users/<id>
61+
curl -X GET http://localhost:8000/users/<id>/ \
62+
63+
```
64+
```bash
65+
# Update the name of a user by their ID.
66+
# PUT /users/<id>
67+
curl -X PUT http://localhost:5000/users/<id> -H "Content-Type: application/json" -d '{"name": "Updated Name"}'
68+
```
69+
```bash
70+
# Delete a user by their ID
71+
# DELETE /
72+
curl -X DELETE http://localhost:5000/users/<id>
73+
```
74+
```bash
75+
Replace `<id>` with the actual ID of the item you want to retrieve, update, or delete.
76+
77+
## Run the testcases
78+
```bash
79+
keploy test -c "docker compose up" --container-name "flask_web_app"
80+
```
81+

flask_postgresql_app/app.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
from flask import Flask, jsonify, request
2+
from flask_sqlalchemy import SQLAlchemy
3+
from dotenv import load_dotenv
4+
import os
5+
6+
# Load environment variables from .env file
7+
load_dotenv()
8+
9+
app = Flask(__name__)
10+
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
11+
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
12+
13+
db = SQLAlchemy(app)
14+
15+
class User(db.Model):
16+
__tablename__ = 'users'
17+
id = db.Column(db.Integer, primary_key=True)
18+
name = db.Column(db.String(80), nullable=False)
19+
20+
def __init__(self, name):
21+
self.name = name
22+
23+
# Create the database tables
24+
@app.before_request
25+
def create_tables():
26+
db.create_all()
27+
28+
# Home route
29+
@app.route('/', methods=['GET'])
30+
def home():
31+
return jsonify({"message": "Welcome to the User Management API!"}), 200
32+
33+
# GET all users
34+
@app.route('/users', methods=['GET'])
35+
def get_users():
36+
users = User.query.all()
37+
return jsonify([{'id': user.id, 'name': user.name} for user in users])
38+
39+
# POST a new user
40+
@app.route('/users', methods=['POST'])
41+
def add_user():
42+
name = request.json.get('name')
43+
if not name:
44+
return jsonify({"error": "Name is required."}), 400
45+
user = User(name=name)
46+
db.session.add(user)
47+
db.session.commit()
48+
return jsonify({"message": f"User {name} added.", "id": user.id}), 201
49+
50+
# PUT to update a user
51+
@app.route('/users/<int:id>', methods=['PUT'])
52+
def update_user(id):
53+
user = User.query.get(id)
54+
if user is None:
55+
return jsonify({"error": "User not found."}), 404
56+
57+
name = request.json.get('name')
58+
if name:
59+
user.name = name
60+
db.session.commit()
61+
return jsonify({"message": f"User {id} updated."})
62+
63+
return jsonify({"error": "Name is required."}), 400
64+
65+
# DELETE a user
66+
@app.route('/users/<int:id>', methods=['DELETE'])
67+
def delete_user(id):
68+
user = User.query.get(id)
69+
if user is None:
70+
return jsonify({"error": "User not found."}), 404
71+
72+
db.session.delete(user)
73+
db.session.commit()
74+
return jsonify({"message": f"User {id} deleted."})
75+
76+
if __name__ == "__main__":
77+
app.run(host="0.0.0.0", port=5000)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
services:
2+
web:
3+
build: .
4+
container_name: flask_web_app
5+
ports:
6+
- "5000:5000"
7+
environment:
8+
- DATABASE_URL=postgresql://flaskuser:password@db:5432/flaskdb
9+
- FLASK_APP=app.py # Ensure Flask app is specified
10+
- FLASK_ENV=development
11+
command: flask run --host=0.0.0.0 # Ensure Flask runs with the correct host
12+
depends_on:
13+
- db
14+
15+
db:
16+
image: postgres:13
17+
container_name: flask_db
18+
environment:
19+
POSTGRES_DB: flaskdb
20+
POSTGRES_USER: flaskuser
21+
POSTGRES_PASSWORD: password
22+
ports:
23+
- "5432:5432"

flask_postgresql_app/keploy.yml

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
path: ""
2+
appId: 0
3+
appName: flask_postgresql_app
4+
command: docker compose up --build
5+
templatize:
6+
testSets: []
7+
port: 0
8+
dnsPort: 26789
9+
proxyPort: 16789
10+
debug: false
11+
disableTele: false
12+
disableANSI: false
13+
containerName: flask_postgresql_app
14+
networkName: ""
15+
buildDelay: 30
16+
test:
17+
selectedTests: {}
18+
globalNoise:
19+
global: {}
20+
test-sets: {}
21+
delay: 5
22+
host: ""
23+
port: 0
24+
apiTimeout: 5
25+
skipCoverage: false
26+
coverageReportPath: ""
27+
ignoreOrdering: true
28+
mongoPassword: default@123
29+
language: ""
30+
removeUnusedMocks: false
31+
fallBackOnMiss: false
32+
jacocoAgentPath: ""
33+
basePath: ""
34+
mocking: true
35+
ignoredTests: {}
36+
disableLineCoverage: false
37+
disableMockUpload: true
38+
useLocalMock: false
39+
updateTemplate: false
40+
record:
41+
filters: []
42+
recordTimer: 0s
43+
configPath: ""
44+
bypassRules: []
45+
generateGithubActions: false
46+
keployContainer: keploy-v2
47+
keployNetwork: keploy-network
48+
cmdType: native
49+
contract:
50+
services: []
51+
tests: []
52+
path: ""
53+
download: false
54+
generate: false
55+
driven: consumer
56+
mappings:
57+
servicesMapping: {}
58+
self: ""
59+
inCi: false
60+
61+
# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
2+
/reports/

0 commit comments

Comments
 (0)