Docsity

WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1, Exams of Nursing

Toggle sidebar
bg1
WGU D522 Python for IT Automation API, MailHog, Logging
& Exception Handling Guide Task 1 & Task 2 Support
This exam assesses advanced Python skills for IT automation, focusing on REST API integration, MailHog email
testing, logging configuration, and exception handling. It covers practical implementation, debugging, and best
practices for automating IT workflows. It contains 50 multiple-choice questions, each with four distractors and a
fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled
sections that mirror the major content areas of the course. Targeted learning outcomes include: Design and
implement Python scripts that interact with REST APIs using requests, including authentication, error handling,
and pagination.; Configure and utilize MailHog for testing email sending functionality in automated workflows.;
Implement robust logging and exception handling strategies to ensure reliable and maintainable automation
scripts.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can
study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately
before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes.
The recommended writing time is 3 hours, with a passing score of 70%. Aligned with This exam adheres to US
university standards for rigorous assessment in computer science and IT automation, aligning with ACM/IEEE
curricula. standards and reflects the question style commonly seen on accredited program examinations. Students
consistently achieving above the cut score on this bank have historically gone on to earn A+ on the corresponding
Section 1: General (Questions 1-50)
1When using Python's requests library to interact with a REST API that returns
paginated results via a 'next' link in the JSON response, which approach best
ensures all pages are retrieved while handling transient network errors?
A) Use a while loop that follows the 'next' link until it is null, wrapping each
request in a try-except block with retries using exponential backoff.
B) Use a for loop over a fixed range of page numbers, ignoring the 'next' link, and
catch exceptions to retry the entire loop.
C) Use a recursive function that calls itself with the 'next' URL, without any
exception handling, relying on Python's recursion limit.
D) Use the requests library's built-in pagination support by passing a
'paginate=True' parameter to the get method.
Answer: A
Rationale: Option A correctly follows the 'next' link dynamically and handles
transient errors with retries and backoff, which is a robust pattern. Option B assumes
a fixed number of pages and may miss data. Option C lacks error handling and may
hit recursion limits. Option D is incorrect because requests does not have built-in
pagination.
2In a Python automation script that sends emails via SMTP, you need to test the
email content without actually sending it to external recipients. How should
MailHog be configured and used?
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download WGU D522 Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 and more Exams Nursing in PDF only on Docsity!

WGU D522 Python for IT Automation API, MailHog, Logging

& Exception Handling Guide Task 1 & Task 2 Support

This exam assesses advanced Python skills for IT automation, focusing on REST API integration, MailHog email testing, logging configuration, and exception handling. It covers practical implementation, debugging, and best practices for automating IT workflows. It contains 50 multiple-choice questions, each with four distractors and a fully worked rationale that explains why the keyed answer is correct. Questions are organized into clearly labelled sections that mirror the major content areas of the course. Targeted learning outcomes include: Design and implement Python scripts that interact with REST APIs using requests, including authentication, error handling, and pagination.; Configure and utilize MailHog for testing email sending functionality in automated workflows.; Implement robust logging and exception handling strategies to ensure reliable and maintainable automation scripts.. Every item has been reviewed for clinical accuracy, current guidelines, and clarity so that students can study with confidence and self-correct as they work through the bank. Use it as a high-yield review immediately before the exam, or as a structured practice tool during the unit - the rationales double as concise teaching notes. The recommended writing time is 3 hours, with a passing score of 70%. Aligned with This exam adheres to US university standards for rigorous assessment in computer science and IT automation, aligning with ACM/IEEE curricula. standards and reflects the question style commonly seen on accredited program examinations. Students consistently achieving above the cut score on this bank have historically gone on to earn A+ on the corresponding

Section 1: General (Questions 1-50)

1 When using Python's requests library to interact with a REST API that returns paginated results via a 'next' link in the JSON response, which approach best ensures all pages are retrieved while handling transient network errors?

