11#!/usr/bin/env python3
22"""
33Test example to take a ping and save it into an sqlite3 database
4+ https://docs.python.org/3/library/sqlite3.html
45"""
5-
6+ # pip install requests
67import requests
7- import time
88import sqlite3
9+ import time
910import sys
1011
12+ # Get argument if there is one and use that as url
1113if len (sys .argv ) == 2 :
1214 url = sys .argv [1 ]
1315else :
1416 url = "http://dbwebb.se/"
1517
18+ # connect to the database and set a cursor
1619conn = sqlite3 .connect ("ping.sqlite3" )
1720cur = conn .cursor ()
1821
19- # init
20- # cur.execute("DROP TABLE IF EXISTS Pings")
21- # cur.execute("CREATE TABLE Pings (url TEXT, time TEXT PRIMARY KEY, repsonse INTEGER)")
22+ # init database incase it's lost
23+ cur .execute ("""
24+ CREATE TABLE IF NOT EXISTS Pings
25+ (url TEXT, time TEXT PRIMARY KEY, repsonse INTEGER)""" )
2226
27+ # get current time for logging
2328rTime = time .ctime (time .time ())
2429
2530try :
26- # url must start with "http://"
31+ # url must start with "http://" or the request fails
2732 r = requests .head (url )
2833 code = r .status_code
2934except requests .ConnectionError :
3035 code = 0
3136
37+ # create the values to be added as tuple
3238values = (url , rTime , code )
33- cur .execute ("INSERT INTO Pings (url, time, repsonse) VALUES (?, ?, ?)" , values )
39+ # insert values into database
40+ cur .execute ("""
41+ INSERT INTO Pings (url, time, repsonse)
42+ VALUES (?, ?, ?)
43+ """ , values )
3444
3545print ("Rows in db:" )
46+ # get all the rows in database
3647cur .execute ("SELECT url, time, repsonse FROM Pings" )
48+ # loop through the result
3749for row in cur :
3850 print (row )
3951
40-
52+ # commit the changes and close the connection
4153conn .commit ()
4254conn .close ()
0 commit comments