MYSPACE / app.py
justsomeonefrom's picture
Update app.py
995ed98 verified
raw
history blame contribute delete
6.98 kB
from flask import Flask, render_template, redirect, url_for, request, session, send_file
# from cookie import fetch_new_cookies
from bs4 import BeautifulSoup
import pandas as pd
import threading
import requests
import tempfile
import json
import os
# Setup Flask app
app = Flask(__name__)
app.secret_key = 'the_data_of_KV'
# Global variable to store student data
student_data = []
url = "https://epay.unionbankofindia.co.in/kvchallan/welcome.aspx"
# cookies = []
# fetch_cookie = fetch_new_cookies()
# if fetch_cookie:
# cookies.append(fetch_cookie)
# else:
# print("Failed to fetch cookies.")
# cookie = cookies[0] if cookies else None
cookie = "e1qvm22s3ouzn2njrla4yv45"
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Accept-Language': 'en-US,en;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': f'ASP.NET_SessionId={cookie}',
'DNT': '1',
'Origin': 'https://epay.unionbankofindia.co.in',
'Referer': 'https://epay.unionbankofindia.co.in/kvchallan/default.aspx',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'same-origin',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
'sec-ch-ua': '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"'
}
def main(payload):
student = payload.split('=')[1]
print(f"Checking for student code {student}...")
response = requests.post(url, headers=headers, data=payload)
data = response.text
if 'ctl00_ContentPlaceHolder1_lblName' in data:
name = data.split('ctl00_ContentPlaceHolder1_lblName">')[1].split('</span>')[0]
else:
return None
if name == '':
return None
else:
dob = data.split('ctl00_ContentPlaceHolder1_lblDOB">')[1].split('</span>')[0]
ubiId = data.split('ctl00_ContentPlaceHolder1_lblUnique">')[1].split('</span>')[0]
Class = data.split('ctl00_ContentPlaceHolder1_lblClass">')[1].split('</span>')[0]
school = data.split('ctl00_ContentPlaceHolder1_lblSchoolName">')[1].split('</span>')[0]
# Parsing HTML with BeautifulSoup to extract VIEWSTATE and other form data
soup = BeautifulSoup(data, 'html.parser')
viewstate = soup.find('input', {'id': '__VIEWSTATE'})['value']
eventvalidation = soup.find('input', {'id': '__EVENTVALIDATION'})['value']
# Prepare the payload for the POST request to simulate the button click
button_payload = {
'__VIEWSTATE': viewstate,
'__EVENTVALIDATION': eventvalidation,
'__EVENTTARGET': 'ctl00$ContentPlaceHolder1$lnkChallan',
'__EVENTARGUMENT': '',
'student_code': student
}
# Send the POST request to generate the challan
challan_response = requests.post(url, headers=headers, data=button_payload)
challan_data = challan_response.text
if challan_data.splitlines()[0].strip() == "<script>alert('Student is not active, can not generate challan!');</script>":
current_status = "No"
else:
current_status = "Yes"
json_entry = (
'\t{\n'
f' "name": "{name}",\n'
f' "dob": "{dob}",\n'
f' "ubiId": "{ubiId}",\n'
f' "class": "{Class}",\n'
f' "school": "{school}",\n'
f' "enrolled": "{current_status}"\n'
' }'
)
with open('data.json', 'w') as f:
json.dump(student_data, f, indent=4)
print(f"Name: {name}\nDOB: {dob}\nUBI ID: {ubiId}\nClass: {Class}\nSchool: {school}\nCurrently Enrolled: {current_status}\n")
return {
"name": name,
"dob": dob,
"ubiId": ubiId,
"class": Class,
"school": school,
"enrolled": current_status
}
# Background thread function
def background_worker():
payload = 'student_code=321456109002825' # Starting point
consecutive_failures = 0
year = int(payload.split('=')[1][7:9])
while True:
result = main(payload)
if result is None:
consecutive_failures += 1
else:
consecutive_failures = 0 # Reset on success
student_data.append(result)
if consecutive_failures == 100: # Increment year after 100 failures
consecutive_failures = 0
admission_number = int(payload.split('=')[1][-6:]) - 100
year += 1
payload = f'student_code=3214561{year}{admission_number :06d}'
# Increment student_code
student_number = int(payload.split('=')[1])
payload = f'student_code={student_number + 1:015d}'
# Start the background worker thread
threading.Thread(target=background_worker, daemon=True).start()
@app.route('/')
def index():
if 'logged_in' in session and session['logged_in']:
return redirect(url_for('dashboard'))
return render_template('login.html')
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
# Replace with actual authentication logic
login_username = os.getenv("username")
login_password = os.getenv("password")
if username == login_username and password == login_password:
session['logged_in'] = True
return redirect(url_for('dashboard'))
return 'Invalid credentials', 401
@app.route('/logout')
def logout():
session.pop('logged_in', None)
return redirect(url_for('index'))
@app.route('/dashboard')
def dashboard():
if 'logged_in' not in session or not session['logged_in']:
return redirect(url_for('index'))
return render_template('dashboard.html', data=student_data)
@app.route('/download')
def download():
if 'logged_in' not in session or not session['logged_in']:
return redirect(url_for('index'))
# Convert student data to a DataFrame
columns = ['Name', 'DOB', 'UBI ID', 'Class', 'School', 'Enrolled']
data = []
for student in student_data:
data.append([
student['name'],
student['dob'],
student['ubiId'],
student['class'],
student['school'],
student['enrolled']
])
df = pd.DataFrame(data, columns=columns)
# Save to a temporary Excel file
temp_dir = tempfile.gettempdir()
file_path = f"{temp_dir}/student_data.xlsx"
df.to_excel(file_path, index=False)
# Send the file to the user
return send_file(file_path, as_attachment=True, download_name='student_data.xlsx')
if __name__ == '__main__':
app.run(debug=True)