Skip to content

Commit

Permalink
using new deno & kv api backend
Browse files Browse the repository at this point in the history
  • Loading branch information
aaronhmiller committed Jul 22, 2024
1 parent ccd60ab commit c2ad5c3
Show file tree
Hide file tree
Showing 7 changed files with 284 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ It told me to install Flask (Python framework) and gave me app.py & index.html &

1. Fire up the crud-app docker compose stack, from its directory, `docker compose up -d`
2. from this project's directory, run `python3 app.py`
3. in your browser, open the page: [http://localhost:8000](http:localhost:8000)
3. in your browser, open the page: [http://localhost:8080](http:localhost:8080)
4. you should see the inital data, and be able to create, update or delete any of the records

## Misconceptions
Expand Down
81 changes: 81 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ def update():
def create():
return render_template('add.html')

@app.route('/update-address')
def update_address():
return render_template('update-address.html')

@app.route('/add-address')
def create_address():
return render_template('add-address.html')

@app.route('/delete')
def delete():
return render_template('delete.html')
Expand All @@ -37,6 +45,17 @@ def get_data():
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to fetch data from API'}), response.status_code

@app.route('/users/<int:data_id>/address', methods=['GET'])
def get_address(data_id):
api_url = f'https://api.demojoyto.win/users/{data_id}/address'
response = requests.get(api_url)
if response.status_code == 200:
return response.json()
else:
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to fetch data from API'}), response.status_code


# Define the route for updating data
@app.route('/users/<int:data_id>', methods=['PUT'])
def update_data(data_id):
Expand All @@ -57,6 +76,26 @@ def update_data(data_id):
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to update user data'}), response.status_code

# Define another route for updating data
@app.route('/users', methods=['PUT'])
def update_data2():

# URL of the RESTful API endpoint for creating a new user
api_url = 'https://api.demojoyto.win/users'

# Extract the data to be created from the incoming request
user_data = request.json

# Make a PUT request to the RESTful API
response = requests.put(api_url, json=user_data)

# Check if the request was successful
if response.status_code == 201:
# Return the created user data response
return response.text
else:
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to update user'}), response.status_code

# Define the route for creating data
@app.route('/users', methods=['POST'])
Expand All @@ -79,6 +118,48 @@ def create_data():
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to create new user'}), response.status_code

# Define the route for creating address data
@app.route('/users/<int:data_id>/address', methods=['POST'])
def create_address_data(data_id):

# URL of the RESTful API endpoint for creating a new user
api_url = f'https://api.demojoyto.win/users/{data_id}/address'

# Extract the data to be created from the incoming request
address_data = request.json

# Make a POST request to the RESTful API
response = requests.post(api_url, json=address_data)

# Check if the request was successful
if response.status_code == 201:
# Return the created address data response
return response.text
else:
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to create new address'}), response.status_code

# Define the route for updating address data
@app.route('/users/<int:data_id>/address', methods=['PUT'])
def update_address_data(data_id):

# URL of the RESTful API endpoint for creating a new user
api_url = f'https://api.demojoyto.win/users/{data_id}/address'

# Extract the data to be created from the incoming request
address_data = request.json

# Make a PUT request to the RESTful API
response = requests.put(api_url, json=address_data)

# Check if the request was successful
if response.status_code == 204:
# Return the created address data response
return response.text
else:
# Handle errors or unsuccessful responses
return jsonify({'error': 'Failed to update address'}), response.status_code

# Define the route for deleting data
@app.route('/users/<int:data_id>', methods=['DELETE'])
def delete_data(data_id):
Expand Down
92 changes: 92 additions & 0 deletions templates/add-address.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update Address Record with REST API</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<h1>Address Data from API</h1>
<div id="data-container"></div>

<h2>Update Address Data</h2>
<form id="insert-form">
<label for="id">Id:</label>
<input type="text" id="id" name="id">
<label for="city">City:</label>
<input type="text" id="city" name="city">
<label for="street">Street:</label>
<input type="text" id="street" name="street">
<input type="submit" value="Submit">
</form>

<h4><a href="add">Add Data</a></h4>
<h4><a href="update">Update Data</a></h4>
<h4><a href="update-address">Add Address</a></h4>
<h4><a href="delete">Delete Data</a></h4>

<script>

// Fetch data from the API and update the UI
function fetchData() {
fetch('/users')
.then(response => response.json())
.then(data => {
const container = document.getElementById('data-container');
container.innerHTML = ''; // Clear previous data

data.forEach(item => {
const userList = document.createElement('div');
const id = item.id;
const addressList = document.createElement('ul');
fetch(`/users/${id}/address`)
.then(response2 => response2.json())
.then(data2 => {
addressList.textContent = JSON.stringify(data2);
});
userList.textContent = JSON.stringify(item);
container.appendChild(userList);
container.appendChild(addressList);
});
})
.catch(error => console.error('Error fetching data:', error));
}

// Handle new data insertion form submission
document.getElementById('insert-form').addEventListener('submit', function(event) {
event.preventDefault();

const form = event.target;
const formData = new FormData(form);
const formDataObject = {};
let userId = formData.get('id'); // Get the user id from the form data
formData.forEach((key, value) => {
if (value !== 'id') {
formDataObject[value] = key;
}
});

// Send POST request to insert new data
fetch(`/users/${userId}/address`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formDataObject)
})
.then(response => response.text())
.then(data => {
console.log('Data inserted:', data);
fetchData(); //refresh after adding
form.reset(); //reset form fields to default values
document.getElementById('name').focus(); //move focus to the first input field of the form
})
.catch(error => console.error('Error inserting data:', error));
});

