Python Refresher and
Web Basics
A Quick Review
and Introduction to
Flask
by
Muhammad Naeem
Python Basics Review
• Data Structures:
• - Lists, Tuples, Dictionaries, Sets.
• - Common operations and use cases.
• Functions:
• - Defining and calling functions.
• - Parameters, return values, and scope.
• Modules:
• - Importing and using modules.
• - Creating custom modules.
Introduction to Web Frameworks
• Flask vs. Django:
• - Flask: Lightweight and flexible micro-framework.
• - Django: High-level, batteries-included framework.
• Key Differences:
• - Flask is minimalistic and great for small projects.
• - Django provides more built-in features for larger projects.
Setting Up Flask
• Installing Flask:
• - Use pip to install Flask: `pip install Flask`.
• Creating a Simple 'Hello World' Application:
• - Create a Python file and import Flask.
• - Define a route and return 'Hello, World!'.
• Routing and Views:
• - Use the `@app.route` decorator to define routes.
• - Map URLs to view functions.
Example: Hello World in Flask
Code Example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
• Explanation:
• - `Flask(__name__)` initializes the Flask app.
• - `@app.route('/')` maps the root URL to the `hello_world` function.
• - `app.run(debug=True)` starts the development server.
Routing and Views in Flask
• Defining Routes:
• - Use the `@app.route` decorator to define routes.
• - Example: `@app.route('/about')` maps to the `/about` URL.
• Dynamic Routes:
• - Use variables in routes: `@app.route('/user/<username>')`.
• View Functions:
• - Functions that handle requests and return responses.
• - Example:
• @app.route('/user/<username>')
• def show_user_profile(username):
• return f'User: {username}'
Conclusion
• Summary:
• - Reviewed Python basics: data structures, functions, and modules.
• - Compared Flask and Django for web development.
• - Set up a simple Flask application and explored routing.
• Next Steps:
• - Explore Flask templates and static files.
• - Learn about Flask extensions (e.g., Flask-SQLAlchemy).