Simple eCommerce API using Flask

How to Get Started on Flask — # flaskSeries # Episode 00

J3
Jungletronics
10 min readMay 28, 2023

--

Based on: hashtag treinamentos’ mentoring — Thanks Lira!

This is all about Flask! here is it running on Replit!

This app lets You Manage & Scale
Your Business on the cloud;
it allows managers to browse and
calculate store’s gross sales
and search items from an
online store - Outfit.

What is Flask? It is a web framework — a minimalist and lightweight design for building web applications in Python.

We going to open an Outfit store on line. Here is our architecture:

Actual implementation v1- browser — controller — excel components; In the next episode we will migrate the data to SQLite — Colaborate U2 : https://excalidraw.com/#room=dc2574af09de86b8b112,No-CmkqU1NsvjSmltXUx7A

Our interest: A Fashion and Apparel Website.

Outfit is the number one fashion destination, bringing together the best of the high street brands.

Mind Map for choose what is the fashion we are attending in your Outfit store — image from this link

Here is our initial clothing department store inventories:

Download db: (Sales — Dez.xlsx)

Necklines Collections. image from this link
Cotton Collections. image from this link

Let’s get started!

0# Step — Go to Replit, create an account (if not yet:) and paste these codes bellow ( or fork it :); I recommend that you make it works first, them try out the app and only then try to make reason. Python is easy to understand!

What is Replit used for?

Replit being Software as a
service (SaaS) allows users to
create online projects (called
Repls, not to be confused
with REPLs) and write code.

1# Step — load the DB (click snowman on Replit dashboard)

Use Pandas together with Flask lib.

from flask import Flask
import pandas as pd

app = Flask(__name__)
table = pd.read_excel("Sales - Dez.xlsx")

This Flask code performs the following tasks:

  1. Importing the necessary modules: The code imports the Flask module and the Pandas module using the import statements. Flask is used to create the web application, while pandas is a library for data manipulation and analysis.
  2. Creating a Flask application object: The line app = Flask(__name__) creates an instance of the Flask class, which represents the Flask application. The __name__ argument is a special Python variable that gets the name of the current module. It is typically used as a reference point for Flask to locate resources such as templates and static files.
  3. Reading an Excel file: The line table = pd.read_excel("Sales - Dez.xlsx") uses pandas to read an Excel file named "Sales - Dez.xlsx" and load it into a pandas DataFrame called table. The Excel file likely contains sales data, and the read_excel() function parses the contents of the file and creates a DataFrame, which is a tabular data structure.

By executing these lines of code, the Flask application is set up, and the sales data from the Excel file is loaded into a pandas DataFrame. This allows we to use the table DataFrame in your Flask routes and perform operations on the sales data, such as filtering, aggregation, or generating responses based on the data.

2# Step — Define the root route, which returns the total gross sales

@app.route("/")
def gross_sales():
gross_sales = float(table["total of sales"].sum())
return {"gross_sales": gross_sales}

This Flask code defines a route for the root URL (“/”) and creates a function named gross_sales() to handle requests to that route. Here's what it does:

  1. The @app.route("/") decorator specifies that this function should be called when a request is made to the root URL ("/").
  2. Inside the function, the line gross_sales = float(table["total of sales"].sum()) calculates the sum of the "total of sales" column in the table Pandas DataFrame and assigns it to the gross_sales variable. The .sum() method is used to calculate the sum of the column values.
  3. The calculated gross_sales value is returned as a JSON response using the return statement. It is wrapped in a dictionary with the key "gross_sales". The response will have the format {"gross_sales": <value>}, where <value> represents the sum of the sales.

When a request is made to the root URL (“/”), the gross_sales() function will be executed. It calculates the total gross sales from the "total of sales" column in the table DataFrame and returns it as a JSON response. This endpoint can be used to retrieve the gross sales information from the dataset.

3# Step — The /sales/products end point brings all 50 items grouped and summed

@app.route("/sales/products")
def sales_products():
table_prod_sales = table[["products",
"total of sales"]].groupby("products").sum()
sales_products_json = table_prod_sales.to_dict()
return sales_products_json

This code provides an API endpoint that retrieves sales data for all products in a database and returns it as a JSON response. The sales data includes the total sales for each product. This endpoint can be used to fetch the sales data for all products in a convenient JSON format.