A) Use a while loop that follows the 'next' link until it is null, wrapping each request in a try-except block with retries using exponential backoff.

B) Use a for loop over a fixed range of page numbers, ignoring the 'next' link, and catch exceptions to retry the entire loop.

C) Use a recursive function that calls itself with the 'next' URL, without any exception handling, relying on Python's recursion limit.

D) Use the requests library's built-in pagination support by passing a 'paginate=True' parameter to the get method.

Answer: A Rationale: Option A correctly follows the 'next' link dynamically and handles transient errors with retries and backoff, which is a robust pattern. Option B assumes a fixed number of pages and may miss data. Option C lacks error handling and may hit recursion limits. Option D is incorrect because requests does not have built-in pagination.

2 In a Python automation script that sends emails via SMTP, you need to test the email content without actually sending it to external recipients. How should MailHog be configured and used?

A) Run MailHog locally, configure the script to use localhost:1025 as the SMTP server, and inspect messages via MailHog's web UI at localhost:8025.

B) Use MailHog's cloud service by signing up for an API key, then send emails through its REST API.

C) Configure the script to use MailHog's SMTP server at mailhog.example.com:25, which requires no authentication.

D) Install MailHog as a Python package and import it directly into the script to intercept emails.

Answer: A Rationale: MailHog is a local SMTP server that captures emails, with a web UI for inspection. Option A correctly describes its typical use. Option B is false; MailHog is not a cloud service. Option C is incorrect because MailHog runs locally by default. Option D is wrong; MailHog is a standalone binary, not a Python library.

3 Which logging configuration in Python ensures that log messages are written to both a file and the console, with different formats for each handler, and that the file handler rotates when it reaches 10 MB?

A) Use logging.basicConfig with filename and stream parameters, and set maxBytes=1010241024.

B) Create a logger, add a StreamHandler and a RotatingFileHandler with maxBytes=1010241024, and set different formatters for each handler.

C) Use the logging.config.dictConfig method with a configuration dictionary that defines two handlers and a formatter, and set rotation via 'maxBytes'.

D) Use the logging module's FileHandler and StreamHandler, and manually check file size in a loop to rotate when needed.

Answer: B Rationale: Option B correctly uses RotatingFileHandler for size-based rotation and allows separate formatters. Option A is incorrect because basicConfig cannot handle multiple handlers with different formats. Option C is plausible but dictConfig can also work; however, B is more direct and common. Option D is inefficient and error-prone.

4 When writing a Python function that makes an API call, which exception handling strategy best balances robustness and debuggability?

A) Catch all exceptions with a bare except clause, log the error, and return None. B) Catch specific exceptions like requests.exceptions.RequestException, log with exc_info=True, and re-raise a custom exception with context.

Option B uses an incorrect flag and endpoint. Option C binds the API but not SMTP. Option D uses an outdated API endpoint.

7 When implementing logging in a Python automation script that runs as a systemd service, which practice ensures that log messages are captured by journald and also available in a file?

A) Configure the logging module to write to sys.stdout and rely on systemd to capture stdout.

B) Use the systemd.journal module to send logs directly to journald, and also add a FileHandler.

C) Set up a SysLogHandler with address '/dev/log' and a FileHandler. D) Use logging.basicConfig with filename and stream, and set systemd to capture the file.

Answer: C Rationale: Option C uses SysLogHandler to send logs to the system log (journald on systemd systems) and also writes to a file. Option A only captures stdout, not file. Option B requires an external module. Option D is incorrect because basicConfig cannot handle multiple handlers with different destinations.

8 In Python, which exception handling construct is most appropriate for ensuring that a critical cleanup action (e.g., closing a database connection) occurs regardless of whether an exception is raised?

A) try-finally B) try-except-else C) try-except D) with statement

