Comments Here you can comment about my website and I can use the feedback to further improve my website
Intro Requests
Purpose of Striverr
- Purpose: Empowering growth, celebrating achievements, connecting journeys, inspiring brighter futures
- Features:
- User Profiles:
- Showcase achievements, highlighting progress and milestones.
- Anonymous Chat:
- Connect with the Gemini chatbot, which responds based on the user’s mood.
- Hobbies:
- Track and share interests to encourage exploration of new passions and creative pursuits.
- Step Tracker:
- Monitor physical activity and work toward fitness goals.
- Bucket List:
- Set and document aspirations, inspiring accountability for pursuing dreams.
- Quotes:
- Collect motivational quotes to uplift users and encourage focus on their journey.
- User Profiles:
Purpose of Individual Feature(Step Tracker)
Users can input their daily steps and receive motivational messages based on the number of steps entered. This feature helps users stay healthy and motivated. Users can create, update, read, and delete their daily step entries.
List Requests
Formatting JSON to DOM
async function fetchLastSteps() {
try {
const response = await fetch('http://127.0.0.1:8887/api/steps', {
method: 'GET',
credentials: 'include', // Ensure JWT cookie is sent with the request
});
if (response.ok) {
const data = await response.json();
const stepCount = data.steps.steps; // Accessing the steps property in the nested object
document.getElementById('steps-display').innerText = stepCount; // Updating the DOM
displayMotivationMessage(stepCount); // Display motivational message
} else {
document.getElementById('steps-display').innerText = 'Error fetching steps'; // Error message in DOM
}
} catch (error) {
document.getElementById('steps-display').innerText = 'Error fetching steps'; // Error message in DOM
}
}
function displayMotivationMessage(steps) {
const messageElement = document.getElementById('motivation-message');
if (steps >= 6000) {
messageElement.innerText = 'Great Job!';
} else if (steps >= 4000) {
messageElement.innerText = 'Good job!';
} else {
messageElement.innerText = 'Lock in!';
}
}
- Fetches step data from the API.
- Parses the JSON response.
- Updates specific DOM elements (steps-display and motivation-message) with relevant data.
- Provides user feedback dynamically based on the fetched data.
Lists and Dictionaries in the database
- Lists are used to reperesnt rows in the database
- Dictionaries are used to represent columns of data
with app.app_context():
"""Create database and tables"""
db.create_all()
"""Tester data for table"""
tester_data = [
Steps(user='user1', steps=5000),
Steps(user='user2', steps=7500),
Steps(user='user3', steps=12000)
]
for data in tester_data:
try:
db.session.add(data)
db.session.commit()
print(f"Record created: {repr(data)}")
Using Third-Party Libraries
Query Execution
Steps.query
is a query object created by SQLAlchemy for theSteps
model.- The
.filter_by()
method applies a filter condition (e.g.,user=current_user.uid
) to narrow down the results. - The
.first()
method retrieves the first matching row from the database as a Python object.
Code Line
steps_entries = Steps.query.filter_by(user=current_user.uid).all()
Crud Operations
def create(self):
"""
The create method adds the object to the database and commits the transaction.
Uses:
The db ORM methods to add and commit the transaction.
Raises:
Exception: An error occurred when adding the object to the database.
"""
try:
db.session.add(self)
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
def delete(self):
"""
Deletes the chat message from the database.
"""
try:
db.session.delete(self)
db.session.commit()
except Exception as e:
db.session.rollback()
raise e
def read(self):
"""
The read method retrieves the object data from the object's attributes and returns it as a dictionary.
Returns:
dict: A dictionary containing the steps data.
"""
return {
'id': self.id,
'user': self.user,
'steps': self.steps
}
Algorithmic code request
API GET,POST,PUT,DELETE Methods
@token_required()
def post(self):
"""
Add a new steps entry for the authenticated user.
"""
current_user = g.current_user
body = request.get_json()
# Validate steps
steps = body.get('steps')
if steps is None or not isinstance(steps, int) or steps < 0:
return {'message': 'Invalid steps provided'}, 400
try:
# Ensure no existing entry exists
existing_steps = Steps.query.filter_by(user=current_user.uid).first()
if existing_steps:
return {'message': 'Steps entry already exists'}, 400
# Create a new steps entry
new_steps = Steps(user=current_user.uid, steps=steps)
new_steps.create()
return jsonify({'message': 'Steps added successfully', 'steps': new_steps.read()})
except Exception as e:
return {'message': 'Failed to create steps', 'error': str(e)}, 500
@token_required()
def put(self):
"""
Update an existing steps entry for the authenticated user.
"""
current_user = g.current_user
body = request.get_json()
# Validate steps
steps = body.get('steps')
if steps is None or not isinstance(steps, int) or steps < 0:
return {'message': 'Invalid steps provided'}, 400
try:
# Fetch and update the user's steps entry
steps_entry = Steps.query.filter_by(user=current_user.uid).first()
if not steps_entry:
return {'message': 'No steps entry found to update'}, 404
steps_entry.steps = steps
steps_entry.create() # Save changes to the database
return jsonify({'message': 'Steps updated successfully', 'steps': steps_entry.read()})
except Exception as e:
return {'message': 'Failed to update steps', 'error': str(e)}, 500
@token_required()
def get(self):
"""
Get the current user's steps entry.
"""
current_user = g.current_user
try:
steps_entry = Steps.query.filter_by(user=current_user.uid).first()
if steps_entry:
return jsonify({'message': 'Steps retrieved successfully', 'steps': steps_entry.read()})
else:
return {'message': 'No steps entry found for the user'}, 404
except Exception as e:
return {'message': 'Failed to retrieve steps', 'error': str(e)}, 500
@token_required()
def delete(self):
"""
Delete an existing steps entry for the authenticated user.
"""
current_user = g.current_user
try:
# Fetch and delete the user's steps entry
steps_entry = Steps.query.filter_by(user=current_user.uid).first()
if not steps_entry:
return {'message': 'No steps entry found to delete'}, 404
steps_entry.delete() # Delete the entry from the database
return jsonify({'message': 'Steps entry deleted successfully'})
except Exception as e:
return {'message': 'Failed to delete steps entry', 'error': str(e)}, 500
Method Contaitning Sequencing, Selection, and Iteration
@token_required()
def post(self):
"""
Add a new steps entry for the authenticated user.
"""
current_user = g.current_user
body = request.get_json()
# Validate steps
steps = body.get('steps')
if steps is None or not isinstance(steps, int) or steps < 0:
return {'message': 'Invalid steps provided'}, 400 # **Selection**: If steps are invalid, return error
try:
# Ensure no existing entry exists
existing_steps = Steps.query.filter_by(user=current_user.uid).first() # **Iteration**: Iterates through database to find existing steps entry
if existing_steps:
return {'message': 'Steps entry already exists'}, 400 # **Selection**: If an entry exists, return error
# Create a new steps entry
new_steps = Steps(user=current_user.uid, steps=steps)
new_steps.create() # **Sequencing**: After validation, create a new entry in the database
return jsonify({'message': 'Steps added successfully', 'steps': new_steps.read()}) # **Sequencing**: Return success response
except Exception as e:
return {'message': 'Failed to create steps', 'error': str(e)}, 500 # **Sequencing**: Handle exceptions
The function returns a JSON response using jsonify, which contains a message and, in the case of success, the newly created steps entry. Incase of errors, the function would return a different JSON response such as 'message': 'Steps entry already exists'
Call to Algorithm request
These functions use the fetch API to send HTTP requests to the backend, and the request method and body are specified depending on the action being performed. One specicfic function is:
async function fetchLastSteps() {
try {
const response = await fetch('http://127.0.0.1:8887/api/steps', {
method: 'GET',
credentials: 'include', // Ensure JWT cookie is sent with the request
});
if (response.ok) {
const data = await response.json();
const stepCount = data.steps.steps; // Accessing the steps property in the nested object
document.getElementById('steps-display').innerText = stepCount;
displayMotivationMessage(stepCount);
} else {
document.getElementById('steps-display').innerText = 'Error fetching steps';
}
} catch (error) {
document.getElementById('steps-display').innerText = 'Error fetching steps';
}
}
- HTTP Method: GET
- Endpoint: /api/steps
- Request: The function sends a GET request to the endpoint with the credentials: ‘include’ option, ensuring the JWT token (stored as a cookie) is sent with the request to authenticate the user. On success, the UI is updated with the steps count and a motivational message.
- If no data exists (e.g., the user has not recorded any steps yet), the server will return an error message.
{ "message": "No steps entry found for the user" }