// Initial data fetch
fetchData();
</script>
</body>
</html>
8 changes: 7 additions & 1 deletion templates/add.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,20 @@ <h1>Data from API</h1>

<h2>Add Data</h2>
<form id="insert-form">
<label for="name">Id:</label>
<input type="text" id="id" name="id">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<label for="password">Password:</label>
<input type="text" id="password" name="password">
<input type="submit" value="Submit">
</form>

<h4><a href="update">Update Data</a></h4>
<h4><a href="update-address">Update Address</a></h4>
<h4><a href="add-address">Add Address</a></h4>
<h4><a href="delete">Delete Data</a></h4>

<script>
Expand Down Expand Up @@ -65,7 +71,7 @@ <h4><a href="delete">Delete Data</a></h4>
console.log('Data inserted:', data);
fetchData(); //refresh after adding
form.reset(); //reset form fields to default values
document.getElementById('name').focus(); //move focus to the first input field of the form
document.getElementById('id').focus(); //move focus to the first input field of the form
})
.catch(error => console.error('Error inserting data:', error));
});
Expand Down
4 changes: 3 additions & 1 deletion templates/delete.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ <h1>Data from API</h1>
<h2>Delete Data</h2>
<div id="delete-buttons-container"></div>
<h4><a href="add">Add Data</a></h4>
<h4><a href="add-address">Add Address Data</a></h4>
<h4><a href="update">Update Data</a></h4>
<h4><a href="update-address">Update Address Data</a></h4>
<script>
// Function to populate form fields with data
function populateForm(data) {
Expand Down Expand Up @@ -94,4 +96,4 @@ <h4><a href="update">Update Data</a></h4>
fetchData();
</script>
</body>
</html>
</html>
92 changes: 92 additions & 0 deletions templates/update-address.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Update Address Record with REST API</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<h1>Address Data from API</h1>
<div id="data-container"></div>

<h2>Update Address Data</h2>
<form id="insert-form">
<label for="id">Id:</label>
<input type="text" id="id" name="id">
<label for="city">City:</label>
<input type="text" id="city" name="city">
<label for="street">Street:</label>
<input type="text" id="street" name="street">
<input type="submit" value="Submit">
</form>

<h4><a href="add">Add Data</a></h4>
<h4><a href="update">Update Data</a></h4>
<h4><a href="update-address">Add Address</a></h4>
<h4><a href="delete">Delete Data</a></h4>

<script>

// Fetch data from the API and update the UI
function fetchData() {
fetch('/users')
.then(response => response.json())
.then(data => {
const container = document.getElementById('data-container');
container.innerHTML = ''; // Clear previous data

data.forEach(item => {
const userList = document.createElement('div');
const id = item.id;
const addressList = document.createElement('ul');
fetch(`/users/${id}/address`)
.then(response2 => response2.json())
.then(data2 => {
addressList.textContent = JSON.stringify(data2);
});
userList.textContent = JSON.stringify(item);
container.appendChild(userList);
container.appendChild(addressList);
});
})
.catch(error => console.error('Error fetching data:', error));
}

// Handle new data insertion form submission
document.getElementById('insert-form').addEventListener('submit', function(event) {
event.preventDefault();

const form = event.target;
const formData = new FormData(form);
const formDataObject = {};
let userId = formData.get('id'); // Get the user id from the form data
formData.forEach((key, value) => {
if (value !== 'id') {
formDataObject[value] = key;
}
});

// Send POST request to insert new data
fetch(`/users/${userId}/address`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formDataObject)
})
.then(response => response.text())
.then(data => {
console.log('Data inserted:', data);
fetchData(); //refresh after adding
form.reset(); //reset form fields to default values
document.getElementById('name').focus(); //move focus to the first input field of the form
})
.catch(error => console.error('Error inserting data:', error));
});

// Initial data fetch
fetchData();
</script>
</body>
</html>
9 changes: 8 additions & 1 deletion templates/update.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,15 @@ <h2>Update Data</h2>
<label for="edit-email">Email:</label>
<input type="text" id="edit-email" name="edit-email" required>

<label for="edit-password">Password:</label>
<input type="text" id="edit-password" name="edit-password" required>

<button type="button" onclick="editData()">Submit</button>
</form>

<h4><a href="add">Add Data</a></h4>
<h4><a href="add-address">Add Address Data</a></h4>
<h4><a href="update-address">Update Address Data</a></h4>
<h4><a href="delete">Delete Data</a></h4>


Expand All @@ -55,8 +60,9 @@ <h4><a href="delete">Delete Data</a></h4>
const id = document.getElementById('edit-id').value;
const name = document.getElementById('edit-name').value;
const email = document.getElementById('edit-email').value;
const password = document.getElementById('edit-password').value;

fetch('/users/' + id, {
fetch('/users', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Expand All @@ -65,6 +71,7 @@ <h4><a href="delete">Delete Data</a></h4>
id: id,
name: name,
email: email,
password: password,
}),
})
.then(response => response.text())
Expand Down

0 comments on commit c2ad5c3

Please sign in to comment.