API调用缓存导致重复执行失败,如何彻底清除缓存并重试?
Got it, let's figure out why your MechanicalSoup-based buy loop is stuck failing repeatedly—caching is a solid suspect here, since MechanicalSoup relies on requests.Session which can hold onto cached responses or stale session data. Here are practical steps to fix this:
1. Disable Caching via Session Headers
Requests (and by extension MechanicalSoup) will cache responses by default for GET requests, and even POSTs can hit server-side caching. Add headers to your browser session that explicitly tell the server to skip cached content:
import mechanicalsoup # Initialize browser with anti-cache headers browser = mechanicalsoup.Browser() browser.session.headers.update({ 'Cache-Control': 'no-cache, no-store, must-revalidate', 'Pragma': 'no-cache', 'Expires': '0' }) # Then use this browser in your buy function while True: try: print("trying to buy a") buy(ashr, tickers[0], client, browser) # Pass the configured browser except Exception as e: print(f"Retry after error: {str(e)}") # Log errors to debug! continue break
2. Reset the Entire Session on Each Retry
If stale cookies or session state are the problem, creating a fresh browser instance every time you retry ensures you start with a clean slate:
while True: try: print("trying to buy a") # Create a new browser session for each attempt fresh_browser = mechanicalsoup.Browser() # Reinitialize your client with this fresh browser if needed fresh_client = your_client_setup_function(fresh_browser) buy(ashr, tickers[0], fresh_client) except Exception as e: print(f"Error encountered: {str(e)}") continue break
3. Manually Clear Cookies Between Attempts
If you don't want to recreate the whole browser, just clear the cookies stored in the session to avoid stale state:
browser = mechanicalsoup.Browser() while True: try: print("trying to buy a") # Wipe cookies before each request browser.session.cookies.clear() buy(ashr, tickers[0], client) except Exception as e: print(f"Retrying: {str(e)}") continue break
4. Verify You're Not Using Cached Responses
Add a check in your buy function to confirm if the response is coming from cache—this will help confirm if caching is indeed the issue:
def buy(ashr, ticker, client): # ... your existing form-filling code ... response = client.submit(form) # Check if the response was cached if hasattr(response, 'from_cache') and response.from_cache: print("WARNING: Got cached response!") # Handle this case (e.g., retry immediately) raise ValueError("Cached response received") # ... rest of your buy logic ...
Pro Tip: Avoid Bare except Clauses
Your current code uses a bare except, which catches all exceptions (including keyboard interrupts) and hides useful error details. Replace it with specific exceptions to debug what's actually failing:
except (requests.exceptions.RequestException, mechanicalsoup.FormNotFoundError) as e: print(f"Request/form error: {str(e)}") except Exception as e: print(f"Unexpected error: {str(e)}")
内容的提问来源于stack exchange,提问作者Carson P

