-
-
Notifications
You must be signed in to change notification settings - Fork 572
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #221 from Imran-imtiaz48/patch-1
Update randomuser-sqlite.py
- Loading branch information
Showing
1 changed file
with
22 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,35 +1,36 @@ | ||
#!/usr/bin/env python3 | ||
# coding: utf-8 | ||
|
||
import json # https://docs.python.org/3/library/json.html | ||
import requests # https://github.com/kennethreitz/requests | ||
import records # https://github.com/kennethreitz/records | ||
import json | ||
import requests | ||
import records | ||
|
||
# randomuser.me generates random 'user' data (name, email, addr, phone number, etc) | ||
r = requests.get('http://api.randomuser.me/0.6/?nat=us&results=10') | ||
j = r.json()['results'] | ||
# Fetch random user data from randomuser.me API | ||
response = requests.get('http://api.randomuser.me/0.6/?nat=us&results=10') | ||
user_data = response.json()['results'] | ||
|
||
# Valid SQLite URL forms are: | ||
# sqlite:///:memory: (or, sqlite://) | ||
# sqlite:///relative/path/to/file.db | ||
# sqlite:////absolute/path/to/file.db | ||
# Database connection string | ||
DATABASE_URL = 'sqlite:///users.db' | ||
|
||
# records will create this db on disk if 'users.db' doesn't exist already | ||
db = records.Database('sqlite:///users.db') | ||
# Initialize the database | ||
db = records.Database(DATABASE_URL) | ||
|
||
# Create the 'persons' table | ||
db.query('DROP TABLE IF EXISTS persons') | ||
db.query('CREATE TABLE persons (key int PRIMARY KEY, fname text, lname text, email text)') | ||
|
||
for rec in j: | ||
user = rec['user'] | ||
name = user['name'] | ||
db.query('CREATE TABLE persons (key INTEGER PRIMARY KEY, fname TEXT, lname TEXT, email TEXT)') | ||
|
||
# Insert user data into the 'persons' table | ||
for record in user_data: | ||
user = record['user'] | ||
key = user['registered'] | ||
fname = name['first'] | ||
lname = name['last'] | ||
fname = user['name']['first'] | ||
lname = user['name']['last'] | ||
email = user['email'] | ||
db.query('INSERT INTO persons (key, fname, lname, email) VALUES(:key, :fname, :lname, :email)', | ||
key=key, fname=fname, lname=lname, email=email) | ||
db.query( | ||
'INSERT INTO persons (key, fname, lname, email) VALUES (:key, :fname, :lname, :email)', | ||
key=key, fname=fname, lname=lname, email=email | ||
) | ||
|
||
# Retrieve and print the contents of the 'persons' table as CSV | ||
rows = db.query('SELECT * FROM persons') | ||
print(rows.export('csv')) |