Fixed database backend

This commit is contained in:
reedts 2018-05-17 14:19:05 +02:00
parent 0f3e9dc220
commit e9ed6bf9b4
2 changed files with 25 additions and 16 deletions

View File

@ -1,5 +1,8 @@
from peewee import * from peewee import *
from playhouse import sqlite_ext from playhouse import sqlite_ext
from playhouse.sqlite_ext import SqliteExtDatabase
db = SqliteExtDatabase('pywatts.db')
class WeatherStation(Model): class WeatherStation(Model):
@ -11,6 +14,9 @@ class WeatherStation(Model):
state = CharField() state = CharField()
id = CharField(unique=True) id = CharField(unique=True)
class Meta:
database = db
class Result(Model): class Result(Model):
station = ForeignKeyField(WeatherStation) station = ForeignKeyField(WeatherStation)
@ -18,3 +24,6 @@ class Result(Model):
temperature = sqlite_ext.JSONField() temperature = sqlite_ext.JSONField()
wind_speed = sqlite_ext.JSONField() wind_speed = sqlite_ext.JSONField()
class Meta:
database = db

View File

@ -1,10 +1,8 @@
from pypvwatts import PVWatts from pypvwatts import PVWatts
from pywatts.models import * from pywatts.db import *
from pathlib import Path from pathlib import Path
db = SqliteDatabase('pywatts.db')
def fetch_data(from_lon, to_lon, from_lat, to_lat, step_size=1): def fetch_data(from_lon, to_lon, from_lat, to_lat, step_size=1):
my_api_key = '' my_api_key = ''
@ -28,28 +26,30 @@ def fetch_data(from_lon, to_lon, from_lat, to_lat, step_size=1):
return results return results
def store_data(db_name, result_list): def store_data(result_list):
db.connect() db.connect()
db.create_tables([WeatherStation, Result])
if not db.table_exists(WeatherStation):
db.create_tables([WeatherStation, Result])
for result in result_list: for result in result_list:
if WeatherStation.select().where(WeatherStation.id == result.location).exists(): if WeatherStation.select().where(WeatherStation.id == result.station_info['location']).exists():
print("Data for station %s already in database. Skipping." % result.station_info.location) print("Data for station %s already in database. Skipping." % result.station_info.location)
continue continue
station = WeatherStation.create( station = WeatherStation.create(
longitude=result.station_info.lon, longitude=result.station_info['lon'],
latitude=result.station_info.lat, latitude=result.station_info['lat'],
location=result.station_info.location, location=result.station_info['location'],
elevation=result.station_info.elevation, elevation=result.station_info['elev'],
city=result.station_info.city, city=result.station_info['city'],
state=result.station_info.state, state=result.station_info['state'],
id=result.station_info.location, id=result.station_info['location'],
) )
Result.create( Result.create(
station=station, station=station,
dc_output=result.outputs.dc, dc_output=result.outputs['dc'],
temperature=result.outputs.tamb, temperature=result.outputs['tamb'],
wind_speed=result.outputs.wspd wind_speed=result.outputs['wspd']
) )