Python is a popular general-purpose programming language that is well-suited for web development due to its extensive libraries and frameworks for building web applications. In job interviews for Python web developer roles, candidates are commonly asked a mix of general Python coding questions and web development-specific questions to assess their skills and knowledge.
This how-to guide provides an overview of common Python web development interview questions with example answers to help prepare for coding interviews or technical assessments.
Python Coding and Concepts
Python web development interviews will typically include questions testing your general Python proficiency before diving into web-specific topics. Be prepared to answer both basic and advanced questions on Python coding and OOP concepts.
Q: What are the key features of Python programming language?
Python is an interpreted, object-oriented, high-level programming language known for its clear and readable syntax. Some of its key features include:
- Dynamic typing - Variables don’t need type declaration. The interpreter infers types during runtime.
- Easy to learn - Has simplified syntax compared to other languages. Uses whitespace for indentation.
- Extensive libraries - Comes bundled with extensive standard library for various tasks.
- Cross-platform - Python code can run on various operating systems like Windows, Linux and macOS.
- Interpreted - Code gets executed line-by-line at runtime by the interpreter rather than compiled in advance.
- Object oriented - Supports object-oriented programming with classes, inheritance, encapsulation etc.
- High-level - Abstracts away low-level details. Reduces developer effort compared to lower-level languages.
Q: Explain how Python is interpreted.
Python is an interpreted language. When we run a Python program, the source code is fed to the Python interpreter which converts the code line-by-line into intermediate bytecode that is then executed.
The interpreter parses each line, compiles it to bytecode, and immediately executes it. This means the compilation and execution happen simultaneously rather than compilation occurring separately as a build step.
The bytecode is a platform-independent representation of the code that can then run on the Python virtual machine on any platform. The interpreter’s just-in-time compilation to bytecode makes Python programs portable across Operating Systems.
Q: What is monkey patching in Python? Give an example.
Monkey patching refers to dynamically modifying classes or objects at runtime. In Python, we can modify classes and methods as we please because of its dynamic nature.
For example:
class A:
def func(self):
print("func() is being called")
def monkey_func(self):
print("This is monkey_func")
A.func = monkey_func
a = A()
a.func() # This is monkey_func
Here, we have monkey patched the func
method on the A class to override its behavior at runtime. This allows modifying code dynamically without touching the source code.
Q: What is Dunder or magic methods in Python?
Dunder or magic methods in Python are special built-in methods that start and end with double underscores.
For example __init__
, __add__
, __len__
etc.
These methods can be used to emulate built-in behaviors in user-defined classes. For example, the __init__
method can be used to initialize objects, __add__
can be used to define custom behavior for the +
operator and so on.
These double underscore methods are also called magic methods in Python. They provide powerful capabilities to classes including operator overloading, iterable/context management protocols and more.
Q: What is the difference between deep and shallow copy in Python?
- Shallow copy constructs a new compound object and then inserts references into it to the objects found in the original. A shallow copy is used when we want to construct the copy of object with same references to the objects found in the original element.
import copy
old_list = [[1, 2], [3,4]]
new_list = copy.copy(old_list)
- Deep copy makes a full independent copy of the original object and all its nested objects recursively. The copied objects do not share any references with the originals.
import copy
old_list = [[1, 2], [3,4]]
new_list = copy.deepcopy(old_list)
So the key difference is, changes made to shallow copy’s elements reflect in original elements but not in case of deep copy.
Python Web Frameworks
You should be well-versed in at least one Python web framework like Django or Flask which are commonly used for web development. Understand the framework’s architecture patterns as well as pros and cons.
Q: What are the key advantages and use cases of Django?
Django is a batteries-included web framework for Python providing an MVC architecture out of the box. Some of its major advantages:
- Rapid development - Provides many common tools/libraries needed for web dev.
- ORM - Powerful Object Relational Mapper for working with databases.
- Administration - Built-in admin interface for managing site.
- Security - Protection against common vulnerabilities like SQL injections, XSS, CSRF etc.
- Scalability - Can scale from lightweight to complex high-traffic sites.
Django is suitable for developing content-driven sites with complex data modeling requirements like CRUD web apps, news sites, e-commerce sites etc. The admin interface allows non-technical users to easily edit content.
Q: Explain Flask’s application and blueprint architecture.
Flask follows the Application Factory pattern where the app is created by instantiating a Flask class. Blueprints are used to organize different components like views, templates etc into separate modules that can be registered onto the application.
For example:
# blueprints.py
auth = Blueprint('auth', __name__)
@auth.route('/login')
...
# app.py
from flask import Flask
from blueprints import auth
app = Flask(__name__)
app.register_blueprint(auth)
if __name__ == "__main__":
app.run()
The Blueprint allows splitting the app into self-contained components that can be registered with the application factory only when required.
Blueprints promote modularity by letting you break down a large app into discrete components.
Q: How are Flask and Django different? When would you pick one over the other?
Flask | Django |
---|---|
Minimalist web framework | Batteries included web framework |
Uses external libs | Bundles many features & utilities |
Simple routing using Werkzeug | More complex URL routing system |
Uses Jinja templating | Uses Django templating language (DTL) |
More control for developer | Opinionated, follows conventions |
Better for small applications | Better for complex, scalable sites |
I would choose Flask for simple web apps that require more customization and control. Django is preferred for feature-heavy sites due to its expansive set of utilities for rapid development following conventions.
Python for Web
You need a strong grasp of Python web development concepts like handling HTTP requests & responses, templating, and working with web APIs.
Q: How are HTTP requests handled in Python web frameworks?
Python web frameworks like Django and Flask provide helper classes to represent HTTP requests and responses as objects.
For example, in Flask, request
contains the incoming request data. We can access request parameters, headers, form data, files etc using the request
object.
Similarly, response
is used to populate response data before returning it to the client.
@app.route("/login", methods=["POST"])
def login():
username = request.form.get("username")
# handle login
...
response = make_response(redirect("/welcome"))
return response
The framework handles parsing the raw HTTP request and populating the request object. We can then process the request parameters without dealing with low-level HTTP handling.
Q: Explain CSS and JS asset management in Django.
Django web applications typically use static files like CSS, Javascript and images that need to be handled properly:
-
Static files should be placed in a
static/
folder inside an app. They can be referenced using{% static %}
template tag that handles the path properly. -
For production, Django’s
collectstatic
command collects all static files from different apps into a single folder ready for serving. -
The
STATICFILES_DIRS
config is used to tell Django about additional static assets locations. -
Static files when deployed are served directly by the web server or a CDN rather than going through Django which only handles the dynamic parts.
-
The
whitenoise
Django app can be used to serve static files efficiently in production.
Proper static file configuration improves performance and allows customizing asset handling.
Q: How do you implement authentication in a Flask application?
Flask has extensions like Flask-Login that implement authentication in a Flask app.
The steps would be:
-
Install Flask-Login extension
-
Create a User class that implements the
UserMixin
mixin -
Initialize Flask-Login by creating a LoginManager and configuring the User class
-
Use the
login_required
andlogin_user
methods to add authentication
For example:
from flask_login import LoginManager, UserMixin, login_required
# User class
class User(UserMixin):
pass
login_manager = LoginManager()
login_manager.init_app(app)
@app.route("/protected")
@login_required
def protected():
return "Logged in Successfully"
@app.route("/login")
def login():
user = User()
login_user(user)
return redirect("/protected")
This allows adding full user authentication easily following Flask-Login best practices.
Q: How can you consume a REST API in Python?
To interact with a REST API in Python, we can use the requests
module. The key steps are:
- Make a GET request to retrieve data:
import requests
url = "https://api.example.com/items"
response = requests.get(url)
items = response.json() # deserialize to dict
- Use POST request to create resource:
data = {"name": "Item1"}
response = requests.post(url, json=data)
item = response.json()
- PUT request to update resource:
item_id = "123"
url = f"https://api.example.com/items/{item_id}"
data = {"name": "New Item Name"}
requests.put(url, json=data)
- DELETE to remove resource:
requests.delete(url)
The requests
module provides an easy API for consuming REST APIs in Python, abstracting away the low-level details.
Python for Web Scraping
Web scraping questions test your skills in using Python for extracting data from websites. Being able to scrape data is useful for a web developer.
Q: Write a simple Python script to scrape data from a web page.
Here is a simple script to scrape paragraphs from a web page using the requests and BeautifulSoup modules:
import requests
from bs4 import BeautifulSoup
url = "http://example.com"
resp = requests.get(url)
soup = BeautifulSoup(resp.content, 'html.parser')
paras = soup.find_all('p')
for p in paras:
print(p.text)
This script makes a GET request to fetch the web page HTML using requests.
BeautifulSoup parses this HTML into a navigable DOM tree. We can use it to easily extract <p>
tags containing paragraphs of text.
Finally, we print the paragraph text stripped of HTML tags.
Q: How can you scrape data from a site that blocks scraping?
There are several techniques to bypass blocks while scraping sites:
- Use proxies - Scrape via different IPs to avoid detection.
- Limit request rate - Add delays between requests to mimic human behavior.
- Rotate User Agents - Use a list of common UA strings as HTTP header.
- Use Selenium - Scrape content dynamically rendered by JavaScript.
- Handle captchas - Use OCR modules to auto-solve captchas.
- Identify as a search engine - Some sites allow scrapers posing as Googlebot.
However, always check the site’s terms to avoid unethical scraping. Consider using their API if available instead of scraping.
Q: What are some best practices for web scraping?
Some web scraping best practices include:
- Check the site’s terms for guidelines on appropriate vs prohibited scraping. Avoid unethical scraping.
- Use APIs instead of screen scraping whenever available.
- Limit request rate and add delays to avoid overloading target sites.
- Use random user-agents to mimic real users.
- Employ caching and proxies to optimize performance.
- Parallelize and distribute scraping over multiple threads/machines.
- Use captchas solving services ethically.
- Make scrapers resilient to site changes using robust parsing.
- Rotate IP addresses and clear cookies to prevent blocking.
- Cache scraped data locally for reuse and analyze offline.
Python Security and Best Practices
You need to demonstrate awareness of security issues and following best practices while building Python web apps.
Q: What are some common security issues that affect Python web applications?
Some common security risks include:
-
Cross-Site Scripting (XSS) - Unsanitized user input allows injecting client-side scripts.
-
SQL Injection - Inserting malformed SQL queries due to unescaped user input.
-
Cross-Site Request Forgery (CSRF) - Forging requests from an authenticated user.
-
Broken Authentication - Flaws in auth logic allowing unauthorized access.
-
Sensitive Data Exposure - Plaintext storage/transmission of passwords, tokens etc.
-
Security Misconfiguration - Using default insecure settings, unnecessary ports open etc.
-
Server-side request forgery (SSRF) - Tricking the app to make requests to unintended servers.
Python web frameworks provide protections against many issues but vulnerabilities can still be introduced by the developer.
Q: How can you prevent SQL injection attacks in Python code?
To prevent SQL injection in Python:
-
Never concatenate or format raw user input into SQL queries.
-
Use parameterized queries and prepared statements instead of string formatting.
For example, with psycopg2:
sql = "SELECT * FROM users WHERE id = %s"
cursor.execute(sql, (user_id))
-
Use ORM libraries like SQLAlchemy that automatically handle escaping all parameters.
-
Validate and sanitize all user inputs.
-
Limit database permissions to only what is absolutely necessary.
-
Use Python DB API’s builtin escaping for exceptional cases.
Q: What are some best practices for writing secure Python code?
Some Python code security best practices include:
-
Keep third-party packages up-to-date to avoid vulnerable dependencies.
-
Use tools like bandit, safety, and blackduck to detect vulnerabilities.
-
Avoid using eval(), exec(), pickle etc which can lead to arbitrary code execution.
-
Validate and sanitize all inputs from users and APIs before use.
-
Use templating engines to avoid XSS vulnerabilities.
-
Handle errors gracefully and don’t reveal sensitive error messages.
-
Encrypt sensitive data like passwords using standard libraries instead of writing custom implementations.
-
Review OAuth2 and token based authentication code to prevent flaws.
-
Enable security features offered by frameworks like CSRF protection middleware.
-
Follow PEP-8 and best practices for clean and maintainable code.
Python Testing
Testing skills are highly valued in Python web development roles. Be ready for questions on unit, integration and end-to-end testing.
Q: How are tests written and run in Django?
Django has inbuilt support for writing tests using the django.test
module and SimpleTestCase
classes.
Some key points:
-
Tests are placed in
tests.py
inside Django apps. -
Each test case extends Django’s
SimpleTestCase
and runs tests using assert methods. -
setUp()
andtearDown()
can set up preconditions and cleanup. -
Run tests with
python manage.py test
. -
Test client can be used to simulate HTTP requests.
For example:
# tests.py
from django.test import SimpleTestCase
class LoginTestCase(SimpleTestCase):
def test_login_page(self):
response = self.client.get('/login/')
assert response.status_code == 200
def test_login_POST(self):
# Test login view using POST
...
This allows testing Django views and functionality without running the server.
Q: What testing approaches are used for end-to-end tests?
End-to-end testing validates the complete application including its integration with external systems like databases, APIs etc. Some approaches used are:
UI Testing - Simulate user interactions and assert for expected outcomes. Done using Selenium browser automation.
API Testing - Test API endpoints directly using a testing library without going through UI. Allows for more granular tests.
Mocking - Isolate components like databases or APIs by mocking their interactions.
Smoke Tests - Broad tests to verify major features work end-to-end.
Exploratory Testing - Ad hoc testing aimed at breaking the software in unscripted ways.
Load Testing - Test application performance under expected traffic loads using tools like Locust.
A combination of these techniques allows thoroughly testing real world scenarios.
Q: How can you implement a mock database for testing in Flask?
Flask provides Flask.app.testing
for app testing that can include mocking a database:
import unittest
from flask import Flask
app = Flask(__name__)
# This mock database replaces the real db for testing
app.config['DATABASE_URI'] = 'sqlite://'
class BasicTests(unittest.TestCase):
def setUp(self):
app.testing = True
self.app = app.test_client()
def test_home(self):
response = self.app.get('/')
# Assertions
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
We can mock the database by using a temporary in-memory sqlite database while testing. The real production database is not used. This allows running tests in isolation without persistence.
Other techniques like using fixtures or factory boy can also be used to create mock database records to run tests.
Python Deployment and DevOps
Deploying and operating Python applications in production requires DevOps skills like infrastructure configuration, monitoring, logging etc.
Q: How can you configure Python applications for production deployments?
Some key configuration for Python production deployments:
- Set DEBUG = False, to disable debug mode.
- Use a production webserver like Nginx/Apache instead of built-in WSGI servers.
- Enable caching and compression using a CDN for static files.
- Use Gunicorn/uWSGI as the app server & reverse proxy to web server.
- Set ALLOWED_HOSTS, SECRET_KEY, SECURITY_MIDDLEWARE correctly.
- Configure email and logging appropriately on the production servers.
- Enable cached template loading for the frameworks.
- Set proper database permissions and ensure adequate capacity.
- Use services like Sentry for monitoring exceptions.
- Enable automated failover and recovery using master-replica clusters.
Q: Explain how you have deployed Python web apps to AWS cloud in the past.
Some ways I have deployed Python apps to AWS are:
-
EC2 - Launch EC2 instances, install dependencies, deploy code using Fabric/Ansible.
-
Elastic Beanstalk - AWS platform for deploying applications like Django/Flask apps.
-
ECS - Deploy Docker containers running the Python app using ECS.
-
Lambda - Develop Flask/API apps that run as AWS Lambda functions.
-
Elastic Load Balancing - Distribute load across EC2 instances or containers.
-
RDS - Setup managed relational databases like PostgreSQL on RDS.
-
S3 - Serve static assets directly from S3.
-
CloudFront - Use CloudFront CDN for caching/global edge delivery.
-
Route 53 - Configure DNS and domain management.
-
CloudWatch - Monitor key metrics and set alerting.
Following AWS best practices allows taking advantage of its managed services for easier deployments.
Q: How would you monitor and log a live Python application?
Some ways to monitor and log a live Python web app:
-
Use tooling like New Relic or Datadog for performance monitoring and alerting.
-
Log app events to tools like ELK stack or AWS CloudWatch logs for analysis.
-
Set up Sentry to track production errors and exceptions.
-
Use Flower to monitor Celery task queues and workers.
-
Monitor infrastructure health using Nagios.
-
Enable StatsD for collecting custom metrics.
-
Check slow database queries using database monitoring.
-
Use profiling tools to identify bottlenecks.
-
Make use of logging handlers for segmented logging to analyze specific segments.
-
Follow Twelve-Factor App methodology for logging and monitoring.
This provides rich observability into a Python app for efficient diagnosing and alerting.
Wrapping Up
Python’s growing popularity in web development means that interviewers will test your expertise in areas like Python fundamentals, web frameworks, security, testing, and production deployments. Learning some commonly asked Python web development interview questions helps you better showcase your hands-on skills during technical interviews and land your next Python developer role.