Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated Dockerfile and my answers to code challenge #47

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

AR20-4
Copy link

@AR20-4 AR20-4 commented Jul 22, 2024

added npm to Dockerfile so the script could run without npm error.

and documented answers to code challenges. Please see below for how I would solve these issues with Javascript because I don't know Python.

Closes #XXX
opened app in docker
Screenshot 2024-07-22 at 2 15 08 PM

got app open and running

Screenshot 2024-07-22 at 2 17 25 PM

Notes

Step 1: Implement the parse method

In parserator_web/views.py, use usaddress to implement the AddressParse.parse() method. It should return two pieces of data:
address_components: The parsed address
address_type: The type of address provided

class AddressParse(APIView):
renderer_classes = [JSONRenderer]

def get(self, request):
    # TODO: Flesh out this method to parse an address string using the
    # parse() method and return the parsed components to the frontend.
    return Response({})


def parse(self, address):
    # TODO: Implement this method to return the parsed components of a
    # given address using usaddress: https://github.com/datamade/usaddress
    return address_components, address_type

*This was a challenge considering I've never used many of these frameworks or platforms. This was my first experience with Docker, Django and I don’t know Python, however, I do know Javascript and how I would code this section using Javascript.

How I would do this with Javascript
To achieve similar functionality in JavaScript on the frontend side, you can use the “fetch” API to make a “GET” request to your Django backend endpoint that parses the address and returns the parsed components as JSON
The JavaScript code will fetch the address parsing results from your Django backend and allow you to handle or display the parsed components and address type in your frontend application. Adjust the endpoint (/api/parse-address) and error handling as necessary to fit your specific frontend and backend setup.
// Assuming you have an input field with id 'addressInput' and a button with id 'parseButton' in your HTML

// Event listener for the button click
document.getElementById('parseButton').addEventListener('click', function() {
// Get the address input value
var address = document.getElementById('addressInput').value;

// Make a GET request to your Django backend
fetch('/api/parse-address?address=' + encodeURIComponent(address))
    .then(function(response) {
        // Check if the response is successful
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        // Parse the JSON response
        return response.json();
    })
    .then(function(data) {
        // Handle the parsed data
        console.log('Parsed components:', data.parsed_components);
        console.log('Address type:', data.address_type);
        // Display or use the parsed components and address type as needed
    })
    .catch(function(error) {
        console.error('There was a problem with the fetch operation:', error);
        // Handle errors here
    });

});

Step 2: Complete the API endpoint

In parserator_web/views.py, complete the AddressParse.get() method to return three pieces of data:
input_string: The string that the user sent
address_components: A dictionary of parsed components that comprise the address, in the format {address_part: tag} (returned by AddressParse.parse())
address_type: A string representing type of the parsed address (returned by AddressParse.parse())
Don't forget to handle strings that cannot be parsed and return errors!

The backend should have an endpoint /api/parse-address that handles GET requests. The endpoint should parse the address using the usaddress library and return a JSON response.

{
"input_string": "123 Main St, Springfield, IL 62701",
"address_components": {
"AddressNumber": "123",
"StreetName": "Main",
"StreetNamePostType": "St",
"PlaceName": "Springfield",
"StateName": "IL",
"ZipCode": "62701"
},
"address_type": "Street Address"
}

Step 3: Wire up the form to send requests to the API

In parserator_web/templates/parserator_web/index.html, fill out the <script> tag in the extra_js block, adding JavaScript code that will use the form to send form data to the API endpoint fleshed out in Step 2.

To add the JavaScript functionality that sends form data to the Django API endpoint (/api/parse-address) and displays the parsed address components on the frontend, you can fill out the <script> tag in the extra_js block with the following code:
{% block extra_js %}

<script> document.addEventListener('DOMContentLoaded', function() { // Event listener for the form submission document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); // Prevent the default form submission // Get the address input value var address = document.getElementById('address').value; // Make a GET request to your Django backend fetch('/api/parse-address?address=' + encodeURIComponent(address)) .then(function(response) { // Check if the response is successful if (!response.ok) { throw new Error('Network response was not ok'); } // Parse the JSON response return response.json(); }) .then(function(data) { // Check if the parsing was successful if (data.error) { throw new Error(data.error); } // Display the parsed results document.getElementById('parse-type').innerText = data.address_type; // Clear previous results var tbody = document.querySelector('tbody'); tbody.innerHTML = ''; // Populate the table with parsed components Object.keys(data.address_components).forEach(function(key) { var tr = document.createElement('tr'); var td1 = document.createElement('td'); var td2 = document.createElement('td'); td1.innerText = key; td2.innerText = data.address_components[key]; tr.appendChild(td1); tr.appendChild(td2); tbody.appendChild(tr); }); // Show the results section document.getElementById('address-results').style.display = 'block'; }) .catch(function(error) { console.error('There was a problem with the fetch operation:', error); // Display or handle errors here }); }); }); </script>

{% endblock %}

Step 4: Display results from the API

In parserator_web/templates/parserator_web/index.html, extend the <script> tag in the extra_js block to display results from the API endpoint in the hidden element

.
Make sure that if the API raises an error, it displays this error to the user.

To extend the <script> tag in the extra_js block to handle displaying results from the API endpoint (/api/parse-address) in the hidden element

and to properly handle errors, you would modify the JavaScript code as follows:
{% block extra_js %}

<script> document.addEventListener('DOMContentLoaded', function() { // Event listener for the form submission document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); // Prevent the default form submission // Get the address input value var address = document.getElementById('address').value; // Make a GET request to your Django backend fetch('/api/parse-address?address=' + encodeURIComponent(address)) .then(function(response) { // Check if the response is successful if (!response.ok) { throw new Error('Network response was not ok'); } // Parse the JSON response return response.json(); }) .then(function(data) { // Check if the parsing was successful if (data.error) { throw new Error(data.error); } // Display the parsed results document.getElementById('parse-type').innerText = data.address_type; // Clear previous results var tbody = document.querySelector('tbody'); tbody.innerHTML = ''; // Populate the table with parsed components Object.keys(data.address_components).forEach(function(key) { var tr = document.createElement('tr'); var td1 = document.createElement('td'); var td2 = document.createElement('td'); td1.innerText = key; td2.innerText = data.address_components[key]; tr.appendChild(td1); tr.appendChild(td2); tbody.appendChild(tr); }); // Show the results section document.getElementById('address-results').style.display = 'block'; }) .catch(function(error) { console.error('There was a problem with the fetch operation:', error); // Display error message to the user var errorElement = document.createElement('p'); errorElement.innerText = 'Error: ' + error.message; errorElement.classList.add('text-danger'); document.getElementById('address-results').innerHTML = ''; // Clear previous results document.getElementById('address-results').appendChild(errorElement); // Show the results section with error message document.getElementById('address-results').style.display = 'block'; }); }); }); </script>

{% endblock %}

added npm to Dockerfile so the script could run without npm error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant