Python Fundamentals, Concurrency, and Django Backend Development Essentials
This article provides a comprehensive overview of core Python concepts—including garbage collection, tuple versus list differences, process/thread/coroutine models, shallow and deep copying, the Global Interpreter Lock, sorting algorithms, closures, decorators, iterators, generators, and essential Django backend components such as WSGI, request lifecycle, middleware, ORM methods, caching, and REST framework.
Python Garbage Collection Mechanism
Python primarily uses reference counting for garbage collection, supplemented by mark-and-sweep and generational techniques to handle circular references.
When an object is referenced, its reference count increments; when del is called, the count decrements, and the object is freed when the count reaches zero. Python also provides a GC API.
Tuple and List Differences
Lists are mutable, whereas tuples are immutable.
>> mylist=[1,3,3]
>>> mylist[1]=2
>>> mytuple=(1,3,3)
>>> mytuple[1]=2
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>Can a Tuple Be Used as a Dictionary Key?
An object can serve as a dictionary key only if it implements the __hash__ method. Therefore, mutable containers like list, dict, set, and tuples containing mutable objects cannot be used as keys; all other objects can.
Process, Thread, and Coroutine
Process
The operating system's basic unit for resource allocation and scheduling; processes are independent, stable, but consume more resources.
Thread
The CPU's basic unit for scheduling; threads share the resources of their parent process. Multithreading improves I/O‑bound performance but a thread crash can bring down the whole process.
Coroutine
Coroutines are sub‑routines that can be paused and resumed, allowing cooperative multitasking within a single thread.
Assignment, Shallow Copy, and Deep Copy
Deep copy creates an independent copy of an object using deepcopy(), so modifications to the copy do not affect the original.
Shallow copy copies only references, so changes to mutable elements affect the original.
Global Interpreter Lock (GIL)
The GIL ensures that only one thread executes Python bytecode at a time within a process. I/O‑bound operations release the GIL, allowing other threads to run.
Multiprocessing spawns separate processes, each with its own interpreter and GIL, enabling true parallelism at the cost of higher resource usage.
List Deduplication
Convert the list to a set to remove duplicates, then back to a list.
Sorting Algorithms
Bubble Sort
Repeatedly compare adjacent elements and swap them if they are out of order, bubbling the largest element to the end of the list each pass.
def bubbleSort(array):
if len(array) < 2:
return array
else:
isSorted = False
counter = 0
while not isSorted:
isSorted = True
for idx in range(len(array) - 1 - counter):
if array[idx] > array[idx + 1]:
isSorted = False
(array[idx + 1], array[idx]) = (array[idx], array[idx + 1])
counter += 1
return arrayQuick Sort
Choose a pivot, partition the array into elements less than and greater than the pivot, then recursively sort the partitions.
def quickSort(array):
if len(array) < 2:
return array
else:
pivot_index = 0
pivot = array[pivot_index]
less_part = [i for i in array[pivot_index+1:] if i <= pivot]
large_part = [i for i in array[pivot_index+1:] if i > pivot]
return quickSort(less_part) + [pivot] + quickSort(large_part)Closures
A function can return another function object; the inner function retains access to the outer scope, enhancing encapsulation.
With Statement
The with statement simplifies resource management by automatically handling setup and teardown (e.g., file closing) via context managers.
Instance Methods vs. Static Methods
Instance methods receive the instance ( self) as the first argument.
Static methods have no implicit first argument.
Class methods receive the class ( cls) as the first argument.
Iterators and Generators
Iterators implement iter() and next() to traverse a collection forward only.
mylist = [1,2,3,4]
it = iter(mylist)
print(next(it)) # 1
print(next(it)) # 2Generators are functions that use yield to produce values lazily.
Anonymous Functions (Lambda)
print([ (lambda x: x*x)(x) for x in range(5) ]) # [0, 1, 4, 9, 16]Functional Tools: map, reduce, filter
# map example
def fn(x):
return x + 1
resp = map(fn, [1,2,3])
print(list(resp)) # [2, 3, 4]
# reduce example
from functools import reduce
nums = [1,2,3,4]
def fn(x, y):
return x * y
resp = reduce(fn, nums)
print(resp) # 24
# filter example
a = [1,2,3,4,5,6,7,8,9,10]
def fn(a):
return a % 2 == 1
newlist = filter(fn, a)
print(list(newlist)) # [1, 3, 5, 7, 9]Django Basics
WSGI
WSGI (Web Server Gateway Interface) is a protocol that connects web servers (e.g., uWSGI, gunicorn) with Python web frameworks like Django or Flask.
Request Lifecycle
Client sends request.
WSGI receives and wraps the request.
Middleware processes request (e.g., CSRF, session).
URL routing matches view.
View executes business logic (ORM, rendering).
Response passes back through middleware.
WSGI sends response to browser.
Built‑in Components
Admin – CRUD interface for models.
Model – Database abstraction.
Form – HTML generation and validation.
ModelForm – Combines model handling and form validation.
Middleware Methods
process_request– Authentication before view. process_view – Runs after URL resolution. process_exception – Handles exceptions. process_template_response – After template rendering. process_response – Final response processing.
FBV vs. CBV
Function‑Based Views (FBV) are plain functions; Class‑Based Views (CBV) are classes that provide method dispatching, improving code reuse and readability.
Adding Decorators to CBV
from django.utils.decorators import method_decorator
@method_decorator(check_login)
def post(self, request):
...
@method_decorator(check_login, name='get')
@method_decorator(check_login, name='post')
class HomeView(View):
...Django ORM Methods
all(), filter(), get(), exclude(), order_by(), reverse(), count(), first(), last(), exists(), values(), values_list(),
distinct()select_related vs. prefetch_related
select_relatedperforms a SQL join to fetch related objects in a single query; prefetch_related executes separate queries and combines results in Python, useful for many‑to‑many relations.
CSRF Implementation
Server generates a token and stores it in the session and a cookie.
Client includes the token in subsequent POST requests.
Server validates the token against the session value.
Logging Model Changes with Signals
# Example using Django signals
from django.db.models.signals import post_save
from django.dispatch import receiver
import logging
@receiver(post_save, sender=MyModel)
def signal_handler(sender, **kwargs):
logger = logging.getLogger()
logger.info('Save successful')Caching Configuration
Dummy Cache
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'TIMEOUT': 300,
'OPTIONS': {
'MAX_ENTRIES': 300,
'CULL_FREQUENCY': 3,
},
}
}Redis Cache
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {'max_connections': 100},
# 'PASSWORD': 'your_password',
},
}
}URL name Attribute
The name attribute enables reverse URL lookup, allowing templates to reference URLs by name rather than hard‑coded paths.
Django REST Framework Components
Authentication
Permissions
Throttling
Versioning
Parsers
Serializers
Pagination
Routing
Views
Renderers
DRF Authentication Flow
Login view calls as_view() → APIView.dispatch(). initialize_request creates the Request object and attaches authentication classes. self.initial() invokes perform_authentication, which calls self._authenticate().
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
