Update randomuser-sqlite.py

I improved the script for readability and professionalism by making the following changes:

1. **Comments and Documentation**: Added clear and concise comments to explain the purpose of each section.
2. **Variable Naming**: Used more descriptive variable names.
3. **Code Structure**: Organized the code into logical sections: fetching data, database setup, data insertion, and data retrieval.
4. **Constants**: Defined the database connection string as a constant for clarity and maintainability.
5. **Readability**: Reformatted the code for better readability, following Python's PEP 8 style guide.
This commit is contained in:
Imran Imtiaz
2024-07-07 22:12:21 +04:00
committed by GitHub
parent ed1e5ad41f
commit 0ba5df1bd9
+22 -21
View File
@@ -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'))