How I Used Lists, Dictionaries, and Databases for My Website!
Using Lists, Dictionaries, and Databases
For my project, I worked extensively with lists to store multiple objects, dictionaries to format my data, and a database (SQLAlchemy) to persistently store information.
In my database, each user is represented as a dictionary with keys corresponding to column names. I retrieve multiple users as a list of dictionaries.
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all() # Fetch all users from DB
return jsonify([user.to_dict() for user in users])
Formatting JSON Data from API into the DOM
I needed to display data from my API on my website. The API returned JSON, which I parsed using JavaScript and updated the DOM.
fetch('/users')
.then(response => response.json())
.then(data => {
data.forEach(user => {
const div = document.createElement('div');
div.textContent = `${user.name} (${user.email})`;
document.body.appendChild(div);
});
});
Extracting a Python List from a Database
I used SQLAlchemy to extract multiple rows from my database. These queries are handled by SQLAlchemy, a third-party ORM.
users = User.query.all()
users_list = [user.to_dict() for user in users]
CRUD Operations with a Class
I created a class with methods to create, read, update, and delete users.
class UserService:
@staticmethod
def create_user(name, email):
user = User(name=name, email=email)
db.session.add(user)
db.session.commit()
return user.to_dict()
@staticmethod
def update_user(user_id, name, email):
user = User.query.get(user_id)
if user:
user.name = name
user.email = email
db.session.commit()
return user.to_dict()
return None
@staticmethod
def delete_user(user_id):
user = User.query.get(user_id)
if user:
db.session.delete(user)
db.session.commit()
return True
return False
Defining an API Class with GET, POST, PUT, and DELETE Methods
I used Flask-RESTful to manage API endpoints for my user model.
class UserAPI(Resource):
def get(self, user_id):
user = User.query.get(user_id)
return jsonify(user.to_dict()) if user else {"error": "User not found"}
def post(self):
data = request.json
user = User(name=data["name"], email=data["email"])
db.session.add(user)
db.session.commit()
return jsonify(user.to_dict()), 201
def put(self, user_id):
data = request.json
user = User.query.get(user_id)
if user:
user.name = data["name"]
user.email = data["email"]
db.session.commit()
return jsonify(user.to_dict())
return {"error": "User not found"}, 404
def delete(self, user_id):
user = User.query.get(user_id)
if user:
db.session.delete(user)
db.session.commit()
return '', 204
return {"error": "User not found"}, 404
A Method Using Sequencing, Selection, and Iteration
I created a function that loops through users, checks a condition, and processes data.
def process_users():
users = User.query.all() # Sequencing (fetch users)
for user in users: # Iteration (looping)
if "@" not in user.email: # Selection (condition)
print(f"Invalid email for {user.name}")
Handling Request Parameters and JSON Responses
I implemented an endpoint that accepts a request body and returns a JSON response.
@app.route('/add_user', methods=['POST'])
def add_user():
data = request.json # Body of request
new_user = User(name=data['name'], email=data['email'])
db.session.add(new_user)
db.session.commit()
return jsonify(new_user.to_dict()), 201 # JSON response
Fetching Data from API (Calling an Algorithm)
I used JavaScript’s fetch
function to call my API and handle the response.
fetch('/user/1')
.then(response => response.json())
.then(user => console.log(user))
.catch(error => console.error('Error:', error));
Handling API Response in the Frontend
I implemented error handling for failed requests.
fetch('/user/1')
.then(response => response.json())
.then(user => {
if (user.error) {
alert(user.error);
} else {
console.log(user.name);
}
});
Handling Normal and Error Conditions
I wrote backend code that handles both normal and error conditions when retrieving a user.
@app.route('/get_user/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = User.query.get(user_id)
if user:
return jsonify(user.to_dict()) # Normal response
return jsonify({"error": "User not found"}), 404 # Error response
On the frontend, if a request fails, I handle it gracefully:
fetch('/get_user/999') // Non-existent user
.then(response => response.json())
.then(data => {
if (data.error) console.error(data.error);
});
This blog outlines how I integrated lists, dictionaries, and databases with APIs to build dynamic functionality for my website.