Compare commits

..

22 Commits

Author SHA1 Message Date
8c1730389c
database configuration 2021-01-15 17:19:18 +01:00
4dad188a07
Merge branch 'master' of ssh://home.hottis.de:2922/wolutator/hausverwaltung 2021-01-15 17:03:43 +01:00
b9031157fb
add Dockerfile 2021-01-15 17:03:33 +01:00
eac10f8484
Merge branch 'master' of https://home.hottis.de/gitlab/wolutator/hausverwaltung into master 2021-01-15 16:40:30 +01:00
f88d3b5b39
last changes 2021-01-15 16:40:20 +01:00
e031660df9
webservice changes 2021-01-15 16:19:05 +01:00
24482da680
database in service 2021-01-15 12:53:46 +01:00
ceadf3338f
error handling in ui 2021-01-15 12:23:25 +01:00
124fca001a
changes in service 2021-01-15 12:22:40 +01:00
9717d171bf
refactor 2021-01-14 21:52:56 +01:00
521e916bbd
hero put 2021-01-14 17:29:17 +01:00
6aec708c84
Merge branch 'master' of https://home.hottis.de/gitlab/wolutator/hausverwaltung into master 2021-01-14 17:10:48 +01:00
53a93a948d
corsified server 2021-01-14 17:10:26 +01:00
8374e1831b
now it works, it was CORS 2021-01-14 17:00:56 +01:00
989e617ffe
fix 2021-01-14 13:46:44 +01:00
1b756cc090
fixes 2021-01-14 13:23:12 +01:00
9570bef24d
http 2021-01-14 12:51:40 +01:00
d4caaae0f2
not working 2021-01-13 15:40:43 +01:00
da51077869
works 2021-01-13 15:23:04 +01:00
845f3fd400
await 2021-01-13 13:02:27 +01:00
13c72409c5
promise learn 2021-01-13 12:07:33 +01:00
c6e338502e
seems to be working like this 2021-01-12 17:56:59 +01:00
25 changed files with 2162 additions and 2017 deletions

File diff suppressed because it is too large Load Diff

View File

@ -5,11 +5,10 @@
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"build-prod": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"build-electron": "ng build --base-href . && cp src/electron/* dist/",
"electron": "npm run build-electron && ./node_modules/.bin/electron dist/"
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
@ -18,6 +17,7 @@
"@angular/compiler": "~11.0.6",
"@angular/core": "~11.0.6",
"@angular/forms": "~11.0.6",
"@angular/http": "^7.2.16",
"@angular/platform-browser": "~11.0.6",
"@angular/platform-browser-dynamic": "~11.0.6",
"@angular/router": "~11.0.6",
@ -30,9 +30,8 @@
"@angular/cli": "~11.0.6",
"@angular/compiler-cli": "~11.0.6",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"@types/node": "^12.19.13",
"codelyzer": "^6.0.0",
"electron": "^11.1.1",
"jasmine-core": "~3.6.0",
"jasmine-spec-reporter": "~5.0.0",
"karma": "~5.1.0",

View File

@ -1,7 +1,7 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http'
import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
@ -20,7 +20,8 @@ import { DashboardComponent } from './dashboard/dashboard.component';
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]

View File

