Python Programming Labs

Master professional Python: HTTP requests, application logging, and command-line interfaces.

Professional Python Development - Module 10

Build real-world applications with networking, logging, and CLI tools.

Lab 28: HTTP Requests
Expert
Coding Challenge
Your Task: Learn to make HTTP requests using Python's requests library and built-in urllib.

Detailed Requirements:
1. GET requests:
import requests # Simple GET request response = requests.get('https://api.github.com/users/python') print(response.status_code) # 200 print(response.json()) # Parse JSON response # With query parameters params = {'q': 'python', 'sort': 'stars'} response = requests.get('https://api.github.com/search/repos', params=params) # With headers headers = {'Authorization': 'token YOUR_TOKEN'} response = requests.get(url, headers=headers)

2. POST requests:
# POST with JSON data data = {'name': 'test', 'value': 123} response = requests.post('https://httpbin.org/post', json=data) # POST with form data form_data = {'username': 'alice', 'password': 'secret'} response = requests.post(url, data=form_data) # Check response if response.ok: print(response.json()) else: print(f"Error: {response.status_code}")

3. Response handling:
response = requests.get(url) # Response attributes print(response.status_code) # 200 print(response.headers) # Response headers print(response.text) # Raw text content print(response.json()) # Parse as JSON print(response.content) # Raw bytes # Check for errors response.raise_for_status() # Raises exception on 4xx/5xx

4. Session and timeout:
# Using sessions (maintains cookies) session = requests.Session() session.headers.update({'User-Agent': 'MyApp/1.0'}) response = session.get('https://example.com/login') response = session.post('https://example.com/data') # Timeout handling try: response = requests.get(url, timeout=5) except requests.Timeout: print("Request timed out") except requests.RequestException as e: print(f"Request failed: {e}")

💡 Pro Tips:
• Always set timeouts to prevent hanging
• Use sessions for multiple requests to same host
• Check response.ok before parsing
• requests needs to be installed: pip install requests

Expected Output:
Status: 200 Response: {'login': 'python', 'id': 1525981, ...} Request successful!

Requirements Checklist

Import requests module
Make a GET request
Check response status code
Parse JSON response
Handle errors or use timeout
Print results to verify
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import requests
• GET: requests.get(url)
• Status: response.status_code or response.ok
• JSON: response.json()
• Timeout: requests.get(url, timeout=5)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 29: Logging Module
Expert
Coding Challenge
Your Task: Master Python's logging module for professional application logging.

Detailed Requirements:
1. Basic logging:
import logging # Basic configuration logging.basicConfig(level=logging.DEBUG) # Log at different levels logging.debug('Debug message') # Detailed info logging.info('Info message') # General info logging.warning('Warning!') # Something unexpected logging.error('Error occurred') # Error but recoverable logging.critical('Critical!') # Program may crash

2. Formatting log messages:
# Custom format logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) logging.info('Application started') # Output: 2024-01-15 10:30:00 - root - INFO - Application started # Format specifiers: # %(asctime)s - Timestamp # %(name)s - Logger name # %(levelname)s - Level (DEBUG, INFO, etc.) # %(message)s - Log message # %(filename)s - Source file # %(lineno)d - Line number

3. File and console logging:
# Log to file logging.basicConfig( filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) # Log to both file and console import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Console handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) # File handler file_handler = logging.FileHandler('app.log') file_handler.setLevel(logging.DEBUG) # Add handlers logger.addHandler(console_handler) logger.addHandler(file_handler)

4. Named loggers and exceptions:
# Named logger logger = logging.getLogger('myapp.module') logger.info('Module initialized') # Log exceptions with traceback try: result = 1 / 0 except Exception: logger.exception('An error occurred') # Automatically includes traceback # Using extra data logger.info('User logged in', extra={'user': 'alice', 'ip': '192.168.1.1'})

💡 Pro Tips:
• Use logger = logging.getLogger(__name__) per module
• logger.exception() includes traceback
• Set different levels for handlers
• Don't use print() for logs in production

Expected Output:
2024-01-15 10:30:00 - INFO - Application started 2024-01-15 10:30:01 - WARNING - Low memory 2024-01-15 10:30:02 - ERROR - Connection failed

Requirements Checklist

Import logging module
Configure with basicConfig()
Use different log levels
Set custom format with format=
Create a named logger with getLogger()
Log messages at various levels
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import logging
• Config: logging.basicConfig(level=logging.DEBUG)
• Levels: debug, info, warning, error, critical
• Named: logger = logging.getLogger('name')
• Exception: logger.exception('msg')
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 30: Command-Line Interfaces (argparse)
Expert
Coding Challenge
Your Task: Build professional command-line interfaces using Python's argparse module.

Detailed Requirements:
1. Basic argument parsing:
import argparse # Create parser parser = argparse.ArgumentParser( description='Process some files.' ) # Add positional argument parser.add_argument('filename', help='The file to process') # Parse arguments args = parser.parse_args() print(f'Processing: {args.filename}')

2. Optional arguments and flags:
# Optional argument with default parser.add_argument( '-o', '--output', default='output.txt', help='Output file (default: output.txt)' ) # Boolean flag parser.add_argument( '-v', '--verbose', action='store_true', help='Enable verbose output' ) # Count flag (-vvv for verbosity) parser.add_argument( '-d', '--debug', action='count', default=0, help='Debug level' ) args = parser.parse_args() if args.verbose: print('Verbose mode enabled')

3. Argument types and choices:
# Typed argument parser.add_argument( '-n', '--number', type=int, required=True, help='Number of items' ) # Choices parser.add_argument( '--format', choices=['json', 'csv', 'xml'], default='json', help='Output format' ) # Multiple values parser.add_argument( '--files', nargs='+', help='List of files' ) # Optional number of values parser.add_argument( '--tags', nargs='*', help='Optional tags' )

4. Subcommands:
# Create subparsers subparsers = parser.add_subparsers(dest='command') # 'add' subcommand add_parser = subparsers.add_parser('add', help='Add item') add_parser.add_argument('name', help='Item name') # 'remove' subcommand remove_parser = subparsers.add_parser('remove', help='Remove item') remove_parser.add_argument('id', type=int, help='Item ID') args = parser.parse_args() if args.command == 'add': print(f'Adding: {args.name}') elif args.command == 'remove': print(f'Removing ID: {args.id}')

💡 Pro Tips:
• Use -h or --help for auto-generated help
• required=True for mandatory optional args
• nargs='+' for one or more, '*' for zero or more
• Subcommands for complex CLIs (like git)

Expected Output:
$ python cli.py input.txt -o result.json -v Processing: input.txt Output: result.json Verbose: True

Requirements Checklist

Import argparse module
Create ArgumentParser with description
Add positional arguments
Add optional arguments with flags
Parse arguments with parse_args()
Use the parsed arguments
Output
# Click "Run Code" to execute your Python code
Hints & Tips
• Import: import argparse
• Create: parser = argparse.ArgumentParser(description='...')
• Positional: parser.add_argument('name')
• Optional: parser.add_argument('-o', '--option')
• Parse: args = parser.parse_args()
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Congratulations, Python Master!

You've completed all 30 Python labs! You now have comprehensive mastery of Python programming.

From basics to advanced topics - variables, OOP, decorators, async, standard library modules, HTTP, logging, and CLI tools.

You're ready for professional development, data science, automation, web development, and more!