Answer: A Rationale: try-finally guarantees the finally block executes even if an exception occurs, making it ideal for cleanup. try-except-else runs else only if no exception, not for cleanup. try-except handles exceptions but doesn't guarantee cleanup. The with statement is for context managers, which may not apply to all cleanup scenarios.

9 When using the requests library to POST JSON data to an API, which code snippet correctly sets the Content-Type header and handles a potential JSON decoding error in the response?

A) requests.post(url, json=data, headers={'Content-Type': 'application/json'}) and then response.json() inside a try-except for ValueError.

B) requests.post(url, data=json.dumps(data), headers={'Content-Type': 'application/json'}) and then response.json() without error handling.

C) requests.post(url, json=data) and then response.json() inside a try-except for requests.exceptions.JSONDecodeError.

D) requests.post(url, data=data, headers={'Content-Type': 'application/json'}) and then response.json() inside a try-except for KeyError.

Answer: A Rationale: Option A correctly uses the json parameter (which sets Content-Type automatically) and handles JSON decoding errors with ValueError (or requests.exceptions.JSONDecodeError, a subclass). Option B manually sets header but lacks error handling. Option C omits explicit header but is also correct; however, A is more explicit. Option D sends data as form-encoded, not JSON.

10 In a Python automation script, you need to log messages with varying severity levels to different destinations: DEBUG and above to a file, and ERROR and above to the console. Which logging configuration achieves this?

A) Set the root logger level to DEBUG, add a FileHandler with level DEBUG and a StreamHandler with level ERROR.

B) Set the root logger level to ERROR, add a FileHandler with level DEBUG and a StreamHandler with level ERROR.

C) Set the root logger level to DEBUG, add a FileHandler with level ERROR and a StreamHandler with level DEBUG.

D) Set the root logger level to DEBUG, add a FileHandler with level DEBUG and a StreamHandler with level DEBUG.

Answer: A Rationale: Option A sets the root logger to DEBUG so all messages are processed, then the FileHandler logs DEBUG and above, while the StreamHandler logs only ERROR and above. Option B sets root to ERROR, so DEBUG and INFO are ignored. Option C swaps the handlers. Option D logs everything to both.

11 A Python automation script uses the requests library to call a REST API. The endpoint returns HTTP 429 with a Retry-After: 30 header. Which implementation most correctly handles this response to satisfy production-grade automation requirements?

A) Immediately retry the request in a tight loop until a 200 status is received. B) Raise a custom exception and terminate the script, since 429 indicates an unrecoverable client error.

the active file, and D is not the naming scheme used by the standard library.

14 Which try/except/else/finally structure correctly logs an exception while guaranteeing a cleanup action runs regardless of success or failure?

A) try: work() except Exception: log() else: cleanup() finally: pass B) try: work() finally: cleanup() except Exception: log() C) try: work() except Exception: log() finally: cleanup() D) try: work() else: cleanup() except Exception: log()

Answer: C Rationale: except handles/logs the exception and finally always executes cleanup, which is the correct ordering. A runs cleanup only on success, B is syntactically invalid (finally must follow except), and D places else before except, which is invalid syntax.

15 An automation script must authenticate to an API whose token expires every 60 minutes. Which design best satisfies the principle of least privilege and operational reliability?

A) Hard-code a long-lived token in the script to avoid refresh logic. B) Store credentials in environment variables or a secrets manager and refresh the token proactively before expiry with retry on 401.

C) Disable token expiry on the server so the script never needs to refresh. D) Log the token to a file so operators can reuse it manually.

Answer: B Rationale: Using a secrets manager/environment variables and refreshing before expiry with 401 retry aligns with least privilege and resilience. A and D expose credentials, and C weakens security by removing expiration.

16 A script parses JSON from an API using response.json(). Occasionally the response is HTML (e.g., a proxy error page). Which exception-handling approach is most robust?

A) Wrap the call in try/except json.JSONDecodeError and log the raw response body for diagnosis.

