3rd Review
3rd Review
2. Tools:
Pycharm(Code editor)
Anaconda(creating the enviourment)
Python IDE
GitBash Terminal
Any Browser(Server Connection)
3. DBMS Used for Implementation:
The Company works on mainly web based Applications under which they have different
department. In my Internship, they are giving me the training for Django as a Backend
Developer. The project they have initially assigned me is related to a shopping Web
Application in which they have two parts one which is used by the customer that is called
front-end and the second one is admin part where all the activities will be monitories, for both
these parts the backend will be designed by me. The basic output of these project will be a
web based application which will be used by the clients for their online shopping purpose.
Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. Built by experienced developers, it takes care of much of the hassle of web
development, so you can focus on writing your app without needing to reinvent the wheel.
It’s free and open source
As my projects in the company are mainly based on web development me and my team worked
on python web based development. Python has some distinct advantages that make it suitable
for developing web applications. Python has a large number of ready-made libraries for
developers to use to solve numerous problems; developers can distribute their libraries as well.
All these things allow developers to not focus on issues that are already solved but to use their
time and energy to build applications and solve problems that are unique to them.
There are mainly two framework which is popular for Python web based development:
1. Django
2. Flask
I have mainly used Django with mezzanine for development of Web-server based applications
and websites.
About Django :
Complete
Django follows the "Batteries included" philosophy and provides almost everything
developers might want to do "out of the box". Because everything you need is part of the one
"product", it all works seamlessly together, follows consistent design principles, and has
extensive and up-to-date documentation.
Versatile
Django can be (and has been) used to build almost any type of website — from content
management systems and wikis, through to social networks and news sites. It can work with
any client-side framework, and can deliver content in almost any format (including HTML,
RSS feeds, JSON, and XML).
Internally, while it provides choices for almost any functionality you might want (e.g. several
popular databases, templating engines, etc.), it can also be extended to use other components
if needed.
Secure
Django helps developers avoid many common security mistakes by providing a framework
that has been engineered to "do the right things" to protect the website automatically. For
example, Django provides a secure way to manage user accounts and passwords, avoiding
common mistakes like putting session information in cookies where it is vulnerable (instead
cookies just contain a key, and the actual data is stored in the database) or directly storing
passwords rather than a password hash.
Django enables protection against many vulnerabilities by default, including SQL injection,
cross-site scripting, cross-site request forgery and click jacking
Scalable
Django uses a component-based "shared-nothing" architecture (each part of the architecture is
independent of the others, and can hence be replaced or changed if needed). Having a clear
separation between the different parts means that it can scale for increased traffic by adding
hardware at any level: caching servers, database servers, or application servers. Some of the
busiest sites have successfully scaled Django to meet their demands (e.g. Instagram and
Disqus).
Maintainable
Django code is written using design principles and patterns that encourage the creation of
maintainable and reusable code. In particular, it makes use of the Don't Repeat Yourself
(DRY) principle so there is no unnecessary duplication, reducing the amount of code. Django
also promotes the grouping of related functionality into reusable "applications" and, at a
lower level, groups related code into modules (along the lines of the Model View Controller
(MVC) pattern).
Portable
Django is written in Python, which runs on many platforms. That means that you are not tied
to any particular server platform, and can run your applications on many flavors of Linux,
Windows, and macOS.
Furthermore, Django is well-supported by many web hosting providers, who often provide
specific infrastructure and documentation for hosting Django sites.
Methodology used:
We follows the Model-View-Template (MVT) variation of the MVC pattern, where the
Template component is responsible for defining the layout of the user interface. The MVT
pattern separates an application into three distinct components:
• Model: The Model component represents the data and business logic of the
application. Django uses an Object-Relational Mapping (ORM) system that allows
developers to define the data models using Python classes. The ORM system then
translates these classes into database tables.
• View: The View component handles the user input and output. In Django, views are
Python functions that take HTTP requests and return HTTP responses. Views interact
with the Model to retrieve or update data and pass the data to the Template for
rendering.
• Template: The Template component defines the layout of the user interface. Django
uses its own templating language that allows developers to define the HTML markup
and control flow logic of the user interface. The Template receives data from the
View and renders it into an HTML response.
Figure 1(Methodolgy)
What does Django code look like?
In a traditional data-driven website, a web application waits for HTTP requests from the web
browser (or other client). When a request is received the application works out what is needed
based on the URL and possibly information in POST data or GET data. Depending on what is
required it may then read or write information from a database or perform other tasks
required to satisfy the request. The application will then return a response to the web browser,
often dynamically creating an HTML page for the browser to display by inserting the
retrieved data into placeholders in an HTML template.
URLs: While it is possible to process requests from every single URL via a single
function, it is much more maintainable to write a separate view function to handle
each resource. A URL mapper is used to redirect HTTP requests to the appropriate
view based on the request URL. The URL mapper can also match particular patterns
of strings or digits that appear in a URL and pass these to a view function as data.
Workingof Django:
A URL mapper is typically stored in a file named urls.py. In the example below, the mapper
(URL patterns) defines a list of mappings between routes (specific URL patterns) and
corresponding view functions. If an HTTP Request is received that has a URL matching a
specified pattern, then the associated view function will be called and passed the request.
urlpatterns = [
path('admin/', admin.site.urls),
path('book/<int:id>/', views.book_detail, name='book_detail'),
path('catalog/', include('catalog.urls')),
re_path(r'^([0-9]+)/$', views.best),
]
The urlpatterns object is a list of path () and/or re_path () functions (Python lists are defined
using square brackets, where items are separated by commas and may have an optional
trailing comma. For example: [item1, item2, item3,]).
The first argument to both methods is a route (pattern) that will be matched.
The path() method uses angle brackets to define parts of a URL that will be captured and
passed through to the view function as named arguments. The re_path () function uses a
flexible pattern matching approach known as a regular expression.
The second argument is another function that will be called when the pattern is matched. The
notation views.book_detail indicates that the function is called book_detail () and can be
found in a module called views (i.e. inside a file named views.py)
Views are the heart of the web application, receiving HTTP requests from web clients and
returning HTTP responses. In between, they marshal the other resources of the framework to
access databases, render templates, etc.
The example below shows a minimal view function index (), which could have been called
by our URL mapper in the previous section. Like all view functions it receives an Http
Request object as a parameter (request) and returns an Http Response object. In this case we
don't do anything with the request, and the response returns a hard-coded string.
def index(request):
# Get an HttpRequest - the request parameter
# perform operations using information from the request.
# Return HttpResponse
return HttpResponse('Hello from Django!')
Django web applications manage and query data through Python objects referred to as
models. Models define the structure of stored data, including the field types and possibly also
their maximum size, default values, selection list options, help text for documentation, label
text for forms, etc. The definition of the model is independent of the underlying database —
we can choose one of several as part of your project settings. Once ywe chosen what database
we want to use, we don't need to talk to it directly at all — we just write our model structure
and other code, and Django handles all the "work" of communicating with the database.
1. Turbogears:
TurboGears applications can be deployed on any web server that supports the WSGI Python
interface. In addition, it comes attached with Gearbox, a command-line interface for
managing projects, and Kajiki, a templating engine.
It is perfect for handling database-driven websites as it has an open-source SQL kit known as
SQLAlchemy. It also has support for SQLObject, which is a powerful Object-relational
mapping package that lets you write server-side code very quickly, in just a few days.
TurboGears can be considered the best alternative to Django, if you are looking for a
framework that is most similar to Django. Both have powerful template engine, high-powered
ORM, database support, and are extensible, but TurboGears is not as opinionated.
2. Web2py:
Web2py is a web-based framework that allows you to create, modify, deploy and manage
apps from anywhere using your browser. It is a cross-platform framework that can be used on
multiple devices and browsers. It also deploys a powerful error logging and ticketing system.
Web2py has no dependencies outside of the Python standard library. It requires no
prerequisites for installation or configuration. Along with backward compatibility, it also has
security measures against attacks such as cross-site scripting, SQL injection and other
malicious attacks.
It has a fully-featured IDE, which allows you to change the content on your website from any
web browser, even after it is deployed. You can develop fast, scalable, secure database-driven
web applications with Web2py.
3. CubicWeb
CubicWeb is a free, open-source semantic web application framework that works on a data
model. Developers can develop web applications efficiently by reusing components called
cubes. It employs object-oriented design principles and has an embedded query language.
CubicWeb also includes Relational Query Language (RQL) which simplifies data-related
queries using a simple syntax. You are able to manage relationship queries, data repositories,
and view attributes.
CubicWeb offers semi-automatic mechanisms for handling XML and JSON code generation,
and workflow with security. Large-scale semantic websites and linked open data apps are
good for using CubicWeb.
4. Microframework:
Django, can sometimes be monolithic. Other full stack frameworks can also be too complex
for small, basic websites and applications that do not require a lot of features. Python has a
series of well-designed micro frameworks such as Flask, Bottle and CherryPy that work
perfectly with small-scale websites.
CherryPy requires minimal lines to write the source code resulting in low development time
and high productivity.
It is a very lightweight alternative for Django and one of the oldest Python frameworks.
CherryPy has built-in tools for coding static web pages, URL encoding, user authentication,
and session management. It is also embedded with a powerful configuration system that can
handle multiple HTTP requests and run multiple HTTP servers simultaneously.
6. Pyramid:
Pyramid is the most flexible Python framework available .A lightweight, scalable framework,
Pyramid is used for developing small to large-scale web apps. It is also great for quick
prototyping and for developers who are working on API projects.
Pyramid has a small footprint but it is easily extendable with add-ons, configurations and
libraries to include unique functionalities in your app. It sometimes provides so many options
that it can get tough to make the right choices in a new project.
Major companies such as Dropbox, Fedora, Mozilla, SurveyMonkey, and Yelp use Pyramid
for website development.
7. Bottle:
The bottle is a simple, fast, and lightweight web-based framework distributed as a single file
module. It works on any Python WSGI compliant server and is mainly used for building
APIs. It is also a preferred choice for building simple prototypes.
It has support for various databases and URL parameters along with the built-in template
engine Simple Template. It is also highly flexible and allows you to integrate third-party
templating engines such as Mako, Jinja2, or Cheetah. There are plugins and external libraries
available for ORM support, NoSQL database, and admin panels.
8. Falcon:
Falcon is a reliable, high-performance Python WSGI library for rapid backend development.
It is mainly used for micro web services, Web API, web sockets, and back-ends of large-scale
applications. It encourages usage of REST architectural style, very much like the Django Rest
framework, and tries to do as little as possible.
It is highly effective and cuts down internal dependencies by using a clean HTTP and REST
framework architecture design. High performance with a significantly lower code base,
Falcon is a minimalistic alternative to Django.
Scope: The scope of the project will be limited to some functions of the e-commerce website. It
will display products, customers can select catalogs and select products, and can remove products
from their cart specifying the quantity of each item. Selected items will be collected in a cart. At
checkout, the item on the card will be presented as an order. Customers can pay for the items in the
cart to complete an order. This project has great future scope. The project also provides security
with the use of login ID and passwords, so that no unauthorized users can access your account. The
only authorized person who has the appropriate access authority can access the software.
Step 2-Install Django: Next, we will install the Django module from the terminal. We will
use PyCharm integrated terminal to do this task, to install the module by running python -m
pip install django command
Step 3-Check Installed Django version: To check the installed Django version, you can run
the python -m django -version command as shown below.
Step 4-Create Django Project: When we execute django-admin startproject command, then it
will create a Django project inside the normal project which we already have created here.
django-admin startproject ProjectName.
Step 5-Run Default Django webserver:- Django internally provides a default webserver
where we can launch our applications. python manage.py runserver command in terminal.
By default, the server runs on port 127.0.0. 8000. Access the webserver at the highlighted
URL.
When We run the server the interface will look like this:
When we Open the project folder using a text editor(Pycharm). The directory structure look
like this :
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls'))
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Models
The below screenshot shows the required models that we will need to create. These models are
tables that will be stored in the SQLite database.
1. category.py
class Category(models.Model):
name = models.CharField(max_length=50)
@staticmethod
def get_all_categories():
return Category.objects.all()
def __str__(self):
return self.name
2. customer.py
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
phone = models.CharField(max_length=10)
email = models.EmailField()
password = models.CharField(max_length=100)
# to save the data
def register(self):
self.save()
@staticmethod
def get_customer_by_email(email):
try:
return Customer.objects.get(email=email)
except:
return False
def isExists(self):
if Customer.objects.filter(email=self.email):
return True
return False
3. products.py
class Products(models.Model):
name = models.CharField(max_length=60)
price = models.IntegerField(default=0)
description = models.CharField(
image = models.ImageField(upload_to='uploads/products/')
@staticmethod
def get_products_by_id(ids):
return Products.objects.filter(id__in=ids)
@staticmethod
def get_all_products():
return Products.objects.all()
@staticmethod
def get_all_products_by_categoryid(category_id):
if category_id:
return Products.objects.filter(category=category_id)
else:
return Products.get_all_products()
4. Orders.py:
class Order(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
address = models.CharField(max_length=50, default='', blank=True)
phone = models.CharField(max_length=50, default='', blank=True)
date = models.DateField(default=datetime.datetime.today)
status = models.BooleanField(default=False)
def placeOrder(self):
self.save()
@staticmethod
def get_orders_by_customer(customer_id):
return Order.objects.filter(customer=customer_id).order_by('-date')
5. Views :
urlpatterns = [
]
The below files show the views for each functionality of the site.
home.py:
class Index(View):
product = request.POST.get('product')
remove = request.POST.get('remove')
cart = request.session.get('cart')
if cart:
quantity = cart.get(product)
if quantity:
if remove:
if quantity <= 1:
cart.pop(product)
else:
cart[product] = quantity-1
else:
cart[product] = quantity+1
else:
cart[product] = 1
else:
cart = {}
cart[product] = 1
request.session['cart'] = cart
print('cart', request.session['cart'])
return redirect('homepage')
# print()
return HttpResponseRedirect(f'/store{request.get_full_path()[1:]}')
def store(request):
cart = request.session.get('cart')
if not cart:
request.session['cart'] = {}
products = None
categories = Category.get_all_categories()
categoryID = request.GET.get('category')
if categoryID:
products = Products.get_all_products_by_categoryid(categoryID)
else:
products = Products.get_all_products()
data = {}
data['products'] = products
data['categories'] = categories
class Login(View):
return_url = None
if Login.return_url:
return HttpResponseRedirect(Login.return_url)
else:
Login.return_url = None
return redirect('homepage')
else:
error_message = 'Invalid !!'
else:
error_message = 'Invalid !!'
print(email, password)
return render(request, 'login.html', {'error': error_message})
def logout(request):
request.session.clear()
return redirect('login')
2. signup.py:
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password
from store.models.customer import Customer
from django.views import View
customer = Customer(first_name=first_name,
last_name=last_name,
phone=phone,
email=email,
password=password)
error_message = self.validateCustomer(customer)
if not error_message:
print(first_name, last_name, phone, email, password)
customer.password = make_password(customer.password)
customer.register()
return redirect('homepage')
else:
data = {
'error': error_message,
'values': value
}
return render(request, 'signup.html', data)
class Order(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
customer = models.ForeignKey(Customer,on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
price = models.IntegerField()
address = models.CharField(max_length=50, default='', blank=True)
phone = models.CharField(max_length=50, default='', blank=True)
date = models.DateField(default=datetime.datetime.today)
status = models.BooleanField(default=False)
def placeOrder(self):
self.save()
@staticmethod
def get_orders_by_customer(customer_id):
return Order.objects.filter(customer=customer_id).order_by('-date')
4. checkout.py:
from django.shortcuts import render, redirect
class CheckOut(View):
def post(self, request):
address = request.POST.get('address')
phone = request.POST.get('phone')
customer = request.session.get('customer')
cart = request.session.get('cart')
products = Products.get_products_by_id(list(cart.keys()))
print(address, phone, customer, cart, products)
for product in products:
print(cart.get(str(product.id)))
order = Order(customer=Customer(id=customer),
product=product,
price=product.price,
address=address,
phone=phone,
quantity=cart.get(str(product.id)))
order.save()
request.session['cart'] = {}
return redirect('cart')
5. orders.py:
class OrderView(View):
Part 2: (Connecting the website With Artiicial Intelligence Using Machine Learning)
Building a recommendation system that can adjust product prices and offers based on user
engagement in the website .
Building a machine learning model that can predict the price and offers for a product based
on user involvement:
Creating backend api to receive request and return recommendation for this-
4. Model integration:
Create backend API to receive requests and return recommendations
Integrate machine learning model into website frontend
1. Choose a web framework: I had chosen Django framework that's compatible with
Python. Django is a full-featured web framework that includes many built-in
components
2. Defining endpoints: Once chosen a web framework, I define the endpoints for API.
An endpoint is a URL that can receive requests and return responses. For example,
I will define an endpoint /recommendations that accepts a user ID and returns a list
of recommended products.
3. Implement request handling: I will write code to handle requests to API endpoints.
This will typically involve parsing request parameters, passing them to the
machine learning model to generate recommendations, and returning the
recommendations in a suitable format, such as JSON or XML.
4. Deploy your API: Once I will implemented the API, I'll need to deploy it to a web
server or cloud platform so that it can be accessed by our website frontend.