sql_api.py

This commit is contained in:
Lasse Studion 2022-12-18 10:51:55 +01:00
parent 4741dde6f4
commit 114413b3aa
2 changed files with 24 additions and 3 deletions

4
.gitignore vendored
View File

@ -8,9 +8,7 @@
!Makefile !Makefile
!README.md !README.md
!requirements.txt !requirements.txt
!sql_api.py.py !sql_api.py
!/tmp/
/tmp/*
!twitter_api.py !twitter_api.py
!twitter_stream_answers.py !twitter_stream_answers.py
!twitterbot.py !twitterbot.py

23
sql_api.py Normal file
View File

@ -0,0 +1,23 @@
import os
import sqlite3
class DB:
def __init__(self, db_file='db.sqlite3', tables={'usernames': 't_username TEXT PRIMARY KEY, m_username TEXT', 'queue': 't_username TEXT PRIMARY KEY, tweet_id INTEGER, timestamp INTEGER'}):
self.database = sqlite3.connect(f"{os.path.dirname(os.path.realpath(__file__))}/{db_file}")
self.cursor = self.database.cursor()
for table, structure in tables.items():
self.cursor.execute(f'CREATE TABLE IF NOT EXISTS {table}({structure})')
def select(self, sql):
"""Returns a list of dicts from DB."""
self.database.row_factory = sqlite3.Row
things = self.database.execute(sql).fetchall()
unpacked = [{k: item[k] for k in item.keys()} for item in things]
return unpacked
def commit(self, sql):
""" Inserts from a query. """
self.cursor.execute(sql)
self.database.commit()