B) Use response.text and eval() to parse the content. C) Assume the API always returns JSON and skip error handling. D) Catch Exception broadly and silently pass.

Answer: A Rationale: response.json() raises json.JSONDecodeError on non-JSON payloads; catching it and logging the raw body enables diagnosis. B is unsafe (eval), C

ignores real failure modes, and D swallows errors without visibility.

17 Which statement best distinguishes logging.exception() from logging.error() inside an except block?

A) logging.exception() automatically includes the traceback and must be called from an exception handler.

B) logging.error() always includes the traceback, while logging.exception() does not.

C) Both are identical in output and differ only in severity level. D) logging.exception() suppresses the exception and prevents propagation.

Answer: A Rationale: logging.exception() logs at ERROR level and appends the current exception's traceback; it is intended for use inside except. B reverses the behavior, C ignores the traceback difference, and D is false-logging does not alter exception propagation.

18 A script uses requests.Session() to call multiple endpoints on the same host. Which benefit most directly improves automation performance and reliability?

A) It automatically retries failed requests with exponential backoff. B) It reuses the underlying TCP connection and persists headers/cookies across requests.

C) It converts all responses to JSON automatically. D) It bypasses TLS certificate verification for speed.

Answer: B Rationale: A Session reuses connections (keep-alive) and persists headers/cookies, reducing latency and simplifying auth. A is false (retries require HTTPAdapter/Retry), C is false, and D would be a security regression.

19 In MailHog, a test must assert that an email's body contains a specific one-time code. Which approach most reliably extracts the code for assertion in an automated test?

A) Query MailHog's HTTP API (e.g., /api/v2/messages) and parse the JSON body for the code.

B) Read MailHog's SMTP debug log and grep for the code. C) Open the MailHog UI manually and copy the code. D) Use IMAP to fetch from MailHog, since MailHog exposes IMAP on port 143 by default.

Answer: A

22 A developer configures MailHog for local email testing. The application sends an email via SMTP to localhost:1025, but MailHog does not display the message. The application logs show SMTPAuthenticationError: 535 Authentication failed. Which configuration change is MOST appropriate?

A) Enable TLS on MailHog by setting --smtp-tls and provide a valid certificate. B) Remove or disable SMTP authentication in the application's email settings, as MailHog does not require authentication by default.

C) Change the SMTP port to 25 and use the system's default mail transfer agent. D) Configure the application to use the MailHog API endpoint on port 8025 instead of SMTP.

Answer: B Rationale: MailHog's SMTP server accepts unauthenticated connections by default; the error indicates the client is attempting authentication. Disabling auth resolves it. TLS and port changes are irrelevant; the API endpoint is for retrieving messages, not sending.

23 In a Python logging configuration, a developer sets up a RotatingFileHandler with maxBytes=1024 and backupCount=3. After the log file exceeds 1024 bytes multiple times, how many total log files exist, and what happens when the fourth rotation occurs?

A) Four files exist; the oldest is deleted and a new file is created. B) Three files exist; the current log is overwritten and no backups are kept. C) Four files exist; the current log is renamed to .1, and the previous .3 is deleted.

D) Two files exist; the handler stops logging until the file is manually cleared.

Answer: C Rationale: RotatingFileHandler keeps the current file plus backupCount rotated files (e.g., .1, .2, .3). On rotation, .3 is removed, .2->.3, .1->.2, and the current becomes .1, so four files total. Options A, B, and D misstate the handler's behavior.

24 A Python script uses try/except/else/finally to interact with a database. The try block executes a query and raises a DatabaseError. The except block handles it, but the else block also runs. Which statement about the else block is correct?

A) The else block runs only if the try block completes without raising an exception.

B) The else block runs regardless of whether an exception occurred. C) The else block runs only if an exception is raised and not caught.

D) The else block runs before the except block if both are present.

Answer: A Rationale: The else clause executes only when the try block finishes without an exception. If an exception is raised and caught, else is skipped. Options B, C, and D contradict this control flow.

