Posts

Showing posts from August, 2015

How Django Works (5) Class Based View

Why Class-based Views As is discussed in series 4 , with URL resolution, Django maps an URL to a given view function based on regular expression. So theoretically, function views would work just fine, because we have all the information we need to process a request, as is shown in the example below. from django.http import HttpResponse import datetime def current_datetime (request): now = datetime.datetime.now() html = "<html><body>It is now %s .</body></html>" % now return HttpResponse(html) So Why Bother With Class-based Views I think there are two major reasons: 1) to organize code related to specific HTTP methods (GET, POST, etc), so they can be addressed by separate methods instead of conditional branching in a big function; 2) to use mix-in, inheritance, and built-in views to reduce the boilerplate code. How Class-based Views Work Everything starts with base class View (site-packages\django\views\generic

Python Class Method and Class Only Method

In this post, I will be discussing Python method especially class method. Example class Foo : def bar_inst ( self ): print ( self , "This is bar_inst" ) @staticmethod def bar_static (): print ( "This is bar_static" ) @classmethod def bar_class (cls): print (cls, "This is bar_class" ) >>> foo = Foo() >>> foo.bar_inst <bound method Foo.bar_inst of <test.Foo object at 0x025A0EB0>> >>> foo.bar_static <function Foo.bar_static at 0x025A34F8> >>> foo.bar_class <bound method type.bar_class of <class 'test.Foo'>> foo.bar_static just returns a function object as if bar_static were defined outside of class. (In Python 2, it would return an unbound method; Python 3 has removed the concept of unbound methods. So a function is either a bound method or a regular function object) How It Works -- Descriptor  Every

How Django Works (4) URL Resolution

Image
Why We Need URL Resolution Theoretically, we could write a single function to process all incoming HTTP requests. It would work well for very simple websites. For any real websites, it would be much more appropriate to categorize HTTP requests based on their URLs and process them separately in different handlers. For example, BASEURL/polls/ would be an application for polls whereas BASEURL/blogs/ would be an application for blogs. This way, different URLs can be considered different logic applications, so we can think of websites in terms of logic applications – a higher level of abstraction that HTTP request/response pairs. Fortunately, many modern web frameworks come default with mechanisms that do the categorization of HTTP requests based on URIs, which spares us the effort of having to reinvent the wheel.   Django's URL Resolution The official Django document has following description about how Django processes a request. https://docs.djangoproject.com/en/1.8/topic

AutoCAD DXF Transformer

I am learning DXF format today. In order to understand it, I wrote a simple program that convert DXF format into json | html | txt formats. It currently only supports simple DXF file with only LINE entity. https://github.com/druckenclam/code4blogs/tree/master/AutoCAD_dxf_transformer

A Calculator that Builds up Abstract Syntax Tree

In this post I will explain how to parse expression and create abstract syntax tree. A calculator is built using Javascript. Code is located at https://github.com/druckenclam/code4blogs/tree/master/ASTCalculator

How Django works (3): Testing Server and Static Files Serving

How Django Handles Static Files By default, Django installs an Application django.contrib.staticfiles, which is responsible for handling requests to files under STATIC_URL.   INSTALLED_APPS = ( 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'polls' , ) STATIC_URL = '/static/' This method is grossly inefficient and probably insecure, so it is unsuitable for production. https://docs.djangoproject.com/en/1.8/howto/static-files/deployment/ How staticfiles App Works Based on the first blog of Django series, Django interacts with web servers by providing a callable application that conforms to WSGI specification. 1 2 3 4 5 class WSGIHandler (base . BaseHandler): initLock = Lock() request_class = WSGIRequest def __call__ ( self , environ, start_

How Django Works (2) Built-in Server, Autoreload

Image
Django's built-in server Django comes with a built-in server for development and testing purpose. The command to start the built-in server is python manage . py runserver    Autoreload One notable feature of the built-in server is its ability to automatically reload once a file is changed. Accord to Official document, "The development server automatically reloads Python code for each request, as needed. You don’t need to restart the server for code changes to take effect. However, some actions like adding files don’t trigger a restart, so you’ll have to restart the server in these cases." The feature can be shut off by --noreload. This blog will examine in implementation detail how autoreload is implemented and how autoreload is used by Django built-in server. The file that implements autoreload is site-packages/django/utils/autoreload.py if django is installed. Or you can find it at https://github.com/django/django/blob/master/django/utils/autoreload.py

Nested Dictionary Comprehension Useless?

Yesterday I was stumped by a question about nested dictionary comprehension. I have to admit that I don't use dictionary comprehension often, especially nested ones. My preferred way is   dict ( zip (list1, list2)) Anyway, I felt the need to go over dictionary comprehension, and I found something really interesting about nested dictionary comprehension -- it probably doesn't have any practical applications. >>> def my_list_comp (): ... a = range ( 3 ) ... b = range ( 3 , 6 ) ... return [(x, y) for x in a for y in b] ... >>> def my_dict_comp (): ... a = range ( 3 ) ... b = range ( 3 , 6 ) ... return {x: y for x in a for y in b} ... >>> my_list_comp() [( 0 , 3 ), ( 0 , 4 ), ( 0 , 5 ), ( 1 , 3 ), ( 1 , 4 ), ( 1 , 5 ), ( 2 , 3 ), ( 2 , 4 ), ( 2 , 5 )] >>> my_dict_comp() { 0 : 5 , 1 : 5 , 2 : 5 } >>>     The behavior of list comprehension is straightforward, but what about th

How Django Works (1)

How websites work in general The way every website works can be simplified as a pair of HTTP request and response. A user sends an HTTP request through a client, most likely one of those browsers, such as Firefox, Chrome; Upon receiving the HTTP request, the website processes the request and sends back an HTTP response. At HTTP level, every website works this way. They have no knowledge about module, view, template, controller, or any other fancy terms. Below is the HTTP request and response pair generated by me accessing my localhost, where I am running polls – the Django tutorial website. Request GET /polls/ HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-GB,en;q=0.8,en-US