<commit_before>#!/usr/bin/env python3

import urllib.request
import urllib.parse
import urllib.error
from os import path
import settings


class Thingspeak:
    """
    Log data to the thingspeak channel.
    """

    def __init__(self):
        script_dir = path.dirname(path.abspath(__file__))
        key_path = path.join(script_dir, 'thingspeak_key.txt')

        with open(key_path) as f:
            self.key = f.read().strip()

    def append(self, data):
        values = {
            'api_key': self.key
        }

        assert len(data) == len(settings.DATA_SPEC)
        count = 1
        for k in settings.DATA_SPEC:
            if k != 'date':  # skip the date field
                values['field' + str(count)] = data[k]
                count += 1

        url = 'https://api.thingspeak.com/update'
        postdata = urllib.parse.urlencode(values).encode('ascii')
        req = urllib.request.Request(url, postdata)

        try:
            response = urllib.request.urlopen(req)
            html_string = response.read()
            response.close()
        except urllib.error.HTTPError as e:
            print('Server could not fulfill the request: ' + e.code)
        except urllib.error.URLError as e:
            print('Failed to reach server: ' + e.reason)
        except Exception as e:
            print('Unknown error: ' + str(e))


def main():
    t = Thingspeak()
    t.append({'date': None, 'temperature_C': 25, 'pH': 6.0, 'volume_L': 250, 'nutrients_mL': 0})


if __name__ == "__main__":
    main()<commit_msg>thingspeak: log date and check responce value<commit_after>#!/usr/bin/env python3

import urllib.request
import urllib.parse
import urllib.error
from os import path
from datetime import datetime
import settings


class Thingspeak:
    """
    Log data to the Thingspeak channel.
    """

    def __init__(self):
        script_dir = path.dirname(path.abspath(__file__))
        key_path = path.join(script_dir, 'thingspeak_key.txt')

        with open(key_path) as f:
            self.key = f.read().strip()

    def append(self, data):
        if len(data) != len(settings.DATA_SPEC):
            raise Exception('Invalid data fields count')

        values = {
            'api_key': self.key,
            'created_at': data['date']
        }

        count = 1
        for k in settings.DATA_SPEC:
            if k != 'date':
                values['field' + str(count)] = data[k]
                count += 1

        url = 'https://api.thingspeak.com/update'
        postdata = urllib.parse.urlencode(values).encode('ascii')
        req = urllib.request.Request(url, postdata)

        try:
            response = urllib.request.urlopen(req)
            response_data = response.read()
            response.close()
            if response_data == b'0':
                raise Exception('Update failed')
        except urllib.error.HTTPError as e:
            print('Server could not fulfill the request: ' + e.code)
        except urllib.error.URLError as e:
            print('Failed to reach server: ' + e.reason)


def main():
    t = Thingspeak()
    date = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
    t.append({'date': date, 'temperature_C': 25, 'pH': 6.0, 'volume_L': 250, 'nutrients_mL': 0})


if __name__ == "__main__":
    main()
{'fraction_non_alphanumeric': 0.12636695018226002, 'fraction_numerical': 0.0069866342648845685, 'mean_word_length': 2.172447013487476, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4066328', 'n_tokens_mistral': 1079, 'n_tokens_neox': 1004, 'n_words': 253}