SlideShare a Scribd company logo
Module 4
Chapter -11, 12
Namyapriya D, Asst Professor, CSE, KSIT 1
MIME types
What is MIME (Multipurpose Internet Mail Extensions)?
 MIME (Multipurpose Internet Mail Extensions) is an extension of the
original Simple Mail Transport Protocol (SMTP) email protocol. It lets
users exchange different kinds of data files, including audio, video,
images and application programs, over email.
 MIME is a standard that extends the format of email to support text in
character sets other than ASCII, as well as attachments like images, audio,
video, and application programs. MIME types are also used in HTTP to
define the type of content being delivered over the web.
Namyapriya D, Asst Professor, CSE, KSIT
Key Components of MIME
Content-Type: Indicates the media type of the resource.
Content-Disposition: Provides information about how to handle the file
(e.g., inline, attachment).
Content-Transfer-Encoding: Describes the encoding used to safely transfer
the content over protocols like SMTP.
Namyapriya D, Asst Professor, CSE, KSIT
Step-by-Step Process
4
 File Request: The client (e.g., a web browser) requests a file from the
Django application.
 Django Response: Django processes the request and prepares to serve the
file.
 Setting MIME Type: Django determines the MIME type of the file using the
mimetypes module or by specifying it directly.
 FileResponse: Django creates a FileResponse object, including the MIME
type in the Content-Type header.
 Send Response: Django sends the response back to the client.
 Client Handling: The client receives the response, checks the Content-Type
header to determine the file type, and then handles the file accordingly (e.g.,
displaying it inline if it's an image, prompting for download if it's an
attachment).
Namyapriya D, Asst Professor, CSE, KSIT
Advantages of MIME
 MIME has several advantages over SMTP.
 Users can send different kinds of binary attachments via email.
 Multiple attachments of different types can be included in the same email.
 There are no limits on message length.
 Multipart messages are supported.
5
Namyapriya D, Asst Professor, CSE, KSIT
Interacting with Non-Html content
Namyapriya D, Asst Professor, CSE, KSIT
Views with Non-Html content
 Normally a Django view receives HttpRequest request and returns HttpResponse
 By using mime-type in the constructor of HttpResponse, one can return Non-HTML content
 One can return image, XML, CSV, PDF etc by including appropriate mime type
Namyapriya D, Asst Professor, CSE, KSIT
Namyapriya D, Asst Professor, CSE, KSIT
What is a csv file?
 A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring
to arrange tabular data. Because it’s a plain text file, it can contain only actual text data—in other
words, printable ASCII or Unicode characters.
 The structure of a CSV file is given away by its name. Normally, CSV files use a comma to
