Skip to content

Commit e5c5304

Browse files
authored
Merge pull request #44 from amosproj/first-test-with-analysis-module
First test with analysis module
2 parents f3d3d63 + 664d960 commit e5c5304

File tree

13 files changed

+409
-35
lines changed

13 files changed

+409
-35
lines changed

apps/analyzer/main.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
from metadata_analyzer.main import main
2+
3+
if __name__ == "__main__":
4+
main()
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import pg8000.dbapi
2+
from sqlalchemy import create_engine, select
3+
from sqlalchemy.orm import Session
4+
from metadata_analyzer.models import BackupData
5+
import os
6+
7+
8+
class Database:
9+
def __init__(self):
10+
self.engine = create_engine("postgresql+pg8000://postgres:postgres@localhost:5432/postgres")
11+
12+
13+
def get_data(self):
14+
session = Session(self.engine)
15+
stmt = select(BackupData)
16+
17+
result = session.scalars(stmt)
18+
return result
19+
20+

apps/analyzer/metadata_analyzer/main.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
from flask import Flask, request
1+
from flask import Flask, request, jsonify
22
from dotenv import load_dotenv
3+
from metadata_analyzer.database import Database, get_data
4+
from metadata_analyzer.simple_analyzer import SimpleAnalyzer
35
import os
46

57
app = Flask(__name__)
68

7-
89
@app.route("/")
910
def hello_world():
1011
return "Hello, world!"
@@ -24,8 +25,19 @@ def echo():
2425
newBody = '{ "output": "' + newData + '" }'
2526
return newBody
2627

28+
@app.route("/analyze", methods=["GET"])
29+
def analyze():
30+
data = list(get_data(database))
31+
result = simple_analyzer.analyze(data)
32+
33+
return jsonify(result)
34+
35+
def main():
36+
global database
37+
global simple_analyzer
38+
database = Database()
39+
simple_analyzer = SimpleAnalyzer()
2740

28-
if __name__ == "__main__":
2941
new_port = os.getenv("FLASK_RUN_PORT")
3042
int_port = int(new_port or 5000)
3143
print("int_port: " + str(int_port))
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
from sqlalchemy.orm import mapped_column, Mapped
2+
from sqlalchemy.ext.declarative import declarative_base
3+
from datetime import datetime
4+
5+
Base = declarative_base()
6+
7+
class BackupData(Base):
8+
__tablename__ = "BackupData"
9+
10+
id: Mapped[str] = mapped_column(primary_key=True)
11+
sizeMB: Mapped[int]
12+
creationDate: Mapped[datetime]
13+
bio: Mapped[str]
14+
15+
def __repr__(self):
16+
return f"""BackupData(id={self.id}, sizeMB={self.sizeMB}, creationDate={self.creationDate}, bio={self.bio!r})"""
17+
18+
def __str__(self):
19+
return repr(self)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class SimpleAnalyzer:
2+
def __init__(self):
3+
pass
4+
5+
def analyze(self, data):
6+
count = len(data)
7+
dates = list(map(lambda backup_data: backup_data.creationDate, data))
8+
sizes = list(map(lambda backup_data: backup_data.sizeMB, data))
9+
return {
10+
"count": count,
11+
"firstBackup": min(dates),
12+
"lastBackup": max(dates),
13+
"minSize": min(sizes),
14+
"maxSize": max(sizes),
15+
}

apps/analyzer/poetry.lock

Lines changed: 272 additions & 15 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

apps/analyzer/project.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
"serve": {
1515
"executor": "@nxlv/python:run-commands",
1616
"options": {
17-
"command": "./.venv/bin/python3.11 ./metadata_analyzer/main.py",
17+
"command": "./.venv/bin/python3.11 ./main.py",
1818
"cwd": "apps/analyzer"
1919
}
2020
},

apps/analyzer/pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ readme = 'README.md'
2424
python = ">=3.9,<3.12"
2525
flask = "^3.0.3"
2626
python-dotenv = "^1.0.1"
27+
sqlalchemy = "^2.0.36"
28+
pg8000 = "^1.31.2"
2729

2830
[tool.poetry.group.dev.dependencies]
2931
autopep8 = "2.0.2"
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { HttpModule } from '@nestjs/axios';
22
import { Module } from '@nestjs/common';
33
import { AnalyzerServiceService } from './analyzer-service.service';
4+
import { AnalyzerController } from './analyzer.controller';
45