@ -1,6 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';
@Component({
selector: 'app-dashboard',
@ -10,14 +11,18 @@ import { HeroService } from '../hero.service';
export class DashboardComponent implements OnInit {
heroes: Hero[] = [];
constructor(private heroService: HeroService) { }
constructor(private heroService: HeroService, private messageService: MessageService) { }
ngOnInit(): void {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes.slice(1, 5));
async getHeroes(): Promise<void> {
try {
this.heroes = await this.heroService.getHeroes();
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
}

View File

@ -4,6 +4,7 @@ import { Location } from '@angular/common';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
import { MessageService } from '../message.service';
@Component({
selector: 'app-hero-detail',
@ -14,22 +15,31 @@ export class HeroDetailComponent implements OnInit {
@Input() hero: Hero;
constructor(private route: ActivatedRoute, private heroService: HeroService, private location: Location) { }
constructor(private route: ActivatedRoute, private heroService: HeroService, private location: Location, private messageService: MessageService) { }
ngOnInit(): void {
this.getHero();
}
getHero(): void {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id).subscribe(hero => this.hero = hero);
async getHero(): Promise<void> {
try {
const id = +this.route.snapshot.paramMap.get('id');
this.hero = await this.heroService.getHero(id)
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
goBack(): void {
this.location.back();
}
save(): void {
this.heroService.updateHero(this.hero).subscribe(() => this.goBack());
async save(): Promise<void> {
try {
await this.heroService.updateHero(this.hero)
this.goBack()
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
}

View File

@ -1,29 +1,28 @@
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { MessageService } from './message.service';
@Injectable({
providedIn: 'root'
})
export class HeroService {
constructor(private messageService: MessageService, private http: HttpClient) { }
constructor(private messageService: MessageService) { }
getHeroes(): Observable<Hero[]> {
getHeroes(): Promise<Hero[]> {
this.messageService.add('HeroService: fetched heroes');
return of(HEROES);
return this.http.get<Hero[]>(`http://172.16.3.185:5000/heroes/heroes`).toPromise()
}
getHero(id: number): Observable<Hero> {
getHero(id: number): Promise<Hero> {
this.messageService.add(`HeroService: fetch hero id=${id}`);
return of(HEROES.find(hero => hero.id === id));
return this.http.get<Hero>(`http://172.16.3.185:5000/heroes/hero/${id}`).toPromise()
}
updateHero(hero: Hero): Observable<any> {
updateHero(hero: Hero): Promise<any> {
this.messageService.add(`HeroService: save change: id=${hero.id}, name=${hero.name}`);
return of(true);
return this.http.put<Hero>(`http://172.16.3.185:5000/heroes/hero/${hero.id}`, hero).toPromise()
}
}

View File

@ -18,8 +18,12 @@ export class HeroesComponent implements OnInit {
constructor(private heroService: HeroService, private messageService: MessageService) { }
getHeroes(): void {
this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes);
async getHeroes() {
try {
this.heroes = await this.heroService.getHeroes();
} catch (err) {
this.messageService.add(JSON.stringify(err, undefined, 4))
}
}
ngOnInit(): void {

View File

@ -1,34 +0,0 @@
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = requite('url')
let mainWindow
function createWindow() {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file',
slashes: true
}))
mainWindow.webContents.openDevTools()
mainWindow.on('closed', function() {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function() {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function() {
if (mainWindow === null) {
createWindow()
}
})

View File

@ -1,5 +0,0 @@
{
"name": "angular-electron",
"version": "0.1.0",
"main": "main.js"
}

View File

@ -3,7 +3,7 @@
<head>
<meta charset="utf-8">
<title>AngularTourOfHeroes</title>
<base href="./">
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

View File

@ -55,7 +55,7 @@
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone-mix'; // Included with Angular CLI.
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************

46
tools/app/promise-learn/.gitignore vendored Normal file
View File

@ -0,0 +1,46 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
/node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,64 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const mariadb_1 = __importDefault(require("mariadb"));
let conn;
class DbHandle {
constructor() { }
async connect() {
this._conn = await mariadb_1.default.createConnection({
host: '172.16.10.18',
user: 'heroes',
password: 'test123',
database: 'heroes'
});
}
async getHeroes() {
var _a, _b;
const result = (_b = await ((_a = this._conn) === null || _a === void 0 ? void 0 : _a.query("SELECT id, name FROM hero"))) !== null && _b !== void 0 ? _b : Promise.reject(new Error('Connection not ready 1'));
return result.map((row) => {
var _a;
return { id: row.id, name: (_a = row.name) !== null && _a !== void 0 ? _a : 'unknown' };
});
}
close() {
var _a, _b;
return (_b = (_a = this._conn) === null || _a === void 0 ? void 0 : _a.end()) !== null && _b !== void 0 ? _b : Promise.reject(new Error('Connection not ready 2'));
}
}
/*
const dbHandle = new DbHandle()
dbHandle.connect()
.then(() => dbHandle.get("SELECT * FROM hero"))
.then((result) => {
console.log(result)
return dbHandle.close()
})
.catch((err) => {
console.log(err)
})
*/
async function exec() {
const dbHandle = new DbHandle();
try {
await dbHandle.connect();
const heroes = await dbHandle.getHeroes();
console.log(heroes);
}
finally {
await dbHandle.close();
}
}
exec().catch((err) => console.log(err.message));
/*
dbHandle.get("SELECT * FROM hero")
.then((result) => {
console.log(result)
return dbHandle.close()
})
.catch((err) => {
console.log(err.message)
})
*/

View File

@ -0,0 +1,87 @@
{
"name": "promise-learn",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@types/geojson": {
"version": "7946.0.7",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.7.tgz",
"integrity": "sha512-wE2v81i4C4Ol09RtsWFAqg3BUitWbHSpSlIo+bNdsCJijO9sjme+zm+73ZMCa/qMC8UEERxzGbvmr1cffo2SiQ=="
},
"@types/node": {
"version": "14.14.20",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.20.tgz",
"integrity": "sha512-Y93R97Ouif9JEOWPIUyU+eyIdyRqQR0I8Ez1dzku4hDx34NWh4HbtIc3WNzwB1Y9ULvNGeu5B8h8bVL5cAk4/A=="
},
"denque": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-1.5.0.tgz",
"integrity": "sha512-CYiCSgIF1p6EUByQPlGkKnP1M9g0ZV3qMIrqMqZqdwazygIA/YP2vrbcyl1h/WppKJTdl1F85cXIle+394iDAQ=="
},
"iconv-lite": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.2.tgz",
"integrity": "sha512-2y91h5OpQlolefMPmUlivelittSWy0rP+oYVpn6A7GwVHNE8AWzoYOBNmlwks3LobaJxgHCYZAnyNo2GgpNRNQ==",
"requires": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
}
},
"long": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz",
"integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA=="
},
"mariadb": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/mariadb/-/mariadb-2.5.2.tgz",
"integrity": "sha512-SfaBl5/LiX2qJNNr7wCQvizVjtWxVm1CUWYKe+y4OMeyYMM6g0GhwX7/BbGtv/O3WthnGrM+Kj1imFnlescO0w==",
"requires": {
"@types/geojson": "^7946.0.7",
"@types/node": "^14.14.7",
"denque": "^1.4.1",
"iconv-lite": "^0.6.2",
"long": "^4.0.0",
"moment-timezone": "^0.5.32",
"please-upgrade-node": "^3.2.0"
}
},
"moment": {
"version": "2.29.1",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.29.1.tgz",
"integrity": "sha512-kHmoybcPV8Sqy59DwNDY3Jefr64lK/by/da0ViFcuA4DH0vQg5Q6Ze5VimxkfQNSC+Mls/Kx53s7TjP1RhFEDQ=="
},
"moment-timezone": {
"version": "0.5.32",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.32.tgz",
"integrity": "sha512-Z8QNyuQHQAmWucp8Knmgei8YNo28aLjJq6Ma+jy1ZSpSk5nyfRT8xgUbSQvD2+2UajISfenndwvFuH3NGS+nvA==",
"requires": {
"moment": ">= 2.9.0"
}
},
"please-upgrade-node": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz",
"integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==",
"requires": {
"semver-compare": "^1.0.0"
}
},
"safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"semver-compare": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz",
"integrity": "sha1-De4hahyUGrN+nvsXiPavxf9VN/w="
},
"typescript": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.1.3.tgz",
"integrity": "sha512-B3ZIOf1IKeH2ixgHhj6la6xdwR9QrLC5d1VKeCSY4tvkqhF2eqd9O7txNlS0PO3GrBAFIdr3L1ndNwteUbZLYg==",
"dev": true
}
}
}

View File

@ -0,0 +1,20 @@
{
"name": "promise-learn",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsc",
"start": "npm run build && node build/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^14.14.20",
"typescript": "^4.1.3"
},
"dependencies": {
"mariadb": "^2.5.2"
}
}

View File

@ -0,0 +1,75 @@
import mariadb from 'mariadb'
import { stringify } from 'querystring'
let conn : mariadb.Connection
interface Hero {
id: number
name: string
}
class DbHandle {
private _conn? : mariadb.Connection
public constructor() {}
public async connect() : Promise<void> {
this._conn = await mariadb.createConnection({
host: '172.16.10.18',
user: 'heroes',
password: 'test123',
database: 'heroes'
})
}
public async getHeroes() : Promise<Hero[]> {
const result = await this._conn?.query("SELECT id, name FROM hero") ?? Promise.reject(new Error('Connection not ready 1'))
return result.map((row: Record<string, unknown>) => {
return { id: row.id, name: row.name ?? 'unknown' }
})
}
public close() : Promise<void> {
return this._conn?.end() ?? Promise.reject(new Error('Connection not ready 2'))
}
}
/*
const dbHandle = new DbHandle()
dbHandle.connect()
.then(() => dbHandle.get("SELECT * FROM hero"))
.then((result) => {
console.log(result)
return dbHandle.close()
})
.catch((err) => {
console.log(err)
})
*/
async function exec() : Promise<void> {
const dbHandle = new DbHandle()
try {
await dbHandle.connect()
const heroes : Hero[] = await dbHandle.getHeroes()
console.log(heroes)
} finally {
await dbHandle.close()
}
}
exec().catch((err) => console.log(err.message))
/*
dbHandle.get("SELECT * FROM hero")
.then((result) => {
console.log(result)
return dbHandle.close()
})
.catch((err) => {
console.log(err.message)
})
*/

View File

@ -0,0 +1,71 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2017", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["es6"], /* Specify library files to be included in the compilation. */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "build", /* Redirect output structure to the directory. */
"rootDir": "src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"resolveJsonModule": true, /* Include modules imported with '.json' extension */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

1
tools/ws/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__/

36
tools/ws/Dockerfile Normal file
View File

@ -0,0 +1,36 @@
FROM python:latest
LABEL Maintainer="Wolfgang Hottgenroth wolfgang.hottgenroth@icloud.com"
ARG APP_DIR="/opt/app"
ARG CONF_DIR="${APP_DIR}/config"
RUN \
apt update && \
apt install -y libmariadbclient-dev && \
pip3 install mariadb && \
pip3 install connexion && \
pip3 install connexion[swagger-ui] && \
pip3 install uwsgi && \
pip3 install flask-cors
RUN \
mkdir -p ${APP_DIR} && \
mkdir -p ${CONF_DIR} && \
useradd -d ${APP_DIR} -u 1000 user
COPY *.py ${APP_DIR}/
COPY swagger.yaml ${APP_DIR}/
COPY server.ini ${CONF_DIR}/
USER 1000:1000
WORKDIR ${APP_DIR}
VOLUME ${CONF_DIR}
EXPOSE 5000
EXPOSE 9191
CMD [ "uwsgi", "./config/server.ini" ]

19
tools/ws/dbpool.py Normal file
View File

@ -0,0 +1,19 @@
import mariadb
pool = None
def createConnectionPool(config):
global pool
pool = mariadb.ConnectionPool(
user = config['user'],
password = config['password'],
host = config['host'],
database = config['database'],
pool_name = 'heroes-wep-app',
pool_size = 5
)
def getConnection():
global pool
return pool.get_connection()

2
tools/ws/greeting.py Normal file
View File

@ -0,0 +1,2 @@
def say_hello(name=None):
return { "message": "Hello {}, from API!".format(name or "") }

63
tools/ws/heroes.py Normal file
View File

@ -0,0 +1,63 @@
from dbpool import getConnection
def get_heroes():
try:
dbh = getConnection()
heroes = []
cur = dbh.cursor()
cur.execute("SELECT id, name FROM hero")
for (id, name) in cur:
heroes.append({"id": id, "name": name})
return heroes
except Exception as err:
return str(err), 500
finally:
dbh.close()
def get_hero(id=None):
try:
dbh = getConnection()
cur = dbh.cursor()
cur.execute("SELECT id, name FROM hero WHERE id = ?", (id,))
hero = None
try:
(id, name) = cur.next()
hero = { "id": id, "name": name }
print("x1: {}\n".format(hero))
except StopIteration:
return "Hero not found", 404
try:
(id, name) = cur.next()
return "More than one hero by that id ({}, {})".format(id, name), 500
except:
pass
return hero
except Exception as err:
return str(err), 500
finally:
dbh.close()
def put_hero(id=None, hero=None):
try:
dbh = getConnection()
cur = dbh.cursor()
cur.execute("UPDATE hero SET name = ? WHERE id = ?", (hero["name"], id))
dbh.commit()
return 'Hero updated', 200
except StopIteration:
return 'Hero not found', 404
except Exception as err:
return str(err), 500
finally:
dbh.close()
def post_hero(hero=None):
try:
newHeroId = len(HEROES)
hero["id"] = newHeroId
HEROES.append(hero)
return 'Hero inserted', 201
except Exception as err:
return str(err), 403

13
tools/ws/server.ini Normal file
View File

@ -0,0 +1,13 @@
[uwsgi]
http = :5000
wsgi-file = server.py
processes = 4
threads = 2
stats = :9191
[database]
host = 172.16.10.18
user = heroes
password = test123
database = heroes

22
tools/ws/server.py Normal file
View File

@ -0,0 +1,22 @@
import connexion
from flask_cors import CORS
from dbpool import createConnectionPool
import configparser
# load configuration
config = configparser.ConfigParser()
config.read('./config/server.ini')
# prepare database connections
createConnectionPool(config['database'])
# instantiate the webservice
app = connexion.App(__name__)
app.add_api('swagger.yaml')
# CORSify it - otherwise Angular won't accept it
CORS(app.app)
# provide the webservice application to uwsgi
application = app.app

116
tools/ws/swagger.yaml Normal file
View File

@ -0,0 +1,116 @@
swagger: '2.0'
info:
title: Heroes
version: "0.1"
paths:
/greeting/hello:
get:
tags: [ "greeting" ]
operationId: greeting.say_hello
summary: Returns a greeting
parameters:
- name: name
in: query
type: string
responses:
200:
description: Successful response.
schema:
type: object
properties:
message:
type: string
description: Message greeting
/heroes/hero/{id}:
get:
tags: [ "heroes" ]
operationId: heroes.get_hero
summary: Returns hero by id
parameters:
- name: id
in: path
type: integer
required: true
responses:
200:
description: Successful response.
schema:
$ref: '#/definitions/Hero'
404:
description: Hero not found
500:
description: Some server error
put:
tags: [ "heroes" ]
operationId: heroes.put_hero
summary: Update a hero
parameters:
- name: id
in: path
type: integer
required: true
- name: hero
in: body
required: true
schema:
$ref: '#/definitions/Hero'
responses:
200:
description: Hero updated
403:
description: Some error
409:
description: Duplicate name
404:
description: Hero not found
500:
description: Some server error
/heroes/hero:
post:
tags: [ "heroes" ]
operationId: heroes.post_hero
summary: Insert a hero
parameters:
- name: hero
in: body
required: true
schema:
$ref: '#/definitions/Hero'
responses:
200:
description: Hero inserted
403:
description: Some error
409:
description: Duplicate name
500:
description: Some server error
/heroes/heroes:
get:
tags: [ "heroes" ]
operationId: heroes.get_heroes
summary: Returns all heroes
responses:
200:
description: Successful response.
schema:
type: array
items:
$ref: '#/definitions/Hero'
404:
description: No heroes available
500:
description: Some server error
definitions:
Hero:
description: Hero type
type: object
properties:
id:
type: integer
name:
type: string