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

HarshithaP46 11 views 36 slides Jul 30, 2024
Slide 1
Slide 1 of 36
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36

About This Presentation

M4


Slide Content

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.sitemaps ', ] 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

C ookies and Sessions in Django 30 Namyapriya D, Asst Professor, CSE, KSIT

C ookies 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 Found\n') # Delete a cookie response.delete_cookie (' example_cookie ') return response Namyapriya D, Asst Professor, CSE, KSIT

S essions 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'] = '[email protected]' 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