separate each specific data value. Here’s what that structure looks like:
 ( Normally, the first line identifies each piece of data—in other words, the name of a data
column. Every subsequent line after that is actual data and is limited only by file size constraints.
 In general, the separator character is called a delimiter, and the comma is not the only one used.
Other popular delimiters include the tab (t), colon (:) and semi-colon (;) characters. Properly
parsing a CSV file requires us to know which delimiter is being used.
Namyapriya D, Asst Professor, CSE, KSIT
Sample CSV File
Namyapriya D, Asst Professor, CSE, KSIT
Download csv
 Python comes with a CSV library, csv. The key to using it with Django is that the csv module’s CSV-creation
capability acts on file-like objects, and Django’s HttpResponse objects are file-like objects.
 The response gets a special MIME type, text/csv. This tells browsers that the document is a CSV file, rather than
an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will result in
ugly, scary gobbledygook in the browser window.
 The response gets an additional Content-Disposition header, which contains the name of the CSV file. This
filename is arbitrary; call it whatever you want. It’ll be used by browsers in the “Save as…” dialog, etc.
 You can hook into the CSV-generation API by passing response as the first argument to csv.writer.
The csv.writer function expects a file-like object, and HttpResponse objects fit the bill.
 For each row in your CSV file, call writer.writerow, passing it an iterable.
 The CSV module takes care of quoting for you, so you don’t have to worry about escaping strings with quotes or
commas in them. Pass writerow() your raw strings, and it’ll do the right thing.
Namyapriya D, Asst Professor, CSE, KSIT
Http content types
Namyapriya D, Asst Professor, CSE, KSIT
Http Content Types
•text/html
•text/plain
•Text/csv
•application/msword
•application/vnd.ms-excel
•application/jar
•application/pdf
•application/octet-stream
•application/x-zip
•images/jpeg
•images/png
•images/gif
•audio/mp3
•video/mp4
•video/quicktime etc.
https://www.iana.org/assignments/media-types/media-
types.xhtml#text
Namyapriya D, Asst Professor, CSE, KSIT
Namyapriya D, Asst Professor, CSE, KSIT
Namyapriya D, Asst Professor, CSE, KSIT
reportLab – pdf documents generation
 ReportLab is an open source toolkit for creating PDF documents from Python. It is a
very extensive library with many features, from small texts and geometric figures to
large graphics and illustrations, all of which can be included in a PDF.
 The first two arguments passed to drawstring indicate the x,y position where the text
will appear.
Namyapriya D, Asst Professor, CSE, KSIT
PDF Generation steps
We start by importing the modules and classes. Canvas is used to draw
things on the pdf,
 initialize a canvas object with the name of the pdf and set the title to be the
document title
we draw a lines of text that we defined in the list
Show the pdf and save
Namyapriya D, Asst Professor, CSE, KSIT
Namyapriya D, Asst Professor, CSE, KSIT
Namyapriya D, Asst Professor, CSE, KSIT
Syndication Feed Framework in Django
• The Syndication Feed Framework in Django simplifies the process of
creating RSS or Atom feeds.
Syndication Feed Framework allows you to expose your site's content as
feeds, which users can subscribe to and receive updates.
How to set Syndication Feed Framework?
Define a Feed Class
Create a feed class by inheriting from
django.contrib.syndication.views.Feed. Define methods to specify the
title, link, description, and the items to be included in the feed.
20
Namyapriya D, Asst Professor, CSE, KSIT
• What is Atom and RSS feed?
RSS:
• RSS (Really Simple Syndication) is a web feed type that allows users to access updates from
websites or blogs without having to visit each one separately. It allows content creators to share
their information in a standardized manner, making it easier for users to subscribe and
automatically receive updates.
ATOM:
• Atom is a standardized web feed format that allows content producers to syndicate their
information. Atom, like RSS (Really Simple Syndication), allows users to subscribe to updates
from websites or blogs without visiting them individually. Atom was created as an alternative to
RSS with the goal of improving extensibility while adopting a more modern approach to web
distribution
21
Namyapriya D, Asst Professor, CSE, KSIT
Configure URLs
Add the feed to your URL configuration to make it accessible via a
specific URL.
Customize Feed Items
You can add more methods to customize the feed items, such as
including the author's name, publication date, and categories.
22
Namyapriya D, Asst Professor, CSE, KSIT
23
#feeds.py
from django.contrib.syndication.views import Feed
from django.urls import reverse
from .models import Post
class LatestPostsFeed(Feed):
title = "Latest Posts"
link = "/feeds/latest/"
description = "Updates on the latest blog posts."
def items(self):
return Post.objects.order_by('-published_date')[:5]
def item_title(self, item):
return item.title
def item_description(self, item):
return item.summary
def item_link(self, item):
return reverse('post_detail', args=[item.pk])
def item_author_name(self, item):
return item.author.get_full_name()
def item_pubdate(self, item):
return item.published_date
def item_categories(self, item):
return [category.name for category in item.categories.all()]
Namyapriya D, Asst Professor, CSE, KSIT
24
# urls.py
from django.urls import path
from .feeds import LatestPostsFeed
urlpatterns = [
# other URL patterns
path('feeds/latest/', LatestPostsFeed(),
name='latest_posts_feed’),
]
Namyapriya D, Asst Professor, CSE, KSIT
Sitemap Framework in Django
To create a sitemap in Django and serve it as an XML file, you'll use Django's built-in
sitemap framework. This will generate a sitemap.xml file that helps search engines index
your website efficiently.
Install and Configure Django Sitemap Framework
First, ensure that django.contrib.sitemaps is included in your INSTALLED_APPS in
settings.py.
Create Sitemap Classes
Create a sitemaps.py file where you define your sitemap classes. Each class should
inherit from django.contrib.sitemaps.Sitemap.
Configure URLs
Add the sitemap to your URL configuration to make it accessible via a specific URL.
Generate XML Sitemap
When you navigate to /sitemap.xml, Django will generate the sitemap in XML format.
25
Namyapriya D, Asst Professor, CSE, KSIT
# settings.py
INSTALLED_APPS =
[
# other installed
apps
'django.contrib.sitema
ps',
]
26
# sitemaps.py
from django.contrib.sitemaps import Sitemap
from .models import Post, Author
class PostSitemap(Sitemap):
changefreq = "weekly"
priority = 0.8
def items(self):
return Post.objects.all()
def lastmod(self, obj):
return obj.updated_date
class AuthorSitemap(Sitemap):
changefreq = "monthly"
priority = 0.6
def items(self):
return Author.objects.all()
def lastmod(self, obj):
return obj.updated_date
Namyapriya D, Asst Professor, CSE, KSIT
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/posts/1/</loc>
<lastmod>2024-07-09</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>http://www.example.com/posts/2/</loc>
<lastmod>2024-07-08</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
27
<url>
<loc>http://www.example.com/authors/1/</loc>
<lastmod>2024-07-07</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<!-- Additional URLs here -->
</urlset>
Namyapriya D, Asst Professor, CSE, KSIT
# models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
content = models.TextField()
updated_date =
models.DateTimeField(auto_now=True)
is_important =
models.BooleanField(default=False)
def __str__(self):
return self.title
28
class Author(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
bio = models.TextField()
updated_date =
models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
Namyapriya D, Asst Professor, CSE, KSIT
# urls.py
from django.contrib import sitemaps
from django.contrib.sitemaps.views import
sitemap
from .sitemaps import PostSitemap,
AuthorSitemap
sitemaps = {
'posts': PostSitemap,
'authors': AuthorSitemap,
}
urlpatterns = [
# other URL patterns
path('sitemap.xml', sitemap, {'sitemaps':
sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
]
29
Namyapriya D, Asst Professor, CSE, KSIT
Cookies and Sessions in Django
30
Namyapriya D, Asst Professor, CSE, KSIT
Cookies
In Django, cookies are a convenient way to store small amounts of data on the
client side. They can be used to maintain stateful information between different
requests from the same user.
Setting a Cookie
Getting a Cookie
Deleting a Cookie
Secure and HttpOnly Cookies
When setting cookies, you can use additional parameters like secure and
httponly to enhance security:
secure: Ensures the cookie is only sent over HTTPS connections.
httponly: Ensures the cookie is only accessible by the server, not via JavaScript.
31
Namyapriya D, Asst Professor, CSE, KSIT
# views.py
from django.http import HttpResponse
def cookie_example_view(request):
response = HttpResponse("Cookie Example")
# Set a cookie
response.set_cookie('example_cookie', 'cookie_value',
max_age=3600, secure=True, httponly=True)
32
# Get a cookie
cookie_value = request.COOKIES.get('example_cookie')
if cookie_value:
response.write(f'Cookie Value: {cookie_value}n')
else:
response.write('Cookie Not Foundn')
# Delete a cookie
response.delete_cookie('example_cookie')
return response
Namyapriya D, Asst Professor, CSE, KSIT
Sessions
In Django, sessions are used to store and retrieve arbitrary data on a per-site-visitor basis.
Django abstracts the process of sending and receiving cookies, allowing you to store data on
the server side and associate it with a session ID that is sent to the client via a cookie. This
approach enhances security and scalability.
Configuring Sessions in Django
Django supports several session backends:
Database-backed sessions
Cached sessions
File-based sessions
Cookie-based sessions
Custom backends
33
Namyapriya D, Asst Professor, CSE, KSIT
# views.py
from django.shortcuts import render
from django.http import HttpResponse
def set_session_view(request):
request.session['username'] = 'john_doe'
request.session['email'] =
'john_doe@example.com'
return HttpResponse("Session data set")
def get_session_view(request):
username = request.session.get('username',
'Guest')
email = request.session.get('email', 'No email
provided')
return HttpResponse(f"Hello, {username}.
Your email is {email}.") 34
def delete_session_view(request):
try:
del request.session['username']
del request.session['email']
except KeyError:
pass
return HttpResponse("Session data cleared")
def clear_session_view(request):
request.session.flush()
return HttpResponse("All session data cleared")
Namyapriya D, Asst Professor, CSE, KSIT
Users and Authentication
Django provides a robust authentication system out of the box, including user
login, logout, password management, and permissions.
Setting Up Authentication
Ensure that django.contrib.auth and django.contrib.contenttypes are included in
your INSTALLED_APPS.
 Creating a User
You can create a user using the Django shell or programmatically within your
views.
• User Login
Django provides a login function to log users in.
• User Logout
Django provides a logout function to log users out.
35
Namyapriya D, Asst Professor, CSE, KSIT
 Password Management
Django includes built-in views for password management. First, ensure the URL
configuration includes Django’s authentication URLs.
Django provides the following built-in views for password management:
PasswordChangeView and PasswordChangeDoneView
PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and
PasswordResetCompleteView
• Custom User Model
For more flexibility, you can create a custom user model by extending
AbstractBaseUser and PermissionsMixin.
• User Registration
To create a user registration form and view, use Django forms.
• Permissions and Authorization
Django’s authentication framework also supports permissions and groups.
36
Namyapriya D, Asst Professor, CSE, KSIT

More Related Content

ODP
The Django Book CH13 Generating Non-HTML Content
PPTX
Introduction to django
PDF
django
PPTX
Django course
PDF
Django workshop : let's make a blog
PDF
Django 1.10.3 Getting started
DOCX
Akash rajguru project report sem v
PPTX
Web development with django - Basics Presentation
The Django Book CH13 Generating Non-HTML Content
Introduction to django
django
Django course
Django workshop : let's make a blog
Django 1.10.3 Getting started
Akash rajguru project report sem v
Web development with django - Basics Presentation

Similar to Module 4 - MIMEs Part 2.pptx. full stack django (20)

PPTX
Tango with django
PDF
Dr. Russell Keith-Magee: Building a development community
PDF
CCCDjango2010.pdf
PDF
The Django Web Application Framework
PDF
Django The Fun Framework
PPTX
Django Architecture Introduction
KEY
Introduction Django
PDF
Django introduction @ UGent
PDF
Django Overview
KEY
Introduction to Django
PDF
GDG Addis - An Introduction to Django and App Engine
PDF
Rapid web application development using django - Part (1)
PPTX
Django Girls Tutorial
PPTX
Django - Python MVC Framework
PDF
بررسی چارچوب جنگو
DOCX
Company Visitor Management System Report.docx
ODP
Django tech-talk
PPTX
Basic Python Django
PDF
Django at Scale
PDF
Django interview Questions| Edureka
Tango with django
Dr. Russell Keith-Magee: Building a development community
CCCDjango2010.pdf
The Django Web Application Framework
Django The Fun Framework
Django Architecture Introduction
Introduction Django
Django introduction @ UGent
Django Overview
Introduction to Django
GDG Addis - An Introduction to Django and App Engine
Rapid web application development using django - Part (1)
Django Girls Tutorial
Django - Python MVC Framework
بررسی چارچوب جنگو
Company Visitor Management System Report.docx
Django tech-talk
Basic Python Django
Django at Scale
Django interview Questions| Edureka
Ad

Recently uploaded (20)

PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
web development for engineering and engineering
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
Geodesy 1.pptx...............................................
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPT
Project quality management in manufacturing
PPTX
OOP with Java - Java Introduction (Basics)
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
DOCX
573137875-Attendance-Management-System-original
UNIT 4 Total Quality Management .pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
CYBER-CRIMES AND SECURITY A guide to understanding
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
web development for engineering and engineering
bas. eng. economics group 4 presentation 1.pptx
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Geodesy 1.pptx...............................................
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Operating System & Kernel Study Guide-1 - converted.pdf
Model Code of Practice - Construction Work - 21102022 .pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Project quality management in manufacturing
OOP with Java - Java Introduction (Basics)
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
573137875-Attendance-Management-System-original
Ad

Module 4 - MIMEs Part 2.pptx. full stack django

  • 1. Module 4 Chapter -11, 12 Namyapriya D, Asst Professor, CSE, KSIT 1
  • 2. MIME types What is MIME (Multipurpose Internet Mail Extensions)?  MIME (Multipurpose Internet Mail Extensions) is an extension of the original Simple Mail Transport Protocol (SMTP) email protocol. It lets users exchange different kinds of data files, including audio, video, images and application programs, over email.  MIME is a standard that extends the format of email to support text in character sets other than ASCII, as well as attachments like images, audio, video, and application programs. MIME types are also used in HTTP to define the type of content being delivered over the web. Namyapriya D, Asst Professor, CSE, KSIT
  • 3. Key Components of MIME Content-Type: Indicates the media type of the resource. Content-Disposition: Provides information about how to handle the file (e.g., inline, attachment). Content-Transfer-Encoding: Describes the encoding used to safely transfer the content over protocols like SMTP. Namyapriya D, Asst Professor, CSE, KSIT
  • 4. Step-by-Step Process 4  File Request: The client (e.g., a web browser) requests a file from the Django application.  Django Response: Django processes the request and prepares to serve the file.  Setting MIME Type: Django determines the MIME type of the file using the mimetypes module or by specifying it directly.  FileResponse: Django creates a FileResponse object, including the MIME type in the Content-Type header.  Send Response: Django sends the response back to the client.  Client Handling: The client receives the response, checks the Content-Type header to determine the file type, and then handles the file accordingly (e.g., displaying it inline if it's an image, prompting for download if it's an attachment). Namyapriya D, Asst Professor, CSE, KSIT
  • 5. Advantages of MIME  MIME has several advantages over SMTP.  Users can send different kinds of binary attachments via email.  Multiple attachments of different types can be included in the same email.  There are no limits on message length.  Multipart messages are supported. 5 Namyapriya D, Asst Professor, CSE, KSIT
  • 6. Interacting with Non-Html content Namyapriya D, Asst Professor, CSE, KSIT
  • 7. Views with Non-Html content  Normally a Django view receives HttpRequest request and returns HttpResponse  By using mime-type in the constructor of HttpResponse, one can return Non-HTML content  One can return image, XML, CSV, PDF etc by including appropriate mime type Namyapriya D, Asst Professor, CSE, KSIT
  • 8. Namyapriya D, Asst Professor, CSE, KSIT
  • 9. What is a csv file?  A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange tabular data. Because it’s a plain text file, it can contain only actual text data—in other words, printable ASCII or Unicode characters.  The structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate each specific data value. Here’s what that structure looks like:  ( Normally, the first line identifies each piece of data—in other words, the name of a data column. Every subsequent line after that is actual data and is limited only by file size constraints.  In general, the separator character is called a delimiter, and the comma is not the only one used. Other popular delimiters include the tab (t), colon (:) and semi-colon (;) characters. Properly parsing a CSV file requires us to know which delimiter is being used. Namyapriya D, Asst Professor, CSE, KSIT
  • 10. Sample CSV File Namyapriya D, Asst Professor, CSE, KSIT
  • 11. Download csv  Python comes with a CSV library, csv. The key to using it with Django is that the csv module’s CSV-creation capability acts on file-like objects, and Django’s HttpResponse objects are file-like objects.  The response gets a special MIME type, text/csv. This tells browsers that the document is a CSV file, rather than an HTML file. If you leave this off, browsers will probably interpret the output as HTML, which will result in ugly, scary gobbledygook in the browser window.  The response gets an additional Content-Disposition header, which contains the name of the CSV file. This filename is arbitrary; call it whatever you want. It’ll be used by browsers in the “Save as…” dialog, etc.  You can hook into the CSV-generation API by passing response as the first argument to csv.writer. The csv.writer function expects a file-like object, and HttpResponse objects fit the bill.  For each row in your CSV file, call writer.writerow, passing it an iterable.  The CSV module takes care of quoting for you, so you don’t have to worry about escaping strings with quotes or commas in them. Pass writerow() your raw strings, and it’ll do the right thing. Namyapriya D, Asst Professor, CSE, KSIT
  • 12. Http content types Namyapriya D, Asst Professor, CSE, KSIT
  • 14. Namyapriya D, Asst Professor, CSE, KSIT
  • 15. Namyapriya D, Asst Professor, CSE, KSIT
  • 16. reportLab – pdf documents generation  ReportLab is an open source toolkit for creating PDF documents from Python. It is a very extensive library with many features, from small texts and geometric figures to large graphics and illustrations, all of which can be included in a PDF.  The first two arguments passed to drawstring indicate the x,y position where the text will appear. Namyapriya D, Asst Professor, CSE, KSIT
  • 17. PDF Generation steps We start by importing the modules and classes. Canvas is used to draw things on the pdf,  initialize a canvas object with the name of the pdf and set the title to be the document title we draw a lines of text that we defined in the list Show the pdf and save Namyapriya D, Asst Professor, CSE, KSIT
  • 18. Namyapriya D, Asst Professor, CSE, KSIT
  • 19. Namyapriya D, Asst Professor, CSE, KSIT
  • 20. Syndication Feed Framework in Django • The Syndication Feed Framework in Django simplifies the process of creating RSS or Atom feeds. Syndication Feed Framework allows you to expose your site's content as feeds, which users can subscribe to and receive updates. How to set Syndication Feed Framework? Define a Feed Class Create a feed class by inheriting from django.contrib.syndication.views.Feed. Define methods to specify the title, link, description, and the items to be included in the feed. 20 Namyapriya D, Asst Professor, CSE, KSIT
  • 21. • What is Atom and RSS feed? RSS: • RSS (Really Simple Syndication) is a web feed type that allows users to access updates from websites or blogs without having to visit each one separately. It allows content creators to share their information in a standardized manner, making it easier for users to subscribe and automatically receive updates. ATOM: • Atom is a standardized web feed format that allows content producers to syndicate their information. Atom, like RSS (Really Simple Syndication), allows users to subscribe to updates from websites or blogs without visiting them individually. Atom was created as an alternative to RSS with the goal of improving extensibility while adopting a more modern approach to web distribution 21 Namyapriya D, Asst Professor, CSE, KSIT
  • 22. Configure URLs Add the feed to your URL configuration to make it accessible via a specific URL. Customize Feed Items You can add more methods to customize the feed items, such as including the author's name, publication date, and categories. 22 Namyapriya D, Asst Professor, CSE, KSIT
  • 23. 23 #feeds.py from django.contrib.syndication.views import Feed from django.urls import reverse from .models import Post class LatestPostsFeed(Feed): title = "Latest Posts" link = "/feeds/latest/" description = "Updates on the latest blog posts." def items(self): return Post.objects.order_by('-published_date')[:5] def item_title(self, item): return item.title def item_description(self, item): return item.summary def item_link(self, item): return reverse('post_detail', args=[item.pk]) def item_author_name(self, item): return item.author.get_full_name() def item_pubdate(self, item): return item.published_date def item_categories(self, item): return [category.name for category in item.categories.all()] Namyapriya D, Asst Professor, CSE, KSIT
  • 24. 24 # urls.py from django.urls import path from .feeds import LatestPostsFeed urlpatterns = [ # other URL patterns path('feeds/latest/', LatestPostsFeed(), name='latest_posts_feed’), ] Namyapriya D, Asst Professor, CSE, KSIT
  • 25. Sitemap Framework in Django To create a sitemap in Django and serve it as an XML file, you'll use Django's built-in sitemap framework. This will generate a sitemap.xml file that helps search engines index your website efficiently. Install and Configure Django Sitemap Framework First, ensure that django.contrib.sitemaps is included in your INSTALLED_APPS in settings.py. Create Sitemap Classes Create a sitemaps.py file where you define your sitemap classes. Each class should inherit from django.contrib.sitemaps.Sitemap. Configure URLs Add the sitemap to your URL configuration to make it accessible via a specific URL. Generate XML Sitemap When you navigate to /sitemap.xml, Django will generate the sitemap in XML format. 25 Namyapriya D, Asst Professor, CSE, KSIT
  • 26. # settings.py INSTALLED_APPS = [ # other installed apps 'django.contrib.sitema ps', ] 26 # sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Post, Author class PostSitemap(Sitemap): changefreq = "weekly" priority = 0.8 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated_date class AuthorSitemap(Sitemap): changefreq = "monthly" priority = 0.6 def items(self): return Author.objects.all() def lastmod(self, obj): return obj.updated_date Namyapriya D, Asst Professor, CSE, KSIT
  • 27. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.example.com/posts/1/</loc> <lastmod>2024-07-09</lastmod> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> <url> <loc>http://www.example.com/posts/2/</loc> <lastmod>2024-07-08</lastmod> <changefreq>weekly</changefreq> <priority>0.8</priority> </url> 27 <url> <loc>http://www.example.com/authors/1/</loc> <lastmod>2024-07-07</lastmod> <changefreq>monthly</changefreq> <priority>0.6</priority> </url> <!-- Additional URLs here --> </urlset> Namyapriya D, Asst Professor, CSE, KSIT
  • 28. # models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) content = models.TextField() updated_date = models.DateTimeField(auto_now=True) is_important = models.BooleanField(default=False) def __str__(self): return self.title 28 class Author(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) bio = models.TextField() updated_date = models.DateTimeField(auto_now=True) def __str__(self): return self.name Namyapriya D, Asst Professor, CSE, KSIT
  • 29. # urls.py from django.contrib import sitemaps from django.contrib.sitemaps.views import sitemap from .sitemaps import PostSitemap, AuthorSitemap sitemaps = { 'posts': PostSitemap, 'authors': AuthorSitemap, } urlpatterns = [ # other URL patterns path('sitemap.xml', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ] 29 Namyapriya D, Asst Professor, CSE, KSIT
  • 30. Cookies and Sessions in Django 30 Namyapriya D, Asst Professor, CSE, KSIT
  • 31. Cookies In Django, cookies are a convenient way to store small amounts of data on the client side. They can be used to maintain stateful information between different requests from the same user. Setting a Cookie Getting a Cookie Deleting a Cookie Secure and HttpOnly Cookies When setting cookies, you can use additional parameters like secure and httponly to enhance security: secure: Ensures the cookie is only sent over HTTPS connections. httponly: Ensures the cookie is only accessible by the server, not via JavaScript. 31 Namyapriya D, Asst Professor, CSE, KSIT
  • 32. # views.py from django.http import HttpResponse def cookie_example_view(request): response = HttpResponse("Cookie Example") # Set a cookie response.set_cookie('example_cookie', 'cookie_value', max_age=3600, secure=True, httponly=True) 32 # Get a cookie cookie_value = request.COOKIES.get('example_cookie') if cookie_value: response.write(f'Cookie Value: {cookie_value}n') else: response.write('Cookie Not Foundn') # Delete a cookie response.delete_cookie('example_cookie') return response Namyapriya D, Asst Professor, CSE, KSIT
  • 33. Sessions In Django, sessions are used to store and retrieve arbitrary data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, allowing you to store data on the server side and associate it with a session ID that is sent to the client via a cookie. This approach enhances security and scalability. Configuring Sessions in Django Django supports several session backends: Database-backed sessions Cached sessions File-based sessions Cookie-based sessions Custom backends 33 Namyapriya D, Asst Professor, CSE, KSIT
  • 34. # views.py from django.shortcuts import render from django.http import HttpResponse def set_session_view(request): request.session['username'] = 'john_doe' request.session['email'] = 'john_doe@example.com' return HttpResponse("Session data set") def get_session_view(request): username = request.session.get('username', 'Guest') email = request.session.get('email', 'No email provided') return HttpResponse(f"Hello, {username}. Your email is {email}.") 34 def delete_session_view(request): try: del request.session['username'] del request.session['email'] except KeyError: pass return HttpResponse("Session data cleared") def clear_session_view(request): request.session.flush() return HttpResponse("All session data cleared") Namyapriya D, Asst Professor, CSE, KSIT
  • 35. Users and Authentication Django provides a robust authentication system out of the box, including user login, logout, password management, and permissions. Setting Up Authentication Ensure that django.contrib.auth and django.contrib.contenttypes are included in your INSTALLED_APPS.  Creating a User You can create a user using the Django shell or programmatically within your views. • User Login Django provides a login function to log users in. • User Logout Django provides a logout function to log users out. 35 Namyapriya D, Asst Professor, CSE, KSIT
  • 36.  Password Management Django includes built-in views for password management. First, ensure the URL configuration includes Django’s authentication URLs. Django provides the following built-in views for password management: PasswordChangeView and PasswordChangeDoneView PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and PasswordResetCompleteView • Custom User Model For more flexibility, you can create a custom user model by extending AbstractBaseUser and PermissionsMixin. • User Registration To create a user registration form and view, use Django forms. • Permissions and Authorization Django’s authentication framework also supports permissions and groups. 36 Namyapriya D, Asst Professor, CSE, KSIT