






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!























50 QUESTIONS
# TOPIC
1 Design and implement Python scripts that interact with REST APIs using requests, including authentication, error handling, and pagination
2 Configure and utilize MailHog for testing email sending functionality in automated workflows
3 Implement robust logging and exception handling strategies to ensure reliable and maintainable automation scripts
4 WGU D522 Python for IT Automation API
5 MailHog
6 Logging & Exception Handling Guide Task 1 & Task 2 Support
7 Foundations of Python for IT Automation
8 Applied Python for IT Automation
9 Advanced Python for IT Automation
10 Python for IT Automation Review
This study document brings together 50 carefully worded exam questions drawn from WGU D Python for IT Automation API, MailHog, Logging & Exception Handling Guide Task 1 & Task 2 Support, with the strongest emphasis placed on 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 and Implement robust logging and exception handling strategies to ensure reliable and maintainable automation scripts. Every item follows the wording style and level of reasoning you meet in the real paper, and each one is paired with a clear rationale so the correct choice is never a guess. Work through the set at your own pace, mark the questions that slow you down, then come back to them until the reasoning feels automatic. Learners who revise this way walk into the exam room recognising the pattern behind the questions instead of meeting them for the first time. Keep going - steady, honest practice is what turns a difficult paper into a comfortable pass.
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. CORRECT
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.
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.
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. CORRECT
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.
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.
A. Check the status code; if 429, sleep for a fixed 60 seconds and retry indefinitely.
B. Use a library like tenacity to retry with exponential backoff, ignoring the 'Retry-After' header.
C. On 429, parse the 'Retry-After' header, sleep for that duration, and retry up to a maximum number of attempts. CORRECT
D. On 429, immediately retry without delay, as the rate limit may reset quickly.
RATIONALE: Option C respects the server's Retry-After header and sets a retry limit, which is polite and effective. Option A ignores the header and may retry too soon or too late. Option B ignores the header. Option D may exacerbate rate limiting.
A. Start MailHog with -smtp-bind-addr 0.0.0.0:1025 and use the /api/v2/messages endpoint to fetch messages. CORRECT
B. Start MailHog with -storage=memory and use the /api/v1/messages endpoint to fetch messages.
C. Start MailHog with -api-bind-addr 0.0.0.0:8025 and use the /api/v2/messages endpoint to fetch messages.
D. Start MailHog with -smtp-bind-addr 0.0.0.0:1025 and use the /api/v1/messages endpoint to fetch messages.
RATIONALE: MailHog's default storage is in-memory, and the API endpoint for messages is /api/v2/messages. Option A correctly binds SMTP to all interfaces. Option B uses an incorrect flag and endpoint. Option C binds the API but not SMTP. Option D uses an outdated API endpoint.
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. CORRECT
D. Use logging.basicConfig with filename and stream, and set systemd to capture the file.
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.
A. try-finally CORRECT
B. try-except-else
C. try-except
D. with statement
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.
A. Set the root logger level to DEBUG, add a FileHandler with level DEBUG and a StreamHandler with level ERROR. CORRECT
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.
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.
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.
C. Read the Retry-After header, sleep for the indicated seconds, then retry with exponential backoff and a capped retry count. CORRECT
D. Ignore the header and retry after a fixed 1-second delay regardless of the server's guidance.
RATIONALE: HTTP 429 is a transient rate-limit signal; honoring Retry-After and combining it with exponential backoff and a retry cap is the accepted production pattern. Option A causes a tight loop that worsens throttling, B misclassifies a recoverable error, and D ignores the server's explicit guidance.
A. The script is sending via SMTP but MailHog's UI only displays messages fetched over IMAP.
B. The script is targeting a real external SMTP server, or MailHog is bound to a different interface/port than the script is using. CORRECT
C. MailHog requires TLS on port 1025, so unencrypted messages are silently discarded.
D. MailHog only accepts messages from localhost, and the script is running in a container.
RATIONALE: MailHog captures messages sent to its configured SMTP listener (default 1025) and displays them in the UI on 8025; a mismatch in host, port, or pointing at a real server is the common failure. A is false because MailHog does not require IMAP, C is false (MailHog accepts plain SMTP by default), and D is false since MailHog accepts connections from any reachable interface.
A. One file only; the handler truncates on overflow.
B. Four files: app.log, app.log.1, app.log.2, app.log.3. CORRECT
C. Three files: app.log, app.log.1, app.log.2.
D. Two files: app.log and app.log.bak.
RATIONALE: RotatingFileHandler keeps the active app.log plus backupCount rotated files (app.log.1..app.log.3), totaling four. A describes no rotation, C omits the active file, and D is not the naming scheme used by the standard library.
A. Wrap the call in try/except json.JSONDecodeError and log the raw response body for diagnosis. CORRECT
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.
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.
A. logging.exception() automatically includes the traceback and must be called from an exception handler. CORRECT
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.
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.
A. It automatically retries failed requests with exponential backoff.
B. It reuses the underlying TCP connection and persists headers/cookies across requests. CORRECT
C. It converts all responses to JSON automatically.
D. It bypasses TLS certificate verification for speed.
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.
A. Query MailHog's HTTP API (e.g., /api/v2/messages) and parse the JSON body for the code. CORRECT
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.
RATIONALE: MailHog exposes a JSON API (v2) that automated tests can query and parse deterministically. B is unreliable, C is not automated, and D is false-MailHog does not provide an IMAP server by default.
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. CORRECT
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.
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.
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. CORRECT
D. Two files exist; the handler stops logging until the file is manually cleared.
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.
A. The else block runs only if the try block completes without raising an exception. CORRECT
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.
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.
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(). CORRECT
D. Use logging.critical(e) and send the email with repr(e).
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.
A. The message appears in both the console and the file.
B. The message appears only in the file.
C. The message appears only in the console.
D. The message is not recorded by either handler. CORRECT
RATIONALE: The logger's level (DEBUG) allows the message to be processed, but each handler filters independently. The StreamHandler (WARNING) and FileHandler (INFO) both ignore DEBUG, so the message is not recorded. Options A, B, and C incorrectly assume one handler would accept it.
A. Store the token in a global variable and refresh it only when a 401 response is received, then retry the request.
B. Use a session with an HTTPAdapter that automatically refreshes the token on every request.
C. Implement a custom AuthBase subclass that checks token expiry before each request and refreshes if needed. CORRECT
D. Set a Retry object with status_forcelist=[401] to automatically retry after refreshing the token.
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.
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. CORRECT
C. Use logging.basicConfig with format and filename parameters.
D. Use a Filter to modify the message format based on the handler.
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.
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. CORRECT
D. Raise a custom exception on the first 429 and log it at CRITICAL without retrying.
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.
A. try: ... except Exception: log; finally: close
B. try: ... except (ConnectionError, TimeoutError) as e: log(e); finally: f.close() CORRECT
C. try: ... except: pass; finally: f.close()
D. try: ... except ConnectionError: log; else: f.close()
RATIONALE: Catching the specific network exceptions preserves unrelated errors like ValueError, and finally always runs to close the handle. Catching bare Exception or using bare except masks or over-catches; using else to close only runs on success and skips cleanup on failure.
A. The message is emitted because the handler's DEBUG level overrides the logger.
B. The message is suppressed because the logger's effective level gates emission before handlers run. CORRECT
C. The message is emitted twice due to level mismatch.
D. The message is emitted only if propagate is False.
RATIONALE: Logger level filtering occurs before handlers are invoked, so a DEBUG record is dropped when the effective logger level is INFO. Handler levels only filter records that reach them. Propagation and duplicate emission are unrelated to this gate.
A. Loop while 'next' is non-null, follow the cursor, and track seen IDs to deduplicate. CORRECT
B. Request page=1..N in parallel with no cursor handling.
C. Increase page size to the maximum and assume a single request returns all data.
D. Retry the same first-page request until the dataset stops growing.
RATIONALE: Cursor-based pagination requires following the 'next' token until exhausted; tracking seen IDs guards against duplicates from shifting datasets. Parallel fixed pages, oversized single requests, and repeated first-page calls do not guarantee completeness or deduplication.
A. SMTP is used to send mail into MailHog; the HTTP API is used to query, inspect, and delete captured messages. CORRECT
B. The HTTP API sends mail; SMTP is only for retrieving messages.
C. Both interfaces are read-only and cannot delete messages.
D. SMTP and HTTP API are interchangeable and both support message deletion.
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.