Here’s how the code works:

  1. The route is defined using the @app.route() decorator with the URL pattern "/sales/products". This means that the route expects a request to the "/sales/products" URL;
  2. The function sales_products() is executed when a request is made to this route;
  3. Inside the function, a subset of the table is created, containing only the "products" and "total of sales" columns. The .groupby("products").sum() method is used to group the data by product and calculate the sum of sales for each product. We search the table using Pandas Dataframe by passing a list of two fields, products and total of sales; then group them up and take the sum. This lines we bring us a subset of the table;
  4. The grouped sales data is converted to a dictionary using the .to_dict() method and stored in the sales_products_json variable;
  5. The sales_products_json dictionary, which contains the sales data for all products, is returned as a JSON response.

By search the table passing a list of two fields, products and total of sales; then group them up and take the sum. This lines we bring us this table:

This is returned by this Flask route: /sales/products and you can use it to make search using the next route: /sales/products/<item>

4# Step — This will search our db by item name

@app.route("/sales/products/<item>")
def sales_per_item(item):
table_prod_sales = table[["products", "total of sales"]].groupby("products").sum()
if item in table_prod_sales.index:
item_sales = table_prod_sales.loc[item]
sales_item_json = item_sales.to_dict()
return sales_item_json
else:
return {item: "Not Found in this database"}

This code provides an API endpoint that retrieves sales data for a specific product from a database and returns it as a JSON response. If the item is not found in the database, it returns an appropriate message indicating that the item was not found

Here’s how the code works:

  1. The route is defined using the @app.route() decorator, specifying the URL pattern as "/sales/products/<item>". This means that the route expects a URL of the form "/sales/products/<item>", where "<item>" can be replaced with the name of a product;
  2. The item parameter is passed to the function sales_per_item(item).
  3. Inside the function, a subset of the table is created, containing only the "products" and "total of sales" columns; The .groupby("products").sum() method is used to group the data by product and calculate the sum of sales for each product.
  4. The function checks if the specified item is present in the index of the grouped sales data. If it is, the sales data for that item is retrieved using .loc[item];
  5. The sales data for the item is converted to a dictionary using the .to_dict() method and stored in the sales_item_json variable.
  6. If the item is found in the sales data, the sales_item_json dictionary is returned as a JSON response;
  7. If the item is not found in the sales data, a dictionary with a single key-value pair is returned, where the item is the key and the value is "Not Found in this database". This indicates that the specified item was not found in the database.

5# Step — last line

app.run(host="0.0.0.0")

The line app.run(host="0.0.0.0") in Flask starts the Flask development server and binds it to the IP address "0.0.0.0".

Here’s what it does:

  1. app refers to the Flask application object that you have created.
  2. The run() method is called on the app object to start the Flask development server.
  3. The host parameter is set to "0.0.0.0". This means that the development server will bind to all available network interfaces on the machine, allowing it to accept requests from any IP address.

By using “0.0.0.0” as the host, the Flask application can be accessed from other devices on the same network. This is useful when you want to test or access your Flask application from a different device or allow external access.

It’s important to note that using “0.0.0.0” as the host can make your application accessible to anyone on the network, so exercise caution and consider appropriate security measures when using this configuration in production environments.

6# Step — All in one shot

from flask import Flask
import pandas as pd

app = Flask(__name__)
table = pd.read_excel("Sales - Dez.xlsx")


@app.route("/")
def gross_sales():
gross_sales = float(table["total of sales"].sum())
return {"gross_sales": gross_sales}


@app.route("/sales/products")
def sales_products():
table_prod_sales = table[["products",
"total of sales"]].groupby("products").sum()
sales_products_json = table_prod_sales.to_dict()
return sales_products_json


@app.route("/sales/products/<item>")
def sales_per_item(item):
table_prod_sales = table[["products", "total of sales"]].groupby("products").sum()
if item in table_prod_sales.index:
item_sales = table_prod_sales.loc[item]
sales_item_json = item_sales.to_dict()
return sales_item_json
else:
return {item: "Not Found in this database"}

app.run(host="0.0.0.0")

Notes:

What is the purpose of Flask?

[ChatGPT]

Flask is a popular web framework
for building web applications
in Python.

Its purpose is to provide developers
with a simple and flexible way to
create web applications and APIs.

Flask is known for its minimalistic
and lightweight design, allowing
developers to have more control over
the development process and make
decisions based on their
specific project requirements.

The main purpose of Flask is
to handle the low-level details
of webdevelopment, such as
routing HTTP requests
to the appropriate functions,
managing session data,
and generating HTTP responses.

It provides a set of tools and
libraries that help streamline
the development process, making
it easier to build web applications
with Python.

Flask follows a "micro" framework
philosophy, which means it provides
only the core functionality
needed to build web applications,
while allowing developers to add
additional features and extensions
as required.

This minimalistic approach makes
Flask highly versatile and allows
developers to keep their
applications lightweight
and efficient.

