From 6222214a895d8caa76f058a99039802db44abfbf Mon Sep 17 00:00:00 2001 From: Benjamin Sigonneau Date: Sun, 10 Jul 2022 21:07:06 +0200 Subject: [PATCH] Save prices to database (sqlite) --- .gitignore | 2 ++ fioul.py | 18 +++++++++++++++++- models.py | 24 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 models.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa28b5b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.db +__pycache__ diff --git a/fioul.py b/fioul.py index dc9b482..555eeb1 100644 --- a/fioul.py +++ b/fioul.py @@ -1,10 +1,13 @@ #! /usr/bin/env python3 # from bottle import hook, request, route, run, static_file, view + +from datetime import date +from models import Price, IntegrityError + import requests import json - query = """query { getProductGroups(category: 1, zipcode: 1184) { name @@ -28,8 +31,21 @@ def get_price(): return product["default_price_tax"] +def store_current_price(): + today = date.today() + # Get price returns a float (price per L) + # We store an int (price per m^3) + price = int(get_price() * 1000) + try: + Price.create(date=today, price=price) + except IntegrityError: + print("Price for today already in database, not writing") + return price + + def main(): print(get_price()) + store_current_price() if __name__ == "__main__": diff --git a/models.py b/models.py new file mode 100644 index 0000000..44cbd2a --- /dev/null +++ b/models.py @@ -0,0 +1,24 @@ +from peewee import SqliteDatabase +from peewee import Model +from peewee import AutoField, DateField, IntegerField + +from peewee import IntegrityError + +# SQLite database using WAL journal mode and 64MB cache. +db = SqliteDatabase("fioul.db") + + +class BaseModel(Model): + class Meta: + database = db + + +class Price(BaseModel): + id = AutoField() + date = DateField(unique=True) + price = IntegerField() + + +def init(): + db.connect() + db.create_tables([Price])