25 A developer wants to log exceptions with full traceback information while also sending a concise alert email. Which combination of logging and exception handling BEST achieves this without duplicating traceback output?

A) Use logging.error(str(e)) in the except block and send the email with traceback.format_exc().

B) Use logging.exception('Error occurred') in the except block and send the email with str(e) only.

C) Use logging.error('Error occurred', exc_info=True) and send the email with traceback.format_exc().

D) Use logging.critical(e) and send the email with repr(e).

Answer: C Rationale: logging.error(..., exc_info=True) includes the traceback in the log, while traceback.format_exc() provides the same for the email without duplicating in the log. Option A logs only the message, B uses logging.exception (which already includes traceback) and sends a short email, D lacks traceback detail.

26 An API returns a JSON payload with nested fields. A Python script uses response.json() but occasionally receives a 204 No Content response, causing a json.decoder.JSONDecodeError. Which handling strategy is MOST robust?

A) Check response.status_code == 204 before calling .json(), and return None or an empty dict for that case.

B) Wrap .json() in a try/except JSONDecodeError and log the raw text. C) Set response.encoding = 'utf-8' before calling .json(). D) Use response.text and parse with json.loads() after stripping whitespace.

Answer: A Rationale: A 204 response has no body, so calling .json() is invalid. Checking status code first prevents the error. Option B catches the error but doesn't prevent it; C and D do not address the empty body issue.

27 A Python script uses smtplib.SMTP to send emails through MailHog. The script must handle transient network failures and ensure the connection is closed even if an exception occurs. Which code pattern BEST achieves this?

Answer: C Rationale: A custom AuthBase subclass can encapsulate token management, checking expiry and refreshing before the request is sent. Option A only refreshes after failure; B is not how adapters work; D's Retry does not refresh tokens, only retries the same request.

30 A developer wants to log messages to both the console and a file, but with different formats: console should show LEVEL: message, file should show TIMESTAMP - LEVEL - message. Which logging configuration achieves this?

A) Use a single Formatter and set different levels for each handler. B) Create two handlers, assign a distinct Formatter to each, and attach both to the logger.

C) Use logging.basicConfig with format and filename parameters. D) Use a Filter to modify the message format based on the handler.

Answer: B Rationale: Each handler can have its own Formatter, allowing different formats for console and file. Option A uses one format for both; C sets a single format; D misuses filters, which do not alter format strings.

31 A Python automation script uses requests to call a REST API that returns a 429 status with a Retry-After header. Which implementation most correctly handles transient rate limiting while preserving idempotency and avoiding thundering-herd retries?

A) Immediately retry in a tight loop until a 200 response is received, ignoring Retry-After.

B) Sleep for a fixed 1 second and retry indefinitely on any non-2xx status. C) Parse Retry-After, apply exponential backoff with jitter, cap attempts, and only retry idempotent methods.

D) Raise a custom exception on the first 429 and log it at CRITICAL without retrying.

Answer: C Rationale: Retry-After should be honored, and exponential backoff with jitter prevents synchronized retry storms while capping attempts avoids infinite loops. Retrying only idempotent methods (GET, PUT, DELETE) preserves safety. Tight loops, fixed sleeps, or no retry all mishandle transient rate limiting.

32 In MailHog, which configuration most reliably prevents messages from an automated test suite from being delivered to real external recipients while still allowing SMTP-level assertions?

A) Set the application's SMTP host to MailHog and port to 1025, and never configure MailHog to relay outbound mail.

B) Set the application's SMTP host to the real MX server but add a BCC to MailHog.

C) Use MailHog's HTTP API to delete messages after each test without changing SMTP settings.

D) Configure MailHog with --smtp-bind-addr 0.0.0.0 and --outgoing-smtp to the production relay.