The simplicity and flexibility
of Flask have contributed
to its popularity among developers.
It has a relatively low learning
curve, making it accessible
to beginners, while still
providing the necessary features
for more complex projects.

Flask also has a large and
active community, which means
there are many resources and
extensions available to help
developers build robust
and scalable web applications.

That’s all folks

Bye for now!

References

TEXT2SQL.AI (Generate SQL — with AI) (thanks to MARCIO)

MONGODB — Build the next big thing (thanks to Alex Ishida)

Hashtag Treinamentos — Become a reference in the Market with Hashtag Training. Thanks to Lira: CEO & Founder of this amazing start up based on Rio de Janeiro — Brazil

DNS Propagation Checker

https://www.whatsmydns.net/
How DNS propagation’s happens?

I had to wait 4–6 hours till it works.

Why?

DNS propagation refers to the process by which changes to DNS (Domain Name System) records are propagated or distributed across the internet.

When you make changes to your domain’s DNS records, such as updating the IP address associated with a domain name or adding new DNS records, it takes some time for these changes to become effective and visible to all internet users.

Here’s how DNS propagation typically occurs:
  1. Making DNS record changes: When you make changes to your DNS records, such as updating the IP address of your domain or modifying other DNS settings, you usually do so through your domain registrar or DNS provider’s control panel or administration interface.
  2. TTL (Time to Live): Each DNS record has a TTL value associated with it. The TTL specifies how long the DNS information should be cached by DNS resolvers and other DNS servers before they expire and need to be refreshed. The TTL is defined in seconds and can be set to various values, commonly ranging from a few minutes to several hours.
  3. DNS caching: DNS resolvers and DNS servers across the internet cache DNS information to improve performance and reduce the load on the DNS infrastructure. When a DNS resolver receives a DNS query for a domain name, it checks if it has a cached copy of the DNS records for that domain. If the TTL of the cached record has not expired, the resolver uses the cached record without making a new DNS lookup.
  4. DNS record propagation: When you make changes to your DNS records, the updated DNS information needs to be propagated to DNS servers and resolvers worldwide. This propagation process involves updating the cached DNS records across the internet with the new information.
  5. Time for propagation: The time it takes for DNS propagation to complete can vary. It depends on factors such as the TTL value of the DNS records, the configuration of DNS servers, the caching behavior of DNS resolvers, and other network-related factors. In most cases, DNS propagation is relatively quick and can take anywhere from a few minutes to a few hours. However, it’s important to note that in some cases, DNS propagation can take longer, especially if the TTL values of the DNS records are set to longer durations.

During the propagation period, different DNS resolvers and servers may still have the old DNS records cached, while others may have already updated to the new records. This can result in some users seeing the old DNS information while others see the updated information, leading to temporary inconsistencies or discrepancies in DNS resolution.

It’s worth mentioning that you can perform DNS lookups using tools like nslookup or online DNS lookup services to check the current status of your DNS records and see if the changes have propagated to a specific DNS server.

👉️ GitHub

Credits

Hashtag Treinamentos

MÁRCIO POMPERMAIER

ALEX ISHIDA

Here is the endpoints:
## Simple ecomerce API using Flask:

This app lets You Manage & Scale Your Business;
it allows managers to browse and calculate
store's gross sales and search items
from an online store

#### DB: "Sales - Dez.xlsx" [ Directory - main root ]

#### End Points (JSON):
###### 1 - Return cia's GROSS SALES:
https://flaskapiecomerce.jaythree.repl.co

##### 2- Return total for each products
https://flaskapiecomerce.jaythree.repl.co/sales/products

##### 3 - Return the total of sale per item

https://flaskapiecomerce.jaythree.repl.co/sales/products/Jeans Jackets
answer ={ "total of sales" : 21432 }

https://flaskapiecomerce.jaythree.repl.co/sales/products/V-Neck
answer = { "total of sales" : 13910 }

https://flaskapiecomerce.jaythree.repl.co/sales/products/Peter Pan Collar
answer = { "total of sales" : 268020 }

Based on: hashtag treinamentos - Lira
Editor: j3
date : march 2023

https://flaskapiecomerce.jaythree.repl.co
https://flaskapiecomerce.jaythree.repl.co/sales/products
https://flaskapiecomerce.jaythree.repl.co/sales/products/Jeans Jackets
https://flaskapiecomerce.jaythree.repl.co/sales/products/V-Neck
https://flaskapiecomerce.jaythree.repl.co/sales/products/Peter Pan Collar

--

--

J3
Jungletronics

Hi, Guys o/ I am J3! I am just a hobby-dev, playing around with Python, Django, Ruby, Rails, Lego, Arduino, Raspy, PIC, AI… Welcome! Join us!