Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Introduction to Django v2
Search
Kien Nguyen
November 20, 2013
Programming
0
100
Introduction to Django v2
Introduction to django and deploy to self-hosted server
Kien Nguyen
November 20, 2013
Tweet
Share
More Decks by Kien Nguyen
See All by Kien Nguyen
Introduction
kiennt
0
47
Facebook Login Security
kiennt
0
52
Clean code
kiennt
8
410
Introduction to Django
kiennt
0
100
Unix_Process.pdf
kiennt
2
8.1k
Happiness
kiennt
1
430
RTMP and RTMPE protocols
kiennt
2
620
Other Decks in Programming
See All in Programming
生成AIコーディングとの向き合い方、AIと共創するという考え方 / How to deal with generative AI coding and the concept of co-creating with AI
seike460
PRO
1
340
ReadMoreTextView
fornewid
1
490
ruby.wasmで多人数リアルタイム通信ゲームを作ろう
lnit
2
320
Benchmark
sysong
0
280
プロダクト志向なエンジニアがもう一歩先の価値を目指すために意識したこと
nealle
0
120
エンジニア向け採用ピッチ資料
inusan
0
180
“いい感じ“な定量評価を求めて - Four Keysとアウトカムの間の探求 -
nealle
0
340
Result型で“失敗”を型にするPHPコードの書き方
kajitack
4
550
Cursor AI Agentと伴走する アプリケーションの高速リプレイス
daisuketakeda
1
130
Hypervel - A Coroutine Framework for Laravel Artisans
albertcht
1
110
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
49
32k
来たるべき 8.0 に備えて React 19 新機能と React Router 固有機能の取捨選択とすり合わせを考える
oukayuka
2
880
Featured
See All Featured
Keith and Marios Guide to Fast Websites
keithpitt
411
22k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
130
19k
GraphQLとの向き合い方2022年版
quramy
49
14k
Building a Modern Day E-commerce SEO Strategy
aleyda
42
7.4k
Optimising Largest Contentful Paint
csswizardry
37
3.3k
[RailsConf 2023] Rails as a piece of cake
palkan
55
5.6k
Fashionably flexible responsive web design (full day workshop)
malarkey
407
66k
A Tale of Four Properties
chriscoyier
160
23k
How STYLIGHT went responsive
nonsquared
100
5.6k
Building Applications with DynamoDB
mza
95
6.5k
Mobile First: as difficult as doing things right
swwweet
223
9.7k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
229
22k
Transcript
Introduction to Django Kien Nguyen Trung
Kien Nguyen Trung github.com/kiennt kiennt.com
What is django
Django is high-level Python Web framework that encourages rapid development
and clean, pragmatics design.
Philosophy Rapid Development Loosely coupled Reusable Applications Dont Repeat Yourself
(DRY)
Features Object Relational Mapping (ORM) Automatic admin interface Elegent URL
design Template system
Architecture
Model - View - Template Model - what things are
View - how things are processed Template - How things are presented
Models import datetime from django.db import models from django.utils import
timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
Represents the DB objects BEGIN; CREATE TABLE "codecamp_question" ( "id"
integer NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL ) ; CREATE TABLE "codecamp_choice" ( "id" integer NOT NULL PRIMARY KEY, "question_id" integer NOT NULL REFERENCES "codecamp_question" ("id"), "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ) ; COMMIT;
ORM latest_question_list = Question.objects.order_by('-pub_date')[:5] q = Question.objects.get(pk=question_id) selected_choice = q.choice_set.get(pk=choice_id)
selected_choice.votes += 1 selected_choice.save() Never write SQL - unless you really need
Views Where all magic happens Normally Keep your logic in
the model Process model instances Render HTML
Views def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice
= p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('results', args=(p.id,)))
Templates Separate design from code Separate designer from code Separate
design from developers
index.html {% if latest_question_list %} <ul> {% for question in
latest_question_list %} <li> <a href="{% url 'detail' question.id %}"> {{ question.question_text }} </a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,
HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context)
detail.html <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message
}}</strong></p> {% endif %} <form action="{% url 'vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}"> {{ choice.choice_text }} </label><br /> {% endfor %} <input type="submit" value="Vote" /> </form>
views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect,
HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
Security advantages No raw SQL from users - we deal
with models and queries Automatic HTML parsing - no XSS attacks CSRF protection - no replay of forms by other code
URLs from django.conf.urls import patterns, include, url from codecamp import
views # for admin page from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', views.index, name='index'), url(r'^polls/(?P<question_id>\d+)/$', views.detail, name='detail'), url(r'^polls/(?P<question_id>\d+)/results/$', views.results, name='results'), url(r'^polls/(?P<question_id>\d+)/vote/$', views.vote, name='vote'), url(r'^admin/', include(admin.site.urls)), ) URLs map to views (view Regular expressions)
http://example.com/ http://example.com/polls/1 http://example.com/polls/1/result http://example.com/polls/1/vote
Views are python function from django.shortcuts import render, get_object_or_404 from
django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from codecamp.models import Question def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', { 'question': question })
Admin interface class ChoiceInline(admin.StackedInline): model = models.Choice extra = 4
class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ] search_fields = ['question_text'] list_display = ('question_text', 'pub_date', 'was_published_recently') inlines = [ChoiceInline] admin.site.register(models.Question, QuestionAdmin)
Admin interface class MemberAdmin(UserAdmin): list_filter = ('is_admin', ) filter_horizontal =
() fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('email', )}), ) search_fields = ('email', 'username') list_display = ('username', 'email', 'is_admin', 'date_joined') list_per_page = 50 admin.site.register(models.Member, MemberAdmin) admin.site.register(models.Question, QuestionAdmin)
Other features Forms Generic Views User management Advance queries
manage.py shell: start up a python shell with your django
project loaded in test: run you unit test runserver: run built in server for python app syncdb: create SQL for your models
Deploy
requirements zero downtime can rollback to old deployments
tools fabric to distribute code to server uWSGI - similar
gunicorn but write in C, and support a lot of features
nginx uWSGI Django App Django App Django App
folders structure current -> /srv/sample_app/releases/c31245.... /srv/sample_app/ /releases /c31245 /d98818
deployment with rollback each release folder is snapshot of a
git commit each release contain it own virtual environment isolate releases about python package, not system package !?
zero downtime uWSIG support autoload by watching changing of a
file or folder when deploy new release write to new file
def release_commit(commit): code_dir = '/srv/simpleprints/base' new_release_dir = '/srv/simpleprints/releases/%s' % commit
# create new release dir run('rm -rf %s' % new_release_dir) run('mkdir -p %s' % new_release_dir) with cd(code_dir): run('git archive %s | tar -C %s -xf -' % (commit, new_release_dir)) remove_old_release() # create virtualenv with cd(new_release_dir): run('virtualenv venv') # install with virtualenv('%s/venv/' % new_release_dir): run('pip install -r %s/requirements.txt' % new_release_dir) run('chown -R kiennt %s' % new_release_dir) reload_uwsgi_for_commit(commit)
QA