Answer: A Rationale: MailHog is a local SMTP sink on port 1025 by default and does not relay unless explicitly configured with an outgoing SMTP server. Pointing the app at MailHog and avoiding outbound relay guarantees no external delivery. BCC to MailHog still sends to real recipients; deleting after send is too late; configuring outgoing SMTP would relay to production.

33 A logging setup uses a RotatingFileHandler with maxBytes=1_000_000 and backupCount=3. After 3.5 MB of logs have been written, how many log files exist and what is the maximum total disk footprint?

A) 4 files; up to 4 MB total. B) 3 files; up to 3 MB total. C) 4 files; up to 3.5 MB total. D) 5 files; up to 5 MB total.

Answer: A Rationale: RotatingFileHandler keeps the active file plus backupCount rotated files, so 1 active + 3 backups = 4 files. Each file can reach maxBytes (1 MB), giving a maximum footprint of about 4 MB. The other options misstate the file count or the per-file cap.

34 Which try/except/finally structure correctly guarantees that a file handle is released and that a specific network error is logged without masking an unrelated ValueError?

A) try: ... except Exception: log; finally: close B) try: ... except (ConnectionError, TimeoutError) as e: log(e); finally: f.close() C) try: ... except: pass; finally: f.close() D) try: ... except ConnectionError: log; else: f.close()

C) Both interfaces are read-only and cannot delete messages. D) SMTP and HTTP API are interchangeable and both support message deletion.

Answer: A Rationale: MailHog receives messages via SMTP on port 1025 and exposes an HTTP API (default 8025) for listing, inspecting, and deleting messages. The HTTP API does not send mail, and deletion is an API capability, not an SMTP one. The other options invert or misstate these roles.

38 A script must log structured JSON with a timestamp, level, and correlation ID across modules. Which design most correctly achieves consistent structured logging without duplicating configuration?

A) Call logging.basicConfig in every module with a JSON formatter. B) Configure a single root logger with a JSON formatter and a filter that injects the correlation ID, then use module-level getLogger(name).

C) Use print(json.dumps(...)) in each module instead of the logging module. D) Create a new FileHandler in each module with a plain text formatter.

Answer: B Rationale: Centralizing configuration on the root logger with a JSON formatter and a filter for the correlation ID yields consistent structured output and avoids duplicate handlers. Repeated basicConfig calls are no-ops after the first, per-module handlers cause duplication, and print bypasses the logging framework.

39 Which exception-handling pattern best preserves the original traceback while adding contextual information when re-raising an API error?

A) except APIError as e: raise APIError('context') B) except APIError as e: raise APIError('context') from e C) except APIError as e: print(e); raise D) except APIError as e: raise e.with_traceback(None)

Answer: B Rationale: Using 'raise ... from e' chains exceptions, preserving the original traceback as the cause while adding context. Re-raising a new exception without 'from' loses the chain; printing then bare raise adds no context; clearing the traceback destroys diagnostic information.

40 A test suite asserts that an email was sent. Which MailHog-based verification most robustly confirms the correct recipient, subject, and body without race conditions?

A) Immediately call the MailHog API once after triggering the send.

B) Poll the MailHog API with a timeout until a matching message appears, then assert on recipient, subject, and decoded body.

C) Sleep for a fixed 5 seconds, then query the API once. D) Check the application log for 'email sent' without querying MailHog.

Answer: B Rationale: Polling with a timeout handles asynchronous delivery without flaky fixed sleeps, and asserting on recipient, subject, and decoded body verifies content. A single immediate call may race, fixed sleeps are slow and unreliable, and log assertions do not prove MailHog received the message.

41 A Python automation script uses requests.Session() to call a REST API. After the first successful call, all subsequent calls return 401 even though the token is still valid. Which mechanism most likely explains this behavior?

A) The session object persists cookies, and the API invalidates the session cookie after one request.

B) The API uses short-lived bearer tokens that expire after a single request. C) The default Connection: close header forces re-authentication on each request. D) The session reuses the TCP connection, and the server drops the Authorization header on keep-alive.

