Changeset ac11efe for src/mapservice


Ignore:
Timestamp:
Nov 24, 2019, 6:14:09 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
f5feba5
Parents:
72cc339
Message:

Implemented Log retrieving on the webservice

Location:
src/mapservice
Files:
1 added
4 edited

Legend:

Unmodified
Added
Removed
  • src/mapservice/openapi.yaml

    r72cc339 rac11efe  
    377377        '404':
    378378          $ref: '#/components/responses/NotFound'
     379  /devices:
     380    get:
     381      description: Returns all devices of user
     382      tags:
     383        - devices
     384      summary: Find devices by id
     385      operationId: devicesGet
     386      security:
     387        - basicAuth: []
     388        - apiKeyAuth: []
     389      parameters:
     390        - name: name
     391          in: query
     392          schema:
     393            $ref: '#/components/schemas/itemName'
     394          example: Love
     395        - $ref: '#/components/parameters/orderBy'
     396        - $ref: '#/components/parameters/offset'
     397        - $ref: '#/components/parameters/limit'
     398      responses:
     399        '200':
     400          description: OK
     401          content:
     402            application/json:
     403              schema:
     404                $ref: '#/components/schemas/devices'
     405              examples:
     406                Devices:
     407                  $ref: '#/components/examples/devices'
     408        '404':
     409          $ref: '#/components/responses/NotFound'
     410    post:
     411      description: Adds a new device to the database
     412      tags:
     413        - devices
     414      summary: Add a new device
     415      operationId: devicesCreate
     416      security:
     417        - basicAuth: []
     418        - apiKeyAuth: []
     419      requestBody:
     420        content:
     421          application/json:
     422            schema:
     423              $ref: '#/components/schemas/DeviceCreation'
     424            example:
     425              name: Lovely Boat
     426              sensorDepth: 2
     427      responses:
     428        '201':
     429          description: Device created
     430          content:
     431            application/json:
     432              schema:
     433                $ref: '#/components/schemas/Device'
     434              examples:
     435                Device:
     436                  $ref: '#/components/examples/Device'
     437        '400':
     438          $ref: '#/components/responses/BadRequest'
     439        '401':
     440          $ref: '#/components/responses/Unauthorized'
     441  '/devices/{id}':
     442    get:
     443      description: Returns the device identified by id
     444      tags:
     445        - devices
     446      summary: Represents a device
     447      operationId: devicesGetById
     448      security:
     449        - basicAuth: []
     450        - apiKeyAuth: []
     451      parameters:
     452        - name: id
     453          in: path
     454          description: Item ID
     455          required: true
     456          schema:
     457            $ref: '#/components/schemas/itemId'
     458      responses:
     459        '200':
     460          description: OK
     461          content:
     462            application/json:
     463              schema:
     464                $ref: '#/components/schemas/Device'
     465              examples:
     466                Water:
     467                  $ref: '#/components/examples/Device'
     468        '404':
     469          $ref: '#/components/responses/NotFound'
     470    delete:
     471      description: Deletes given device and returns remaining devices of the user
     472      tags:
     473        - devices
     474      summary: Deletes device
     475      operationId: devicesDeviceDelete
     476      security:
     477        - basicAuth: []
     478        - apiKeyAuth: []
     479      parameters:
     480        - name: id
     481          in: path
     482          description: Item id
     483          required: true
     484          schema:
     485            $ref: '#/components/schemas/itemId'
     486          example: 1
     487      responses:
     488        '200':
     489          description: OK
     490          content:
     491            application/json:
     492              schema:
     493                $ref: '#/components/schemas/devices'
     494              example:
     495                Devices:
     496                  $ref: '#/components/examples/devices'
     497        '400':
     498          $ref: '#/components/responses/BadRequest'
     499        '401':
     500          $ref: '#/components/responses/Unauthorized'
     501        '404':
     502          $ref: '#/components/responses/NotFound'
     503  '/logs':
    379504    post:
    380505      description: Adds a new log to the database
    381506      tags:
    382         - waters
     507        - logs
    383508      summary: Add a new log
    384       operationId: watersCreateLog
    385       parameters:
    386         - name: water_id
    387           in: path
    388           description: Water ID
    389           required: true
    390           schema:
    391             $ref: '#/components/schemas/itemId'
    392         - name: gauge_id
    393           in: path
    394           description: Gauge ID
    395           required: true
    396           schema:
    397             $ref: '#/components/schemas/itemId'
     509      operationId: logsLogCreate
    398510      security:
    399511        - basicAuth: []
    … …  
    424536        '401':
    425537          $ref: '#/components/responses/Unauthorized'
    426   '/waters/{water_id}/gauges/{gauge_id}/{log_id}':
     538  '/logs/{log_id}':
    427539    get:
    428540      description: Returns the log identified by id
    429541      tags:
    430         - waters
     542        - logs
    431543      summary: Represents a log
    432       operationId: watersLogGetById
     544      operationId: logsLogGetById
    433545      parameters:
    434         - name: water_id
    435           in: path
    436           description: Water ID
    437           required: true
    438           schema:
    439             $ref: '#/components/schemas/itemId'
    440         - name: gauge_id
    441           in: path
    442           description: Gauge ID
    443           required: true
    444           schema:
    445             $ref: '#/components/schemas/itemId'
    446546        - name: log_id
    447547          in: path
    … …  
    473573      description: Deletes given log and returns remaining logs of the gauge
    474574      tags:
    475         - waters
     575        - logs
    476576      summary: Deletes log
    477       operationId: watersLogDelete
     577      operationId: logsLogDelete
    478578      security:
    479579        - basicAuth: []
    480580        - apiKeyAuth: []
    481581      parameters:
    482         - name: water_id
    483           in: path
    484           description: Water ID
    485           required: true
    486           schema:
    487             $ref: '#/components/schemas/itemId'
    488         - name: gauge_id
    489           in: path
    490           description: Gauge ID
    491           required: true
    492           schema:
    493             $ref: '#/components/schemas/itemId'
    494582        - name: log_id
    495583          in: path
    … …  
    508596                Devices:
    509597                  $ref: '#/components/examples/logs'
    510         '400':
    511           $ref: '#/components/responses/BadRequest'
    512         '401':
    513           $ref: '#/components/responses/Unauthorized'
    514         '404':
    515           $ref: '#/components/responses/NotFound'
    516   /devices:
    517     get:
    518       description: Returns all devices of user
    519       tags:
    520         - devices
    521       summary: Find devices by id
    522       operationId: devicesGet
    523       security:
    524         - basicAuth: []
    525         - apiKeyAuth: []
    526       parameters:
    527         - name: name
    528           in: query
    529           schema:
    530             $ref: '#/components/schemas/itemName'
    531           example: Love
    532         - $ref: '#/components/parameters/orderBy'
    533         - $ref: '#/components/parameters/offset'
    534         - $ref: '#/components/parameters/limit'
    535       responses:
    536         '200':
    537           description: OK
    538           content:
    539             application/json:
    540               schema:
    541                 $ref: '#/components/schemas/devices'
    542               examples:
    543                 Devices:
    544                   $ref: '#/components/examples/devices'
    545         '404':
    546           $ref: '#/components/responses/NotFound'
    547     post:
    548       description: Adds a new device to the database
    549       tags:
    550         - devices
    551       summary: Add a new device
    552       operationId: devicesCreate
    553       security:
    554         - basicAuth: []
    555         - apiKeyAuth: []
    556       requestBody:
    557         content:
    558           application/json:
    559             schema:
    560               $ref: '#/components/schemas/DeviceCreation'
    561             example:
    562               name: Lovely Boat
    563               sensorDepth: 2
    564       responses:
    565         '201':
    566           description: Device created
    567           content:
    568             application/json:
    569               schema:
    570                 $ref: '#/components/schemas/Device'
    571               examples:
    572                 Device:
    573                   $ref: '#/components/examples/Device'
    574         '400':
    575           $ref: '#/components/responses/BadRequest'
    576         '401':
    577           $ref: '#/components/responses/Unauthorized'
    578   '/devices/{id}':
    579     get:
    580       description: Returns the device identified by id
    581       tags:
    582         - devices
    583       summary: Represents a device
    584       operationId: devicesGetById
    585       security:
    586         - basicAuth: []
    587         - apiKeyAuth: []
    588       parameters:
    589         - name: id
    590           in: path
    591           description: Item ID
    592           required: true
    593           schema:
    594             $ref: '#/components/schemas/itemId'
    595       responses:
    596         '200':
    597           description: OK
    598           content:
    599             application/json:
    600               schema:
    601                 $ref: '#/components/schemas/Device'
    602               examples:
    603                 Water:
    604                   $ref: '#/components/examples/Device'
    605         '404':
    606           $ref: '#/components/responses/NotFound'
    607     delete:
    608       description: Deletes given device and returns remaining devices of the user
    609       tags:
    610         - devices
    611       summary: Deletes device
    612       operationId: devicesDeviceDelete
    613       security:
    614         - basicAuth: []
    615         - apiKeyAuth: []
    616       parameters:
    617         - name: id
    618           in: path
    619           description: Item id
    620           required: true
    621           schema:
    622             $ref: '#/components/schemas/itemId'
    623           example: 1
    624       responses:
    625         '200':
    626           description: OK
    627           content:
    628             application/json:
    629               schema:
    630                 $ref: '#/components/schemas/devices'
    631               example:
    632                 Devices:
    633                   $ref: '#/components/examples/devices'
    634598        '400':
    635599          $ref: '#/components/responses/BadRequest'
    … …  
    786750          $ref: '#/components/schemas/Gauges'
    787751        logs:
    788           $ref: '#/components/schemas/LogMetaData'
     752          $ref: '#/components/schemas/logs'
    789753      required:
    790754        - waterId
    … …  
    820784          $ref: '#/components/schemas/point'
    821785        logs:
    822           $ref: '#/components/schemas/LogMetaData'
     786          $ref: '#/components/schemas/logs'
    823787        comment:
    824788          $ref: '#/components/schemas/comment'
    … …  
    883847        sensorDepth:
    884848          $ref: '#/components/schemas/sensorDepth'
     849        logs:
     850          $ref: '#/components/schemas/logs'
    885851        comment:
    886852          $ref: '#/components/schemas/comment'
    … …  
    924890          type: number
    925891          format: float
     892      required:
     893        - datetime
     894        - location
    926895    LogMetaData:
    927896      title: 'Metadata of a log, without log entries'
    … …  
    931900          $ref: '#/components/schemas/itemId'
    932901        submitter:
    933           $ref: '#/components/schemas/User'
     902          $ref: '#/components/schemas/username'
    934903        water:
    935904          $ref: '#/components/schemas/itemId'
    … …  
    941910          $ref: '#/components/schemas/GaugeLevel'
    942911        start:
    943           title: Date and Time of the first log entry
     912          title: Date and Time of the first log entry in UTC timezone
    944913          type: string
    945914          format: date-time
    946915        end:
    947           title: Date and Time of the last log entry
     916          title: Date and Time of the last log entry in UTC timezone
    948917          type: string
    949918          format: date-time
    … …  
    978947      properties:
    979948        water:
    980           $ref: '#/components/schemas/Water'
     949          $ref: '#/components/schemas/itemId'
    981950        device:
    982           $ref: '#/components/schemas/Device'
     951          $ref: '#/components/schemas/itemId'
    983952        gauge:
    984           $ref: '#/components/schemas/Gauge'
     953          $ref: '#/components/schemas/itemId'
    985954        gaugeLevel:
    986955          $ref: '#/components/schemas/GaugeLevel'
    … …  
    996965      type: array
    997966      items:
    998         $ref: '#/components/schemas/Log'
     967        $ref: '#/components/schemas/LogMetaData'
    999968    LogGeoJson:
    1000969      title: Log in GeoJson format
    … …  
    13121281  - name: devices
    13131282    description: All actions used to manage devices of an user
     1283  - name: logs
     1284    description: All actions used to manage logs of an water, device, gauge or user
  • src/mapservice/src/server_impl/controllers/DevicesController.py

    r72cc339 rac11efe  
    6161                raise MapserviceUnauthorized
    6262       
    63         print(id)
    6463        if not Device.query.filter_by(owner = user).filter_by(id=id).delete():
    6564                raise MapserviceBadRequest(detail="Could not delete device with id {}".format(id))
  • src/mapservice/src/server_impl/controllers/WatersController.py

    r72cc339 rac11efe  
    1717import connexion
    1818
    19 from ..database.Model import User, Water, Gauge, db
     19from ..database.Model import User, Water, Gauge, Log, db
    2020from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
    2121
  • src/mapservice/src/server_impl/database/Model.py

    r72cc339 rac11efe  
    2121from geoalchemy2 import Geometry
    2222from geoalchemy2.shape import to_shape
     23from sqlalchemy_utc import UtcDateTime
    2324from shapely import wkb
    2425import hashlib
    … …  
    123124                        for gauge in obj.gauges:
    124125                                result['gauges'].append(gauge.to_dict())
     126                if obj.logs:
     127                        logs = []
     128                        for log in obj.logs:
     129                                logs.append(log.meta_data())
     130                        result['logs'] = logs
    125131                return result
    126132       
    … …  
    147153                location = Gauge.wkb_to_dict(obj.location)
    148154                result['location'] = [location['longitude'], location['latitude']]
     155                if obj.logs:
     156                        logs = []
     157                        for log in obj.logs:
     158                                logs.append(log.meta_data())
     159                        result['logs'] = logs
    149160                if obj.comment:
    150161                        result['comment'] = obj.comment
    … …  
    186197        def to_dict(obj):
    187198                result = { 'deviceId': obj.id, 'name': obj.name, 'sensorDepth': obj.sensor_depth }
     199                if obj.logs:
     200                        logs = []
     201                        for log in obj.logs:
     202                                logs.append(log.meta_data())
     203                        result['logs'] = logs
    188204                if obj.comment:
    189205                        result['comment'] = obj.comment
    190206                return result
     207       
     208class Log(db.Model):
     209        __tablename__ = "logs"
     210       
     211        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
     212        submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
     213        water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
     214        device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
     215        gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
     216        gauge_level = db.Column(db.Float, nullable=False)
     217        start = db.Column(UtcDateTime, nullable=False)
     218        end = db.Column(UtcDateTime, nullable=False)
     219        comment = db.Column(db.String(255))
     220       
     221        submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
     222        water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
     223        device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
     224        gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
     225       
     226        def meta_data(obj):
     227                result = {
     228                        'logId': obj.id,
     229                        'submitter': obj.submitter.username,
     230                        'water': obj.water.id,
     231                        'device': obj.device.id,
     232                        'gauge': obj.gauge.id,
     233                        'gaugeLevel': obj.gauge_level,
     234                        'start': obj.start.isoformat('T'),
     235                        'end': obj.end.isoformat('T')
     236                }
     237                entries_count = 0
     238                if obj.log_entries:
     239                        entries_count = len(obj.log_entries)
     240                result['entriesCount'] = entries_count
     241                if obj.comment:
     242                        result['comment'] = obj.comment
     243                return result
     244       
     245        def log(obj):
     246                result = { 'metaData': obj.meta_data() }
     247                entries = []
     248                if obj.log_entries:
     249                        for log in obj.log_entries:
     250                                entries.append(log.to_dict())
     251                result['entries'] = entries
     252                return result
     253
     254class LogEntry(db.Model):
     255        __tablename__ = "logentries"
     256       
     257        id = db.Column(db.Integer, primary_key=True, autoincrement=True)
     258        log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
     259        datetime = db.Column(UtcDateTime, nullable=False)
     260        # POINT(Lon Lat)
     261        location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
     262        water_depth = db.Column(db.Float)
     263       
     264        log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
     265       
     266        def to_dict(obj):
     267                result = {'datetime': obj.datetime.isoformat('T') }
     268                location = Gauge.wkb_to_dict(obj.location)
     269                result['location'] = [location['longitude'], location['latitude']]
     270                if obj.water_depth:
     271                        result['waterDepth'] = obj.water_depth
     272                return result
     273       
    191274
    192275def db_setup():
    … …  
    200283        db_setup()
    201284       
    202         print("CREATING DATABASE TEST CONTENT")
     285        print("CREATING DATABASE TEST CONTENT...")
    203286        with db.session.no_autoflush:
    204287                test_user_john = None
    … …  
    223306                        db.session.commit()
    224307               
    225                 test_key_del = ApiKey(user=test_user_jane, key='DelApiKey4711')
    226308                if len(ApiKey.query.filter_by(key='DelApiKey4711').all()) < 1:
    227                         db.session.add(test_key_del)
     309                        db.session.add(ApiKey(user=test_user_jane, key='DelApiKey4711'))
     310                        db.session.commit()
    228311                if len(ApiKey.query.filter_by(key='test_key').all()) < 1:
    229                         test_key = ApiKey(user=test_user_jane, key='test_key')
    230                         db.session.add(test_key)
     312                        db.session.add(ApiKey(user=test_user_jane, key='test_key'))
     313                        db.session.commit()
    231314                if len(ApiKey.query.filter_by(key='ApiKey4712').all()) < 1:
    232                         test_key = ApiKey(user=test_user_jane, key='ApiKey4712')
    233                         db.session.add(test_key)
     315                        db.session.add(ApiKey(user=test_user_jane, key='ApiKey4712'))
     316                        db.session.commit()
     317               
    234318                mississippi = None
    235319                query = Water.query.filter_by(name='Mississippi').all()
    … …  
    244328                        forggensee = Water(name='Forggensee', manager=test_user_john, osm_id=897899, osm_type=OsmType.Relation)
    245329                        db.session.add(forggensee)
    246                                                        
    247                 if len(Gauge.query.filter_by(name='New Orleans').all()) < 1:
     330                        db.session.commit()
     331               
     332                new_orleans = None
     333                query = Gauge.query.filter_by(name='New Orleans').all()
     334                if len(query) == 1:
     335                        new_orleans = query[0]
     336                else:
    248337                        new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)')
    249338                        db.session.add(new_orleans)
    250                        
    251                
    252                 if len(Device.query.filter_by(name='GnuBoat 1').all()) < 1:
     339                        db.session.commit()
     340               
     341                gnuboat_one = None
     342                query = Device.query.filter_by(name='GnuBoat 1').all()
     343                if len(query) == 1:
     344                        gnuboat_one = query[0]
     345                else:
    253346                        gnuboat_one = Device(name='GnuBoat 1', owner=test_user_jane, sensor_depth=0.2, comment='SUP attachment')
    254347                        db.session.add(gnuboat_one)
    255                 db.session.commit()
    256 
     348                        db.session.commit()
     349                       
     350                if len(Log.query.filter_by(submitter=test_user_jane).all()) < 1:
     351                        import pandas as pd
     352                        import random
     353                        import pytz
     354                       
     355                        end = datetime.datetime.now(pytz.timezone('Europe/Berlin'))
     356                        start = end - datetime.timedelta(hours=1)
     357                        log = Log(submitter=test_user_jane, water=mississippi, device=gnuboat_one, gauge=new_orleans, gauge_level=2.2, start=start, end=end, comment='Test log for {}'.format(mississippi.name))
     358                        db.session.add(log)
     359                       
     360                        i = 0
     361                        for entrie_datetime in pd.date_range(start=start, end=end, freq='S'):
     362                                db.session.add(LogEntry(log=log, datetime=entrie_datetime, location='SRID=4326;POINT(-90.1361{} 29.934722)'.format(i), water_depth=random.random() * 10.0))
     363                                i += 1
     364                       
     365                       
     366                        db.session.commit()
     367                print("...Finished")
     368
Note: See TracChangeset for help on using the changeset viewer.