SlideShare une entreprise Scribd logo
1  sur  44
Rajan K Upadhyay 
1
Programming Languages 
Popular 
Programming Languages > 500 
Frameworks > 90000 
at least what Wikipedia says 
What Really I should Learn ? 
2
Lets go back & check last software you developed 
• Without Alternatives, how difficult it was to estimate ? 
• Ideas -> Conceptualization -> Enterprise Ready was full of Effort, Pain, 
Time waste, Complexity & Change !!! 
• Was my system adaptive to the change that business demand? … God 
it was really nightmare to maintain the code …. 
• What is the time it took to get the customer from a frustrated to a happy 
customer ? also the time it took to develop version 2, with different 
requirements & scale: 
3
Time is an essence 
Python : Django A complete framework 
A Web Framework that shortens the Time it takes to develop 
software in at least an Order of Magnitude. while also 
tremendously minimizing Effort Pain, Time waste, Complexity, 
Cost of change & more 
9/1/2014 4
Python: Language of Best 
• By The organizations attracting the best Programmers 
in the world 
Google, NASA, MIT 
5
• “The framework for perfectionists 
with deadlines” 
• Model-Template-View ( MTV ) not as 
complex as MVC 
• Flexible template language that can 
be used to generate HTML, CSV, 
Email or any other format 
• Includes ORM that supports many 
databases – Postgresql, MySQL, 
Oracle, SQLite 
• Lots of extras included – 
middleware, csrf protections, 
sessions, caching, authentication 
• Written in C – high 
performance, ability to link to 
C libraries for extensions 
• Interpreted script language 
compiled on the fly into byte 
code 
• Easier to read coding 
standards – whitespace 
sensitive 
• Object Oriented 
WHY 
6
Scalability 
• Django runs on regular web servers, such as 
Apache, Lighty or Nginx, using a built-in Python 
or WSGI adapter 
• This makes it very lightweight & scalable, as any 
LAMP deployment 
o There are examples of sites that handle MM reqs/hour, using less 
than 10 servers 
7
IT Acceptance 
• IT environments today are mostly familiar with 
Java 
• Solution: use Jython that compiles Python to 
bytecode 
o Package a Django project as .war 
o Sun constantly improves Jython & maintains compatibility /w 
Django 
8
DJANGO: 
QUICK OVERVIEW 
9
Project File Structure 
django-admin.py startproject 
<PROJECT_ROOT> 
manage.py 
<PROJECT_DIR> 
__init__.py 
settings.py 
urls.py 
wsgi.py 
10
settings.py 
• Defines settings used by a Django application 
• Referenced by wsgi.py to bootstrap the project 
loading 
• Techniques for managing dev vs prod settings: 
o Create settings-dev.py and settings-prod.py and use symlink to link 
settings.py to the correct settings 
o Factor out common settings into base-settings.py and import. Use 
conditionals to load correct settings based on DEBUG or other setting 
11
Sample Settings… 
DEBUG = True 
TEMPLATE_DEBUG = True 
ALLOWED_HOSTS = [] 
# Application definition 
INSTALLED_APPS = ( 
'django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
) 
12
Django Apps 
• Reusable modules 
• django-admin.py startapp <app_name> 
• Creates stub layout: 
<APP_ROOT> 
admin.py 
models.py 
templates (directory) 
tests.py 
views.py 
urls.py 
13
Django Models 
• Defined in models.py 
• Typically inherit from django.db.models.Model 
Example Model: 
from django.db import models 
class TestModel(models.Model): 
name = models.CharField(max_length = 20) 
age = models.IntegerField() 
14
Models (cont’d) 
• Default is to set NOT NULL on all fields. Override by 
adding null = True to field definition: 
name = models.CharField(max_length=20, null = 
True) 
• Relationships defined through special field types: 
models.OneToOneField(model) 
models.ForeignKey(model) 
models.ManyToManyField(model) 
15
Models (cont’) 
• Need Nulls in a Boolean Field? Use 
models.NullBooleanField() 
• Set Default value with “default”: 
count = models.IntegerField(default = 0) 
• Use a inner Meta class to define additional options, 
especially useful for abstract classes: 
class TestModel(models.Model): 
class Meta: 
abstract = True 
16
Model Methods 
• model.save(self, *args, **kwargs) 
• model.delete(self, *args, **kwargs) 
• model.get_absolute_url(self) 
• model.__str__(self) [Python 3] 
model.__unicode__(self) [Python 2] 
• Override with super(MODEL, self).save(*args, 
**kwargs) 
17
Activating a Model 
• Add the app to INSTALLED_APPS in settings.py 
• Run manage.py validate 
• Run manage.py syncdb 
• Migrations 
o Write custom script or manually handle migrations 
o Use South 
18
Selecting Objects 
• Models include a default manager called objects 
• Manager methods allow selecting all or some 
instances 
Question.objects.all() 
Question.objects.get(pk = 1) 
Use try block, throws DoesNotExist 
exception if no match 
Question.objects.filter(created_date__lt = ‘2014- 
01-01’) 
• Returns QuerySet 
19
Introspecting Legacy 
Models 
• manage.py inspectdb 
• Cut and paste generated code into models.py – 
Easy!! 
20
Full Sample 
from django.db import models 
from datetime import datetime 
class TimestampedModel(models.Model): 
created_datetime = models.DateTimeField() 
updated_datetime = models.DateTimeField() 
def save(self, *args, **kwargs): 
if self.id is None: 
self.created_datetime = datetime.now() 
updated_datetime = datetime.now() 
super(TimestampedModel,self).save(*args, **kwargs) 
class Meta: 
abstract = True 
21
Full Sample (cont’d) 
class Question(TimestampedModel): 
question_text = models.CharField(max_length = 200) 
def __str__(self): 
return self.question_text 
22
Function vs. Class Views 
• Django allows two styles of views – functions or class 
based views 
• Functions – take a request object as the first 
parameter and must return a response object 
• Class based views – allow CRUD operations with 
minimal code. Can inherit from multiple generic 
view classes (i.e. Mixins) 
23
Sample – Viewing a List 
of Questions 
• Function based: 
from .models import Question 
from django.shortcuts import render_to_response 
def question_list(request): 
questions = Question.objects.all() 
return render_to_response(‘question_list.html’, { 
‘questions’:questions}) 
24
Quick CRUD Operations 
with Generic Views 
• ListView 
• UpdateView 
• CreateView 
• If Model is specified, automagically creates a 
matching ModelForm 
• Form will save the Model if data passes validation 
• Override form_valid() method to provide custom 
logic (i.e sending email or setting additional fields) 
25
Sample – As Class Based 
View 
from .models import Question 
from django.views.generic import ListView 
class QuestionList(ListView): 
model = Question 
context_object_name = ‘questions’ 
26
Django Templates 
• Very simple syntax: 
variables = {{variable_name}} 
template tags = {%tag%} 
• Flexible – can be used to render html, text, csv, 
email, you name it! 
• Dot notation – template engine attempts to resolve 
by looking for matching attributes, hashes and 
methods 
27
Question List Template 
<!doctype html> 
<html lang=en> 
<head> 
<meta charset=utf-8> 
<title>List of Questions</title> 
</head> 
<body> 
{%if questions%} 
<ul> 
{%for q in questions%} 
<li>{{q.question_text}}</li> 
{%endfor%} 
</ul> 
{%else%} 
<p>No questions have been defined</p> 
{%endif%} 
</body> 
</html> 
28
urls.py 
• Defines routes to send urls to various views 
• Can use regular expressions 
• Extract parameters from a url and pass to the view 
as a named parameter: 
r(‘^question/(?P<question_id>d+)/$’,’views.question_ 
detail’) 
• Extensible – urls.py can include additional url files 
from apps: 
r(‘^question/’,include(question.urls)) 
29
Forms in Django 
• django.forms provides a class to build HTML forms 
and validation. Example: 
from django import forms 
class EditQuestionForm(forms.Form): 
question_text = forms.CharField(max_length = 200) 
• Often redundant when creating forms that work on 
a single model 
30
ModelForms 
• Automatically generate a form from a model. 
• Handles saving a bound model 
• Can specify fields to be included or excluded in the 
form 
• Sample: 
from django.forms import ModelForm 
from .models import Question 
class QuestionForm(ModelForm): 
class Meta: 
model = Question 
fields = [‘question_text’] 
31
Using a ModelForm 
• Create an instance of an empty form: 
form = QuestionForm() 
• Create a form to update an existing instance of a 
model: 
question = Question.objects.get(pk = 1) 
form = QuestionForm(instance = question) 
• Pass the form into the template and use the form 
methods to render the form: 
form.as_p 
form.as_ul 
form.<field_name> 
form.<field_name>.errors 
32
Request & Response 
• Request object encapsulate the request and provide 
access to a number of attributes and methods for 
accessing cookies, sessions, the logged in user object, 
meta data (i.e environment variables), 
• Response objects are returned to the browser. Can set 
content type, content length, response does not have 
to return HTML or a rendered template 
• Special response types allow for common functionality: 
HttpResponeRedirect 
Http404 
HttpStreamingResponse 
33
Django Extras 
• CRSF Middleware – enabled by default. Include 
template tag in all forms: 
{%csrf_token%} 
• Authentication 
• Caching 
• Sessions 
• Messages 
• Email 
• Logging 
34
Auth Decorators 
• Live in django.contrib.auth.decorators 
• login_required 
@login_required 
def function_view(request): 
…. 
• user_passes_test (can be used with lambda 
functions for real power) – 
@user_passes_test(lambda u: u.is_staff) 
def function_view(request): 
… 
• has_perms – test for user permissions 
35
Demo: 30 mins 
Let’s develop an Release Tracking system 
o Create Business Data Model 
o Database CRUD Operations to manage/add/edit/delete Releases 
o Rich Web UI (search, filters, last actions) 
o Users management (permissions, groups), User logging, Access level 
control 
o Scalable deployment (any # of users) 
36
Step1: Settings: Connect to 
Database 
• DATABASES = { 
• 'default': { 
• 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 
• 'NAME': ‘release', # Or path to database file if using sqlite3. 
• # The following settings are not used with sqlite3: 
• 'USER': 'root', 
• 'PASSWORD': ‘', 
• 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 
• 'PORT': '', # Set to empty string for default. 
• } 
• } 
37
Step2: Data Model 
from django.db import models 
class Environment(models.Model): 
environment = models.CharField(null=False, max_length=200) 
# Create your models here. 
class Release(models.Model): 
dateCreated = models.DateField(null=False, auto_now_add=True) 
releaseDate = models.DateField(null=False) 
releaseTitle = models.CharField(null=False, max_length=200) 
releaseEnv = models.ForeignKey(Environment) 
38
Step3: Sync DB 
django_manage.py syncdb 
Whoooo ---- Your DB tables are created 
What Next  Lets create some Interfaces 
39
Register Admin 
from django.db import models 
from django.contrib import admin 
class Environment(models.Model): 
environment = models.CharField(null=False, max_length=200) 
# Create your models here. 
class Release(models.Model): 
dateCreated = models.DateField(null=False, auto_now_add=True) 
releaseDate = models.DateField(null=False) 
releaseTitle = models.CharField(null=False, max_length=200) 
releaseEnv = models.ForeignKey(Environment) 
admin.site.register(Release) 
admin.site.register(Environment) 
40
Admin Interface Ready 
• Run  manage.py runserver 8000 
http://127.0.0.1:8000/admin/ 
- Entire CRUD Operation for 
Models 
- User Authentication, Groups, 
Access Level & control 
- User Log 
- Multisite & Multi Application 
41
Views: Front End 
• Setup a URL pattern : Edit url.py 
url(r'^$', 'ReleaseTracker.views.home', name='home'), 
. Create view as home 
# Create your views here. 
from django.http import HttpResponse 
from rtracker.models import Environment 
from rtracker.models import Release 
from django.shortcuts import get_object_or_404, render_to_response 
from django.template import RequestContext 
def home(request): 
releaseitems = Release.objects.all() 
return render_to_response('home.html', {'releaseitems': releaseitems}, 
context_instance=RequestContext(request)) 
42
Create Template 
Create home.html in templates 
<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
</head> 
<body> 
{# you can include templates #} 
{% include "nav.html" %} 
{% for release in releaseitems %} 
{{release.releaseTitle}} 
{% endfor %} 
</body> 
</html> 
43
FRONT END 
• Open http://127.0.0.1:8000/ 
You will be able to see the model data 
44

Contenu connexe

Tendances

Django and Mongoengine
Django and MongoengineDjango and Mongoengine
Django and Mongoengineaustinpublic
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptThéodore Biadala
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applicationsHassan Abid
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Phpfunkatron
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoLakshman Prasad
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.jsBert Wijnants
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Iakiv Kramarenko
 

Tendances (20)

Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
 
Django Mongodb Engine
Django Mongodb EngineDjango Mongodb Engine
Django Mongodb Engine
 
Django and Mongoengine
Django and MongoengineDjango and Mongoengine
Django and Mongoengine
 
Django
DjangoDjango
Django
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Django a whirlwind tour
Django   a whirlwind tourDjango   a whirlwind tour
Django a whirlwind tour
 
Django
DjangoDjango
Django
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
In-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascriptIn-depth changes to Drupal 8 javascript
In-depth changes to Drupal 8 javascript
 
Django for mobile applications
Django for mobile applicationsDjango for mobile applications
Django for mobile applications
 
Intro To Mvc Development In Php
Intro To Mvc Development In PhpIntro To Mvc Development In Php
Intro To Mvc Development In Php
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Building Pluggable Web Applications using Django
Building Pluggable Web Applications using DjangoBuilding Pluggable Web Applications using Django
Building Pluggable Web Applications using Django
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Viking academy backbone.js
Viking academy  backbone.jsViking academy  backbone.js
Viking academy backbone.js
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
 

Similaire à Tango with django

django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030Kevin Wu
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics PresentationShrinath Shenoy
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| EdurekaEdureka!
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگوrailsbootcamp
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklistMax Kleiner
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Udit Gangwani
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletonGeorge Nguyen
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django FrameworkRicardo Soares
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAEWinston Chen
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web FrameworkDavid Gibbons
 

Similaire à Tango with django (20)

django_introduction20141030
django_introduction20141030django_introduction20141030
django_introduction20141030
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
 
templates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtratemplates in Django material : Training available at Baabtra
templates in Django material : Training available at Baabtra
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
 
Discovering Django - zekeLabs
Discovering Django - zekeLabsDiscovering Django - zekeLabs
Discovering Django - zekeLabs
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
 
Django Documentation
Django DocumentationDjango Documentation
Django Documentation
 
A gentle intro to the Django Framework
A gentle intro to the Django FrameworkA gentle intro to the Django Framework
A gentle intro to the Django Framework
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
 
An Introduction to Django Web Framework
An Introduction to Django Web FrameworkAn Introduction to Django Web Framework
An Introduction to Django Web Framework
 

Plus de Rajan Kumar Upadhyay

Speed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times fasterSpeed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times fasterRajan Kumar Upadhyay
 
Features of globalization and india in global economy
Features of globalization and india in global economyFeatures of globalization and india in global economy
Features of globalization and india in global economyRajan Kumar Upadhyay
 
State of Retail E-commerce In India
State of Retail E-commerce In IndiaState of Retail E-commerce In India
State of Retail E-commerce In IndiaRajan Kumar Upadhyay
 
Hadoop & distributed cloud computing
Hadoop & distributed cloud computingHadoop & distributed cloud computing
Hadoop & distributed cloud computingRajan Kumar Upadhyay
 
Business Intelligence & its Best Practices
Business Intelligence & its Best PracticesBusiness Intelligence & its Best Practices
Business Intelligence & its Best PracticesRajan Kumar Upadhyay
 

Plus de Rajan Kumar Upadhyay (8)

Speed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times fasterSpeed Up RPA Deployment 10 times faster
Speed Up RPA Deployment 10 times faster
 
RPA & Supply Chain
RPA  &  Supply ChainRPA  &  Supply Chain
RPA & Supply Chain
 
Features of globalization and india in global economy
Features of globalization and india in global economyFeatures of globalization and india in global economy
Features of globalization and india in global economy
 
State of Retail E-commerce In India
State of Retail E-commerce In IndiaState of Retail E-commerce In India
State of Retail E-commerce In India
 
Hadoop & distributed cloud computing
Hadoop & distributed cloud computingHadoop & distributed cloud computing
Hadoop & distributed cloud computing
 
Nextop Cloud computing Platform
Nextop Cloud computing PlatformNextop Cloud computing Platform
Nextop Cloud computing Platform
 
Data analysis & decisions
Data analysis & decisionsData analysis & decisions
Data analysis & decisions
 
Business Intelligence & its Best Practices
Business Intelligence & its Best PracticesBusiness Intelligence & its Best Practices
Business Intelligence & its Best Practices
 

Dernier

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Tango with django

  • 2. Programming Languages Popular Programming Languages > 500 Frameworks > 90000 at least what Wikipedia says What Really I should Learn ? 2
  • 3. Lets go back & check last software you developed • Without Alternatives, how difficult it was to estimate ? • Ideas -> Conceptualization -> Enterprise Ready was full of Effort, Pain, Time waste, Complexity & Change !!! • Was my system adaptive to the change that business demand? … God it was really nightmare to maintain the code …. • What is the time it took to get the customer from a frustrated to a happy customer ? also the time it took to develop version 2, with different requirements & scale: 3
  • 4. Time is an essence Python : Django A complete framework A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more 9/1/2014 4
  • 5. Python: Language of Best • By The organizations attracting the best Programmers in the world Google, NASA, MIT 5
  • 6. • “The framework for perfectionists with deadlines” • Model-Template-View ( MTV ) not as complex as MVC • Flexible template language that can be used to generate HTML, CSV, Email or any other format • Includes ORM that supports many databases – Postgresql, MySQL, Oracle, SQLite • Lots of extras included – middleware, csrf protections, sessions, caching, authentication • Written in C – high performance, ability to link to C libraries for extensions • Interpreted script language compiled on the fly into byte code • Easier to read coding standards – whitespace sensitive • Object Oriented WHY 6
  • 7. Scalability • Django runs on regular web servers, such as Apache, Lighty or Nginx, using a built-in Python or WSGI adapter • This makes it very lightweight & scalable, as any LAMP deployment o There are examples of sites that handle MM reqs/hour, using less than 10 servers 7
  • 8. IT Acceptance • IT environments today are mostly familiar with Java • Solution: use Jython that compiles Python to bytecode o Package a Django project as .war o Sun constantly improves Jython & maintains compatibility /w Django 8
  • 10. Project File Structure django-admin.py startproject <PROJECT_ROOT> manage.py <PROJECT_DIR> __init__.py settings.py urls.py wsgi.py 10
  • 11. settings.py • Defines settings used by a Django application • Referenced by wsgi.py to bootstrap the project loading • Techniques for managing dev vs prod settings: o Create settings-dev.py and settings-prod.py and use symlink to link settings.py to the correct settings o Factor out common settings into base-settings.py and import. Use conditionals to load correct settings based on DEBUG or other setting 11
  • 12. Sample Settings… DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) 12
  • 13. Django Apps • Reusable modules • django-admin.py startapp <app_name> • Creates stub layout: <APP_ROOT> admin.py models.py templates (directory) tests.py views.py urls.py 13
  • 14. Django Models • Defined in models.py • Typically inherit from django.db.models.Model Example Model: from django.db import models class TestModel(models.Model): name = models.CharField(max_length = 20) age = models.IntegerField() 14
  • 15. Models (cont’d) • Default is to set NOT NULL on all fields. Override by adding null = True to field definition: name = models.CharField(max_length=20, null = True) • Relationships defined through special field types: models.OneToOneField(model) models.ForeignKey(model) models.ManyToManyField(model) 15
  • 16. Models (cont’) • Need Nulls in a Boolean Field? Use models.NullBooleanField() • Set Default value with “default”: count = models.IntegerField(default = 0) • Use a inner Meta class to define additional options, especially useful for abstract classes: class TestModel(models.Model): class Meta: abstract = True 16
  • 17. Model Methods • model.save(self, *args, **kwargs) • model.delete(self, *args, **kwargs) • model.get_absolute_url(self) • model.__str__(self) [Python 3] model.__unicode__(self) [Python 2] • Override with super(MODEL, self).save(*args, **kwargs) 17
  • 18. Activating a Model • Add the app to INSTALLED_APPS in settings.py • Run manage.py validate • Run manage.py syncdb • Migrations o Write custom script or manually handle migrations o Use South 18
  • 19. Selecting Objects • Models include a default manager called objects • Manager methods allow selecting all or some instances Question.objects.all() Question.objects.get(pk = 1) Use try block, throws DoesNotExist exception if no match Question.objects.filter(created_date__lt = ‘2014- 01-01’) • Returns QuerySet 19
  • 20. Introspecting Legacy Models • manage.py inspectdb • Cut and paste generated code into models.py – Easy!! 20
  • 21. Full Sample from django.db import models from datetime import datetime class TimestampedModel(models.Model): created_datetime = models.DateTimeField() updated_datetime = models.DateTimeField() def save(self, *args, **kwargs): if self.id is None: self.created_datetime = datetime.now() updated_datetime = datetime.now() super(TimestampedModel,self).save(*args, **kwargs) class Meta: abstract = True 21
  • 22. Full Sample (cont’d) class Question(TimestampedModel): question_text = models.CharField(max_length = 200) def __str__(self): return self.question_text 22
  • 23. Function vs. Class Views • Django allows two styles of views – functions or class based views • Functions – take a request object as the first parameter and must return a response object • Class based views – allow CRUD operations with minimal code. Can inherit from multiple generic view classes (i.e. Mixins) 23
  • 24. Sample – Viewing a List of Questions • Function based: from .models import Question from django.shortcuts import render_to_response def question_list(request): questions = Question.objects.all() return render_to_response(‘question_list.html’, { ‘questions’:questions}) 24
  • 25. Quick CRUD Operations with Generic Views • ListView • UpdateView • CreateView • If Model is specified, automagically creates a matching ModelForm • Form will save the Model if data passes validation • Override form_valid() method to provide custom logic (i.e sending email or setting additional fields) 25
  • 26. Sample – As Class Based View from .models import Question from django.views.generic import ListView class QuestionList(ListView): model = Question context_object_name = ‘questions’ 26
  • 27. Django Templates • Very simple syntax: variables = {{variable_name}} template tags = {%tag%} • Flexible – can be used to render html, text, csv, email, you name it! • Dot notation – template engine attempts to resolve by looking for matching attributes, hashes and methods 27
  • 28. Question List Template <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>List of Questions</title> </head> <body> {%if questions%} <ul> {%for q in questions%} <li>{{q.question_text}}</li> {%endfor%} </ul> {%else%} <p>No questions have been defined</p> {%endif%} </body> </html> 28
  • 29. urls.py • Defines routes to send urls to various views • Can use regular expressions • Extract parameters from a url and pass to the view as a named parameter: r(‘^question/(?P<question_id>d+)/$’,’views.question_ detail’) • Extensible – urls.py can include additional url files from apps: r(‘^question/’,include(question.urls)) 29
  • 30. Forms in Django • django.forms provides a class to build HTML forms and validation. Example: from django import forms class EditQuestionForm(forms.Form): question_text = forms.CharField(max_length = 200) • Often redundant when creating forms that work on a single model 30
  • 31. ModelForms • Automatically generate a form from a model. • Handles saving a bound model • Can specify fields to be included or excluded in the form • Sample: from django.forms import ModelForm from .models import Question class QuestionForm(ModelForm): class Meta: model = Question fields = [‘question_text’] 31
  • 32. Using a ModelForm • Create an instance of an empty form: form = QuestionForm() • Create a form to update an existing instance of a model: question = Question.objects.get(pk = 1) form = QuestionForm(instance = question) • Pass the form into the template and use the form methods to render the form: form.as_p form.as_ul form.<field_name> form.<field_name>.errors 32
  • 33. Request & Response • Request object encapsulate the request and provide access to a number of attributes and methods for accessing cookies, sessions, the logged in user object, meta data (i.e environment variables), • Response objects are returned to the browser. Can set content type, content length, response does not have to return HTML or a rendered template • Special response types allow for common functionality: HttpResponeRedirect Http404 HttpStreamingResponse 33
  • 34. Django Extras • CRSF Middleware – enabled by default. Include template tag in all forms: {%csrf_token%} • Authentication • Caching • Sessions • Messages • Email • Logging 34
  • 35. Auth Decorators • Live in django.contrib.auth.decorators • login_required @login_required def function_view(request): …. • user_passes_test (can be used with lambda functions for real power) – @user_passes_test(lambda u: u.is_staff) def function_view(request): … • has_perms – test for user permissions 35
  • 36. Demo: 30 mins Let’s develop an Release Tracking system o Create Business Data Model o Database CRUD Operations to manage/add/edit/delete Releases o Rich Web UI (search, filters, last actions) o Users management (permissions, groups), User logging, Access level control o Scalable deployment (any # of users) 36
  • 37. Step1: Settings: Connect to Database • DATABASES = { • 'default': { • 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. • 'NAME': ‘release', # Or path to database file if using sqlite3. • # The following settings are not used with sqlite3: • 'USER': 'root', • 'PASSWORD': ‘', • 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. • 'PORT': '', # Set to empty string for default. • } • } 37
  • 38. Step2: Data Model from django.db import models class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) 38
  • 39. Step3: Sync DB django_manage.py syncdb Whoooo ---- Your DB tables are created What Next  Lets create some Interfaces 39
  • 40. Register Admin from django.db import models from django.contrib import admin class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) admin.site.register(Release) admin.site.register(Environment) 40
  • 41. Admin Interface Ready • Run  manage.py runserver 8000 http://127.0.0.1:8000/admin/ - Entire CRUD Operation for Models - User Authentication, Groups, Access Level & control - User Log - Multisite & Multi Application 41
  • 42. Views: Front End • Setup a URL pattern : Edit url.py url(r'^$', 'ReleaseTracker.views.home', name='home'), . Create view as home # Create your views here. from django.http import HttpResponse from rtracker.models import Environment from rtracker.models import Release from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext def home(request): releaseitems = Release.objects.all() return render_to_response('home.html', {'releaseitems': releaseitems}, context_instance=RequestContext(request)) 42
  • 43. Create Template Create home.html in templates <!DOCTYPE html> <html> <head> <title></title> </head> <body> {# you can include templates #} {% include "nav.html" %} {% for release in releaseitems %} {{release.releaseTitle}} {% endfor %} </body> </html> 43
  • 44. FRONT END • Open http://127.0.0.1:8000/ You will be able to see the model data 44