91 lines
2.0 KiB
Python
91 lines
2.0 KiB
Python
#! /usr/bin/env python3
|
|
|
|
# from bottle import hook, request, route, run, static_file, view
|
|
|
|
from argparse import ArgumentParser
|
|
from datetime import date
|
|
from models import Price, IntegrityError
|
|
|
|
|
|
import requests
|
|
import json
|
|
|
|
query = """query {
|
|
getProductGroups(category: 1, zipcode: 1184) {
|
|
name
|
|
default_price_tax
|
|
}
|
|
}
|
|
"""
|
|
|
|
|
|
def get_price():
|
|
response = requests.post(
|
|
url="https://www.bretagne-multi-energies.fr/graphql",
|
|
json={"query": query},
|
|
headers={"content-type": "application/json"},
|
|
)
|
|
json_data = json.loads(response.text)
|
|
products = json_data["data"]["getProductGroups"]
|
|
product = next(
|
|
filter(lambda x: x["name"] == "Fioul Domestique Standard", products), None
|
|
)
|
|
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
|
|
|
|
|
|
# ----------------------------------------------------------------------
|
|
# Argument parsing
|
|
# use a decorator to simplify argparse usage, as suggested by
|
|
# https://mike.depalatis.net/blog/simplifying-argparse.html
|
|
|
|
cli = ArgumentParser(description="Balises")
|
|
subparsers = cli.add_subparsers(dest="subcommand")
|
|
|
|
|
|
def subcommand(args=[], parent=subparsers):
|
|
def decorator(func):
|
|
parser = parent.add_parser(func.__name__, description=func.__doc__)
|
|
for arg in args:
|
|
parser.add_argument(*arg[0], **arg[1])
|
|
parser.set_defaults(func=func)
|
|
|
|
return decorator
|
|
|
|
|
|
@subcommand()
|
|
def update(args):
|
|
store_current_price()
|
|
|
|
|
|
@subcommand()
|
|
def show(args):
|
|
print(get_price())
|
|
|
|
|
|
# ----------------------------------------------------------------------
|
|
# Main
|
|
|
|
|
|
def main():
|
|
args = cli.parse_args()
|
|
if args.subcommand is None:
|
|
cli.print_help()
|
|
else:
|
|
args.func(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|