import requests LOGIN_URL = "http://localhost:7777/user/login" EDIT_MILESTONE_URL = "http://localhost:7777/setyotontowi/experiments/milestones/1/edit" session = requests.Session() USERNAME = "setyotontowi" PASSWORD = "nasipadang" def login(): """Log in and store session cookies.""" print("Logging in...") payload = { "user_name": USERNAME, "password": PASSWORD } response = session.post(LOGIN_URL, data=payload) if response.status_code == 200: print("Login successful.") return True else: print(f"Login failed: {response.status_code} - {response.text}") return False def get_csrf_token(): """Fetch CSRF token from the edit milestone page.""" print("Fetching CSRF token...") response = session.get(EDIT_MILESTONE_URL) if response.status_code == 200: token = extract_csrf_token(response.text) if token: print(f"CSRF token obtained: {token}") return token else: print("Failed to extract CSRF token.") return None elif response.status_code == 401: # Unauthorized → Need to re-login print("Session expired, re-logging in...") return None else: print(f"Failed to get CSRF token: {response.status_code} - {response.text}") return None def extract_csrf_token(html): """Extract CSRF token from HTML using regex.""" import re match = re.search(r'name="_csrf" value="(.*?)"', html) if match: return match.group(1) return None