Skip to content

Commit

Permalink
Merge pull request #221 from Imran-imtiaz48/patch-1
Browse files Browse the repository at this point in the history
Update randomuser-sqlite.py
  • Loading branch information
kennethreitz authored Jul 9, 2024
2 parents ed1e5ad + 0ba5df1 commit 5941ab2
Showing 1 changed file with 22 additions and 21 deletions.
43 changes: 22 additions & 21 deletions examples/randomuser-sqlite.py
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'))

0 comments on commit 5941ab2

Please sign in to comment.