Answer: A Rationale: A requests.Session persists cookies across requests; if the API sets a session cookie that is invalidated server-side after first use, subsequent requests carry a stale cookie and receive 401. Bearer tokens are not single-use by default, Connection: close does not trigger re-auth, and servers do not strip Authorization on keep-alive.

42 An exception handler catches requests.exceptions.RequestException but the script still crashes on a DNS failure. Which exception subclass is NOT caught by that handler?

A) requests.exceptions.ConnectionError B) requests.exceptions.Timeout C) socket.gaierror D) requests.exceptions.HTTPError

Answer: C Rationale: socket.gaierror is raised by the underlying socket layer and is not a subclass of RequestException, so it escapes the handler. ConnectionError, Timeout, and HTTPError are all subclasses of RequestException and would be caught.

last_attempt attribute holds the final Future containing the original exception. The original exception is not re-raised directly, it is not suppressed, and catch order depends on the exception hierarchy, not on RetryError specifically.

46 A log record is emitted with logging.exception('failed') inside an except block. Compared to logging.error('failed'), what additional information does logging.exception include?

A) The current stack frame's local variables. B) The exception type, message, and traceback. C) The HTTP status code of the last API call. D) The logger's effective level and handler list.

Answer: B Rationale: logging.exception logs at ERROR level and automatically appends the current exception's type, message, and traceback via exc_info=True. It does not capture local variables, HTTP status codes, or logger configuration metadata.

47 An API returns a 429 status with a Retry-After: 30 header. A script using requests with no retry logic immediately retries and receives another 429. Which change best implements correct backoff behavior?

A) Wrap the call in a loop with time.sleep(30) before each retry. B) Use requests.adapters.HTTPAdapter with max_retries=Retry(total=5, backoff_factor=1).

C) Set stream=True to keep the connection open until the server is ready. D) Switch to http.client which automatically honors Retry-After.

Answer: A Rationale: The Retry-After header specifies an exact wait; honoring it requires reading the header and sleeping that duration, which a manual loop with time.sleep(30) accomplishes. HTTPAdapter with backoff_factor uses exponential backoff and ignores Retry-After by default, stream=True is unrelated, and http.client does not auto-honor the header.

48 A custom exception class is defined as class APIError(Exception): pass. A caller writes except APIError as e: raise inside a nested handler. What is the effect of the bare raise?

A) It raises a new APIError with an empty message. B) It re-raises the currently handled exception with its original traceback. C) It raises RuntimeError because no active exception exists. D) It suppresses the exception and returns None.

Answer: B Rationale: A bare raise inside an except block re-raises the active exception preserving its original traceback. It does not create a new instance, raise RuntimeError, or suppress the exception.

49 A script uses logging.config.dictConfig to set up handlers. After configuration, a module-level logger created before dictConfig is called does not emit records. Which is the most likely reason?

A) dictConfig disables all loggers created before it runs unless disable_existing_loggers is False.

B) dictConfig only configures loggers whose names are listed in the loggers key.

C) Module-level loggers cannot be reconfigured after import. D) dictConfig requires incremental=True to affect existing loggers.

Answer: A Rationale: By default dictConfig sets disable_existing_loggers=True, disabling loggers not explicitly named in the configuration. Setting it to False preserves them. Loggers can be reconfigured post-import, and incremental is unrelated to this behavior.

50 A function uses a finally block that executes return 'cleanup'. The try block also executes return 'result'. What value is returned, and why?

A) 'result', because the try return takes precedence. B) 'cleanup', because finally overrides the try return. C) A SyntaxError is raised for conflicting returns. D) None, because the returns cancel each other.

Answer: B Rationale: A return in a finally block overrides any return or exception from the try block, so 'cleanup' is returned. This is valid syntax, not an error, and the returns do not cancel to None.