|
18 | 18 |
|
19 | 19 | DEFAULT_TIMEOUT = 5 |
20 | 20 |
|
| 21 | +CRUMB_FAILURE = ( |
| 22 | + "Failed to obtain crumb. Ability to retrieve data will be significantly limited." |
| 23 | +) |
| 24 | + |
21 | 25 | HEADERS = [ |
22 | 26 | { |
23 | 27 | "upgrade-insecure-requests": "1", |
@@ -1362,42 +1366,47 @@ def initialize_session(session=None, **kwargs): |
1362 | 1366 | return session |
1363 | 1367 |
|
1364 | 1368 |
|
1365 | | -def setup_session(host: str): |
1366 | | - url = f"https://{host}/quote/tsla" |
1367 | | - session = requests.Session() |
1368 | | - session.headers = random.choice(HEADERS) |
| 1369 | +def setup_session(session: requests.Session): |
| 1370 | + url = "https://finance.yahoo.com" |
1369 | 1371 | try: |
1370 | | - _ = session.get(url, allow_redirects=True) |
| 1372 | + response = session.get(url, allow_redirects=True) |
1371 | 1373 | except SSLError: |
1372 | 1374 | counter = 0 |
1373 | 1375 | while counter < 5: |
1374 | 1376 | try: |
1375 | 1377 | session.headers = random.choice(HEADERS) |
1376 | | - _ = session.get(url, verify=False) |
| 1378 | + response = session.get(url, verify=False) |
1377 | 1379 | break |
1378 | 1380 | except SSLError: |
1379 | 1381 | counter += 1 |
1380 | 1382 |
|
1381 | | - if not session.cookies: |
1382 | | - return None, None |
| 1383 | + if not isinstance(session, FuturesSession): |
| 1384 | + return session |
1383 | 1385 |
|
1384 | | - crumb = get_crumb(session) |
1385 | | - return session.cookies, crumb |
| 1386 | + _ = response.result() |
| 1387 | + return session |
1386 | 1388 |
|
1387 | 1389 |
|
1388 | 1390 | def get_crumb(session): |
1389 | 1391 | try: |
1390 | 1392 | response = session.get("https://query2.finance.yahoo.com/v1/test/getcrumb") |
1391 | | - return response.text |
1392 | 1393 |
|
1393 | 1394 | except (ConnectionError, RetryError): |
1394 | | - logger.critical( |
1395 | | - "Failed to obtain crumb. Ability to retrieve data will be significantly " |
1396 | | - "limited." |
1397 | | - ) |
| 1395 | + logger.critical(CRUMB_FAILURE) |
1398 | 1396 | # Cookies most likely not set in previous request |
1399 | 1397 | return None |
1400 | 1398 |
|
| 1399 | + if isinstance(session, FuturesSession): |
| 1400 | + crumb = response.result().text |
| 1401 | + else: |
| 1402 | + crumb = response.text |
| 1403 | + |
| 1404 | + if crumb is None or crumb == "" or "<html>" in crumb: |
| 1405 | + logger.critical(CRUMB_FAILURE) |
| 1406 | + return None |
| 1407 | + |
| 1408 | + return crumb |
| 1409 | + |
1401 | 1410 |
|
1402 | 1411 | def flatten_list(ls): |
1403 | 1412 | return [item for sublist in ls for item in sublist] |
|
0 commit comments