DEV Community

Kanny Mohamad
Kanny Mohamad

Posted on • Edited on

KMarket

Welcome to KMarket, your one-stop destination for a seamless online shopping experience. Whether you are a user looking to browse and purchase items or an admin managing the marketplace, KMarket has got you covered with robust features and an intuitive interface.

User-Friendly Authentication

At KMarket, we prioritize security and ease of access. Our platform offers a straightforward login system that allows users to access their accounts effortlessly. If you don’t have an account, creating one is a breeze. Simply sign up with your email and a password, which will be securely hashed to ensure your data remains protected.

Explore and Select Products

Once logged in, users are greeted with an array of products displayed with vibrant images, detailed descriptions, and competitive prices. Our user interface is designed to make browsing enjoyable and straightforward. See something you like? Simply select the products you are interested in and add them to your selection.

Personalized Profile Page

After selecting your desired products, navigate to your profile page to review your choices. Here, you can view your personal details, including your name, email, and phone number, as well as the images of the products you have selected. The profile page provides a clear and concise summary of your selections, ensuring you have all the information you need before making a purchase.

Manage Your Selections

KMarket gives you full control over your selections. If you change your mind about a product, you can easily remove it from your list. This flexibility ensures that you only purchase items you truly want.

Admin Capabilities

For users with admin privileges, KMarket offers a comprehensive set of tools to manage the marketplace. Admins can perform full CRUD (Create, Read, Update, Delete) operations on the user table. This means you can add new users, update existing user information, delete users, and view a detailed table of all users.

Seamless Navigation

Navigating KMarket is designed to be intuitive and user-friendly. For admins, a convenient back button allows you to return to the home page effortlessly, ensuring you can manage the marketplace without any hassle.

Technical Overview

I want to introduce you to my K-Market project. This platform is built with Flask and SQLAlchemy for the backend, featuring many-to-many relationships and models. The frontend uses React Router for client-side routing and Tailwind CSS for styling. It supports full CRUD operations, follows REST conventions, and includes validation and error handling, built with useContext.

Here is the structure of my project:

  • Client Folder: Contains the main components, pages, and useContext.
  • Server Folder: Contains the instance (including the database), models (including the tables), config, and seed for seeding the tables with data.

Generating a React Application

To get started, let's spin up our React application using create-react-app:

npx create-react-app client --use-npm

Creating the Server Application

With the environment set up, let's get started on building our Flask application!

Setting Up the Virtual Environment

Navigate to the root directory of your project.
Run the following command to create and activate a virtual environment using Pipenv:
pipenv install && pipenv shell
$ tree -L 2
$ # the -L argument limits the depth at which we look into the directory structure
.
├── CONTRIBUTING.md
├── LICENSE.md
├── Pipfile
├── README.md
├── client
│ ├── README.md
│ ├── package.json
│ ├── public
│ └── src
└── server
├── app.py
├── config.py
├── models.py
└── seed.py
Then enter the commands to create the instance and migrations folders and the database app.db file:
flask db init
flask db upgrade head

Tools that have been used:
react-router-domv6
React Context

Client side:

Building the Client Side with UseContext to Prevent Prop Drilling
To manage state and prevent prop drilling, we'll use the useContext hook. This allows us to share state across components without having to pass props down through multiple levels.

Using React Router Dom v6 with Nested Routes
We will use React Router Dom v6 to handle routing in our application. Nested routes can be defined using the children property. To render these nested routes, you need to include the Outlet component in your parent component.

Using Formik and Yup for Form Validation
To install Formik, run the following command:

npm install --save formik

To install Yup, run the following command:

npm install yup

Client side:

Run pipenv install to install the dependencies and pipenv shell to enter your virtual environment before running your code.

pipenv install
pipenv shell
Change into the server directory and configure the FLASK_APP and FLASK_RUN_PORT environment variables:

cd server
export FLASK_APP=app.py
export FLASK_RUN_PORT=5555
Let's create the database app.db with an empty user table:

flask db init
flask db migrate -m "Initial migration."
flask db upgrade head
And for delete the db

rm -rf migrations

For adding new model we following to perform a migration:

flask db migrate -m 'add review'
flask db upgrade head
Implement validations and error handling
we can add to the column when we first create a column nullable=False that is mean it can not be no value

name = db.Column(db.String, nullable=False)
we are going to import validates from sqlalchemy.orm and use validates decorator,

@validates('email')
def validates_email(self, key, email_input):
if '@' not in email_input:
raise ValueError("wrong email format")
return email_input
we can test that through flask shell

Werkzeug
it is WSGi library It includes a number of features that will come in handy as we start to build our first Python web applications:

An in-browser debugger.
Robust classes for requests and responses.
Routing, auto-generation and management of URLs.
A development server.
A testing framework that does not require a running server.

Serializer we import Serializer from SerializerMixin

from sqlalchemy_serializer import SerializerMixin
By using SQLAlchemy-Serializer, programmers can create faster and more efficient programs that can easily share data with others, we can include and not include some key, value pair from json file and also using .to_dict() to make it easier to loop on the data in the table as en example: in model.py

class Goods(db.Model, SerializerMixin):
__tablename__ = 'goods'

in the app.py

class Goodss(Resource):
def get(self):
goods = Goods.query.all()
goods_list = [good.to_dict() for good in goods]
return make_response(jsonify(goods_list), 200)

Seeding the database
Here is an example of how to add a user to the database:

users.append(Admin(name="admin", email="admin@gmail.com", password="1234"))
db.session.add_all(users)
db.session.commit()
then run

python seed.py

One-To-Many Relationships

A single User can have multiple Login entries. This is indicated by the logins attribute in the User class, which is a list of Login objects associated with the user.

`class User(db.Model, SerializerMixin):
tablename = 'users'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String, nullable=False)
email = db.Column(db.String, unique=True, nullable=False)
_password = db.Column(db.String, nullable=False)
phone_number = db.Column(db.String, nullable=True)
admin = db.Column(db.Boolean, default=False)

logins = relationship('Login', backref='user', lazy=True)
Enter fullscreen mode Exit fullscreen mode

class Login(db.Model, SerializerMixin):
tablename = 'logins'

id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
_password = db.Column(db.String, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)`
Enter fullscreen mode Exit fullscreen mode

Password:

import bcrypt in the config and invoke it, and we need to run

pip install flask-bcrypt
Session
hold user info for us, allow some information between requests, no need to make query every time

Secret Key
to get the secret ket just run in the terminal

$ python -c 'import os; print(os.urandom(16))'
then in the config file

app.secret_key = b'Z\x9e&T\x87\xe5\xc1Q6|\xdaJ\xc7I\x87\xe6'
Tailwindcss
Tailwind CSS
Folder Structure
src/
style.css
public/dist/
style.css
index.html
Setup
npm run build:css

Step 1: Update package.json
Make sure your package.json includes the following script:

"scripts": {
"start": "react-scripts start",
"build:css": "tailwind build src/style.css -o dist/style.css",
"test": "react-scripts test",
"eject": "react-scripts eject"
}

Conclusion

KMarket is more than just an online marketplace; it is a platform designed with the user in mind. From secure authentication to a personalized shopping experience, and powerful admin tools, KMarket ensures that both users and admins have everything they need at their fingertips. Join KMarket today and discover a better way to shop and manage your online marketplace.

Top comments (0)