56
@Module({
67
providers: [AnalyzerServiceService],
78
imports: [HttpModule],
9+
controllers: [AnalyzerController],
810
exports: [AnalyzerServiceService],
911
})
10-
export class AnalyzerServiceModule {}
12+
export class AnalyzerServiceModule {}

apps/backend/src/app/analyzerService/analyzer-service.service.ts

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Inject, Injectable, Logger } from '@nestjs/common';
22
import { ConfigService } from '@nestjs/config';
33
import { HttpService } from '@nestjs/axios';
4-
import { map, Observable } from 'rxjs';
4+
import { firstValueFrom, map, Observable } from 'rxjs';
55

66
/**
77
* Service to connect to the Analyzer service.
@@ -23,12 +23,39 @@ export class AnalyzerServiceService {
2323
* @param text The text to echo.
2424
* @returns The echoed text.
2525
*/
26-
echo(text: string): Observable<string> {
26+
sendEcho(text: string): Observable<string> {
2727
this.logger.debug(`Sending echo request to Analyzer service`);
2828
return this.httpService
2929
.post<string>(`${this.analyzerServiceUrl}/echo`, {
3030
body: { text },
3131
})
3232
.pipe(map((response) => response.data));
3333
}
34+
35+
/**
36+
* Echo the given text.
37+
* @param text
38+
*/
39+
async echo(text: string): Promise<string> {
40+
return await firstValueFrom(this.sendEcho(text));
41+
}
42+
43+
/**
44+
* Gets the first entry of a dummy dataset in the database using the Analyzer service. (Used for Demo purposes)
45+
*
46+
* @returns The first entry.
47+
*/
48+
getAnalyzerDemo(): Observable<string> {
49+
this.logger.debug(`Sending demo analyzer request to Analyzer service`);
50+
return this.httpService
51+
.get(`${this.analyzerServiceUrl}/analyze`)
52+
.pipe(map((response) => response.data));
53+
}
54+
55+
/**
56+
* Return the "analyzed" data.
57+
*/
58+
async analyzerDemo(): Promise<string> {
59+
return await firstValueFrom(this.getAnalyzerDemo());
60+
}
3461
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import {
2+
Controller,
3+
Get,
4+
Logger,
5+
Param,
6+
} from '@nestjs/common';
7+
import { ApiOkResponse, ApiOperation } from '@nestjs/swagger';
8+
import { AnalyzerServiceService } from './analyzer-service.service';
9+
10+
@Controller('analyzer')
11+
export class AnalyzerController {
12+
readonly logger = new Logger(AnalyzerController.name);
13+
14+
constructor(private readonly analyzerServiceService: AnalyzerServiceService) {}
15+
16+
@Get('echo/:text')
17+
@ApiOperation({ summary: 'Echo the given text.' })
18+
@ApiOkResponse({ type: String })
19+
async echo(@Param('text') text: string): Promise<string> {
20+
return await this.analyzerServiceService.echo(text);
21+
}
22+
23+
@Get('analyzerDemo/')
24+
@ApiOperation({ summary: 'Demos getting analyzed data from analyzer using the database.' })
25+
@ApiOkResponse({ type: String })
26+
async analyzerDemo(): Promise<string> {
27+
return this.analyzerServiceService.analyzerDemo();
28+
}
29+
}

apps/backend/src/app/demo/demo.controller.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,4 @@ export class DemoController {
3535
return await this.demoService.createEntry(createEntryDto.text);
3636
}
3737

38-
@Get('echo/:text')
39-
@ApiOperation({ summary: 'Echo the given text.' })
40-
@ApiOkResponse({ type: String })
41-
async echo(@Param('text') text: string): Promise<string> {
42-
return await this.demoService.echo(text);
43-
}
4438
}

apps/backend/src/app/demo/demo.service.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,4 @@ export class DemoService {
3131
return this.demoRepository.save(entry);
3232
}
3333

34-
/**
35-
* Echo the given text.
36-
* @param text
37-
*/
38-
async echo(text: string): Promise<string> {
39-
return await firstValueFrom(this.analyzerService.echo(text));
40-
}
4134
}

0 commit comments

Comments
 (0)