Added POST and PUT endpoint for /ship

This commit is contained in:
Daniel Schick 2023-12-20 18:06:41 +01:00
parent 3ae282102c
commit ae9053bcaf
4 changed files with 151 additions and 4 deletions

View File

@ -1,7 +1,10 @@
from flask import Blueprint, request
from .. import impl
from ..services.auth_guard import auth_guard
from marshmallow import EXCLUDE
from ..schemas import model
import json
import logging
bp = Blueprint('ships', __name__)
@ -14,3 +17,33 @@ def GetShips():
return impl.ships.GetShips(token)
else:
return json.dumps("not authenticated"), 403
@bp.route('/ships', methods=['post'])
@auth_guard() # no restriction by role
def PostShip():
try:
content = request.get_json(force=True)
loadedModel = model.ShipSchema().load(data=content, many=False, partial=True)
except Exception as ex:
logging.error(ex)
print(ex)
return json.dumps("bad format"), 400
return impl.ships.PostShip(loadedModel)
@bp.route('/ships', methods=['put'])
@auth_guard() # no restriction by role
def PutShip():
try:
content = request.get_json(force=True)
loadedModel = model.ShipSchema().load(data=content, many=False, partial=True, unknown=EXCLUDE)
except Exception as ex:
logging.error(ex)
print(ex)
return json.dumps("bad format"), 400
return impl.ships.PutShip(loadedModel)

View File

@ -31,3 +31,98 @@ def GetShips(token):
def PostShip(schemaModel):
"""
:param schemaModel: The deserialized model of the record to be inserted
"""
# TODO: Validate the incoming data
# This creates a *new* entry
try:
pooledConnection = local_db.getPoolConnection()
commands = pydapper.using(pooledConnection)
query = "INSERT INTO ship ("
isNotFirst = False
for key in schemaModel.keys():
if key == "id":
continue
if key == "created":
continue
if key == "modified":
continue
if isNotFirst:
query += ","
isNotFirst = True
query += key
query += ") VALUES ("
isNotFirst = False
for key in schemaModel.keys():
if key == "id":
continue
if key == "created":
continue
if key == "modified":
continue
if isNotFirst:
query += ","
isNotFirst = True
query += "?" + key + "?"
query += ")"
commands.execute(query, schemaModel)
new_id = commands.execute_scalar("select last_insert_id()")
pooledConnection.close()
return json.dumps({"id" : new_id}), 201, {'Content-Type': 'application/json; charset=utf-8'}
except Exception as ex:
logging.error(ex)
print(ex)
result = {}
result["message"] = "call failed"
return json.dumps(result), 500, {'Content-Type': 'application/json; charset=utf-8'}
def PutShip(schemaModel):
"""
:param schemaModel: The deserialized model of the record to be inserted
"""
# This updates an *existing* entry
try:
pooledConnection = local_db.getPoolConnection()
commands = pydapper.using(pooledConnection)
query = "UPDATE ship SET "
isNotFirst = False
for key in schemaModel.keys():
if key == "id":
continue
if key == "created":
continue
if key == "modified":
continue
if isNotFirst:
query += ", "
isNotFirst = True
query += key + " = ?" + key + "? "
query += "WHERE id = ?id?"
affected_rows = commands.execute(query, param=schemaModel)
pooledConnection.close()
return json.dumps({"id" : schemaModel["id"]}), 200, {'Content-Type': 'application/json; charset=utf-8'}
except Exception as ex:
logging.error(ex)
print(ex)
result = {}
result["message"] = "call failed"
return json.dumps(result), 500, {'Content-Type': 'application/json; charset=utf-8'}

View File

@ -11,7 +11,7 @@ def initPool(instancePath):
try:
global config_path
if(config_path == None):
config_path = os.path.join(instancePath,'../../../secure/connection_data_devel.json');
config_path = os.path.join(instancePath,'E:/temp/connection_data.json');
print (config_path)

View File

@ -185,7 +185,6 @@ class UserSchema(Schema):
@dataclass
class Times:
id: int
eta_berth: datetime
eta_berth_fixed: bool
@ -223,7 +222,7 @@ class User:
modified: datetime
@dataclass
class Ship(Schema):
class Ship:
id: int
name: str
imo: int
@ -233,11 +232,31 @@ class Ship(Schema):
width: float
is_tug: bool
bollard_pull: int
eni: str
eni: int
created: datetime
modified: datetime
deleted: bool
class ShipSchema(Schema):
def __init__(self):
super().__init__(unknown=None)
pass
id = fields.Int(Required=False)
name = fields.String(allow_none=False, metadata={'Required':True})
imo = fields.Int(allow_none=False, metadata={'Required':True})
callsign = fields.String(allow_none=True, metadata={'Required':False})
participant_id = fields.Int(allow_none=True, metadata={'Required':False})
length = fields.Float(allow_none=True, metadata={'Required':False})
width = fields.Float(allow_none=True, metadata={'Required':False})
is_tug = fields.Bool(allow_none=True, metadata={'Required':False}, default=False)
bollard_pull = fields.Int(allow_none=True, metadata={'Required':False})
eni = fields.Int(allow_none=True, metadata={'Required':False})
created = fields.DateTime(allow_none=True, metadata={'Required':False})
modified = fields.DateTime(allow_none=True, metadata={'Required':False})
deleted = fields.Int(allow_none=True, metadata={'Required':False})
class TimesId(Schema):
pass