Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Database the easy way (dataset)
#1
dataset for a quick way to way to storage data.
It also has a lot out of power underneath,as is build of top SQLAlchemy.
Can also exported from a database to eg JSON,CSV.

Some ip-addresses to a SQlite database.
import dataset

data = '''\
91.105.0.0/17
46.109.0.0/16
194.8.16.0/21
194.8.24.0/22
194.8.40.0/23
194.8.43.0/24
195.122.0.0/19'''

db = dataset.connect('sqlite:///ip_range.db')
table = db['ip_range']
for ip in data.split('\n'):
    ip_in = dict(ip=ip)
    table.insert(ip_in)
Test it out.
>>> [ip for ip in db['ip_range']][1:4]
[OrderedDict([('id', 2), ('ip', '46.109.0.0/16')]),
 OrderedDict([('id', 3), ('ip', '194.8.16.0/21')]),
 OrderedDict([('id', 4), ('ip', '194.8.24.0/22')])]
>>> [ip['ip'] for ip in db['ip_range']][1:4]
['46.109.0.0/16', '194.8.16.0/21', '194.8.24.0/22']

>>> table.find_one(id='2')
OrderedDict([('id', 2), ('ip', '46.109.0.0/16')])
>>> table.find_one(id='2').get('ip')
'46.109.0.0/16'

>>> print(db['ip_range'].columns)
['id', 'ip']
>>> print(len(db['ip_range']))
7
As is it a database it also has SQL queries
>>> [ip for ip in db.query("select * from ip_range order by rowid asc limit 3")]
[OrderedDict([('id', 1), ('ip', '91.105.0.0/17')]),
 OrderedDict([('id', 2), ('ip', '46.109.0.0/16')]),
 OrderedDict([('id', 3), ('ip', '194.8.16.0/21')])]
>>> [ip for ip in db.query("select * from ip_range order by rowid desc limit 3")]
[OrderedDict([('id', 7), ('ip', '195.122.0.0/19')]),
 OrderedDict([('id', 6), ('ip', '194.8.43.0/24')]),
 OrderedDict([('id', 5), ('ip', '194.8.40.0/23')])]

New set of data.
import dataset

player_lst = [
    {'name': 'Superman', 'score': 9999999},
    {'name': 'Hulk', 'score': 2000001},
    {'name': 'Batman', 'score': 500055}
    ]

db = dataset.connect('sqlite:///heroes.db')
table = db['Score_table']
for item in player_lst:
    table.insert(item)
Use it.
print('{} had a score of {}'.format(table.find_one(name='Superman')['name'],\
                                    table.find_one(name='Superman')['score']))
#--> Superman had a score of 9999999


#Highest Score SQL.
>>> [i for i in db.query("SELECT MAX(score) FROM Score_table")]
[OrderedDict([('MAX(score)', 9999999)])]
>>> [i for i in db.query("SELECT MAX(score) FROM Score_table")][0]['MAX(score)']
9999999
Freeze to JSON :cool: 
#Make
result = db['Score_table'].all()
dataset.freeze(result, format='json', filename='Score_table.json')

#Load
import json

with open("Score_table.json") as j:
    score_table = json.load(j)

#Test
>>> score_table
{'count': 3,
 'meta': {},
 'results': [{'id': 1, 'name': 'Superman', 'score': 9999999},
             {'id': 2, 'name': 'Hulk', 'score': 2000001},
             {'id': 3, 'name': 'Batman', 'score': 500055}]}
#2
-

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)