Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.22 KB | None | 0 0
  1. from flask import request,Flask,Response,render_template,redirect,send_file,make_response
  2. app = Flask(__name__)
  3. DBLOCATION='./sattasite.db'
  4. ADMINPASS="changeme@line4"
  5. @app.errorhandler(404)
  6. def page_not_found(e):
  7. return 'Sorry, nothing at this URL.bhag yaha se.', 404
  8.  
  9. def check_auth(username, password):
  10. return username == 'admin' and password == ADMINPASS
  11. def authenticate():
  12. return Response('You have to login with proper credentials for this url', 401,{'WWW-Authenticate': 'Basic realm="Login Required"'})
  13.  
  14. from functools import wraps
  15. def requires_auth(f):
  16. @wraps(f)
  17. def decorated(*args, **kwargs):
  18. auth = request.authorization
  19. if not auth or not check_auth(auth.username, auth.password):
  20. return authenticate()
  21. return f(*args, **kwargs)
  22. return decorated
  23.  
  24. from datetime import datetime,timedelta
  25. from pytz import timezone
  26. import sqlite3
  27. def getstor():
  28. conn = sqlite3.connect('sattasite.db')
  29. c = conn.cursor()
  30. try:x=list(c.execute('SELECT key,value from stor'))
  31. except:
  32. x=list(c.execute('CREATE TABLE stor(key text,value text)'))
  33. x=list(c.execute('SELECT key,value from stor'))
  34. c.close()
  35. conn.commit()
  36. conn.close()
  37. return dict(x)
  38. def setstor(kvps):
  39. if type(kvps)==type({}):kvps=list(kvps.items())
  40. old=getstor()
  41. conn = sqlite3.connect('sattasite.db')
  42. c = conn.cursor()
  43. c.executemany('delete from stor where key like ?',[[k] for k,v in kvps if k in old])
  44. c.executemany('insert into stor values(?,?)', kvps)
  45. c.close()
  46. conn.commit()
  47. conn.close()
  48. return "stored"
  49. def tb2hm(ct):
  50. conn = sqlite3.connect(DBLOCATION)
  51. c = conn.cursor()
  52. c.execute('SELECT cthmpgname FROM ctnm where ctblename like ?', [ct])
  53. rt=c.fetchone()
  54. #print('tb2hm',ct,'fetch',rt)
  55. conn.commit()
  56. #c.close()
  57. conn.close()
  58. return rt[0]
  59. def hm2tb(ct):
  60. conn = sqlite3.connect(DBLOCATION)
  61. c = conn.cursor()
  62. c.execute('SELECT ctblename FROM ctnm where cthmpgname like ?', [ct])
  63. rt=c.fetchone()
  64. #print('tb2hm',ct,'fetch',rt)
  65. conn.commit()
  66. #c.close()
  67. conn.close()
  68. return rt[0]
  69. def showHome(dd,mm,yy):
  70. conn = sqlite3.connect(DBLOCATION)
  71. c = conn.cursor()
  72. for row in c.execute('SELECT * FROM data WHERE mm=? and yy=? and dd=?',[mm,yy,dd]):
  73. #print("row",row)
  74. row=list(row)
  75. row[3]=tb2hm(row[3])
  76. row.append(__import__('urllib').parse.urlencode({"month":mm,"year":yy,"city":row[3]}))
  77. yield row
  78. conn.commit()
  79. conn.close()
  80.  
  81. @app.route('/')
  82. def home():
  83. now=datetime.now(timezone('Asia/Kolkata'))
  84. today=now.strftime('%d %m %Y').split(),now.strftime('%B %d, %Y')
  85. yester=now-timedelta(days=1)
  86. yester=yester.strftime('%d %m %Y').split(),yester.strftime('%B %d, %Y')
  87. return render_template("home.html",dataT=showHome(*today[0]),today=today[1],yest=yester[1],dataY=showHome(*yester[0]),showFH=showFor(1))
  88.  
  89. @app.route('/showFor')
  90. def showFor(hide=0):
  91. tmm,tyy=datetime.now(timezone('Asia/Kolkata')).strftime('%m %Y').split()
  92. mm,yy,city=request.args.get('month',tmm),request.args.get('year',tyy),request.args.get('city','')
  93. if hide==0:hide=request.args.get('hide','no')
  94. if hide==1:hide=''
  95. conn = sqlite3.connect(DBLOCATION)
  96. c = conn.cursor()
  97. header=["DATE"]
  98. if not city:city=list(x[0] for x in c.execute('SELECT cthmpgname FROM ctnm where isspecial="1"'))[0]
  99. spcities=list(x[0] for x in c.execute('SELECT ctblename FROM ctnm where isspecial="1"'))
  100. spcities=sorted(spcities,key=lambda k:dict(zip("DSWR FRBD GZBD GALI".split(),range(4))).get(k,-1))#tries to maintain the order
  101. header+=spcities
  102. cols=[]
  103. for spcty in spcities:
  104. rows=list(c.execute('SELECT dd,count FROM data WHERE mm=? and yy=? and cTname like ?',[mm,yy,spcty]))
  105. cols.append(sorted(rows,key=lambda dc:int(dc[0])))
  106. cityT=hm2tb(city)
  107. if cityT not in spcities:
  108. header.append(cityT)
  109. rows=list(c.execute('SELECT dd,count FROM data WHERE mm=? and yy=? and cTname like ?',[mm,yy,cityT]))
  110. cols.append(sorted(rows,key=lambda dc:int(dc[0])))
  111. #cols=list([es[0][0]]+[e[1] for e in es] for es in zip(*cols))
  112. cols=list([sorted([e[0] for e in es])[0]]+[e[1] for e in es] for es in __import__('itertools').zip_longest(*cols,fillvalue=['??']*2))
  113. cols=sorted(cols,key=lambda x:int(x[0]))
  114. #cols=[header]+cols
  115. conn.commit()
  116. conn.close()
  117.  
  118. pmm,pyy=int(mm)-1,yy
  119. if pmm==0:pyy,pmm=str(int(pyy)-1),12
  120. pmm="{:02}".format(pmm)
  121. nmm,nyy=int(mm)+1,yy
  122. if nmm==13:nyy,nmm=str(int(nyy)+1),1
  123. nmm="{:02}".format(nmm)
  124. prevU="/showFor?"+__import__('urllib').parse.urlencode({"month":pmm,"year":pyy,"city":city,"hide":hide})
  125. nextU="/showFor?"+__import__('urllib').parse.urlencode({"month":nmm,"year":nyy,"city":city,"hide":hide})
  126. prevS,nextS=datetime(*map(int,[pyy,pmm,1])).strftime("%b %Y"),datetime(*map(int,[nyy,nmm,1])).strftime("%b %Y")
  127. mmS=datetime(*map(int,[yy,mm,1])).strftime("%B")
  128. if int(nyy+nmm)>int(tyy+tmm):nextU=""
  129. if int(pyy+pmm)<201501:prevU=""
  130. nav={"prev_url":prevU,"prev_str":"< {}".format(prevS),"next_url":nextU,"next_str":"{} >".format(nextS)}
  131. return render_template("showFor.html",hide=request.path=="/",data=cols,header=header,mm=mm,mmS=mmS,yy=yy,city=hide and city,cityT=cityT,nav=nav,search=searchMMDD())
  132.  
  133. @app.route('/subscribe',methods=['POST'])
  134. def subscribePost():
  135. if request.method=='POST':
  136. import time
  137. name,phno,time,ip=request.form.get("username","-"),request.form.get("phno","-"),time.time(),request.remote_addr
  138. with open("subscribers.csv","a") as f:
  139. f.write("{},{},{},{}".format(name,phno,time,ip))
  140. return redirect("/",code=302)
  141. @app.route('/subscribe',methods=['GET'])
  142. @requires_auth
  143. def subscribeGET():
  144. if request.method=='GET':
  145. import pandas as pd
  146. df=pd.read_csv("subscribers.csv",header=None,names="Name PhoneNo Time I/P".split())
  147. df['Time']=df.Time.astype("int64")
  148. return df.to_html()
  149.  
  150.  
  151. @app.route('/search',methods=['GET','POST'])
  152. def searchMMDD():
  153. #autoupdate db-scrap
  154. warn,updiff="Updated {} seconds ago.",''
  155. lastupdateToday=getstor().get('lastupdateToday',1)
  156. if not lastupdateToday:
  157. updateHomePage()
  158. else:
  159. updiff=int(__import__('time').time())-int(lastupdateToday)
  160. if updiff<60*60*1:#less than 1hr
  161. pass
  162. elif updiff<60*60*23 and updiff>60*60*1:#more than 1hr but less than 23hr
  163. updateHomePage()
  164. updiff=1
  165. elif updiff<60*60*24*29:#less than 1month
  166. #update this+lastmonth+today
  167. tmm,tyy=datetime.now(timezone('Asia/Kolkata')).strftime('%m %Y').split()
  168. updatePast(dcity="all",dmm=tmm,dyy=tyy)
  169. tmm,tyy=("{:02}".format(int(tmm)-1),tyy) if tmm!='01' else ('12',str(int(tyy)-1))
  170. updatePast(dcity="all",dmm=tmm,dyy=tyy)
  171. updateHomePage()
  172. updiff=1
  173. else:
  174. warn="Warning: SiteData not autoupdated since last month or more ({}secs). Kindly follow admin guide to update data manually."
  175. warn=warn.format(updiff)
  176. if request.method=='POST':
  177. cty=__import__('urllib').parse.parse_qs(request.referrer).get('city',[''])[0]
  178. if not cty:
  179. conn = sqlite3.connect(DBLOCATION)
  180. c = conn.cursor()
  181. cty=list(x[0] for x in c.execute('SELECT cthmpgname FROM ctnm where isspecial="1"'))[0]
  182. conn.commit()
  183. conn.close()
  184. mm,yy=request.form.get('month','12'),request.form.get('year','2018')
  185. return redirect("/showFor?"+(__import__('urllib').parse.urlencode({"month":mm,"year":yy,"city":cty,"hide":""})), code=302)
  186. months = [datetime(2018, i, i).strftime('%d %B').split() for i in range(1,13)]
  187. years = list(range(2015,datetime.now(timezone('Asia/Kolkata')).year+1))[::-1]
  188. return render_template("search.html",months=months,years=years,msg=warn)
  189.  
  190. def urlpath(url):
  191. import sys
  192. if sys.version_info[0] < 3:
  193. import urllib
  194. return urllib.splitquery(url)[0]
  195. else:
  196. from urllib.parse import urlparse,urlunparse
  197. return urlunparse(list(urlparse(url))[:3]+['']*3)
  198. def scrapTodayYest():
  199. import requests
  200. from bs4 import BeautifulSoup as bsp
  201. a2m=lambda ahi:{
  202. 'game':ahi.parent.h2.text,
  203. 'time':ahi.previousSibling.previousSibling.text,
  204. 'url':ahi['href'],
  205. 'tvalue': ahi.parent.parent.h3.text
  206. }
  207. rh=requests.get('https://satta-king-fast.com/')
  208. sp=bsp(rh.text,'html.parser')
  209. ahrefs=filter(lambda a:a.text=="Record Chart",sp.findAll('a'))
  210. temps=[[d['url'],d['game'],d['time'],d['tvalue']] for d in map(a2m,ahrefs)]
  211. rt=dict()
  212. for url,game,time,tv in temps:
  213. rt[game]=rt.get(game,{'url':urlpath(url),'dt-val-ts':[]})
  214. rt[game]['dt-val-ts'].append([tv,time])
  215. dates=[t.findAll('h1')[0].text.split()[-2].replace(',','') for t in sp.findAll('table')[:2]]
  216. for game in rt:
  217. rt[game]['dt-val-ts']=list(map(lambda xy:[xy[0]]+xy[1],zip(dates,rt[game]['dt-val-ts'])))
  218. return rt
  219. @app.route('/updateToday')
  220. def updateHomePage():
  221. temps=scrapTodayYest()
  222. #turn temps to rows
  223. rows=[]
  224. mmtoday,yytoday=datetime.now(timezone('Asia/Kolkata')).strftime('%m %Y').split()
  225. for cT,V in temps.items():
  226. try:cT=hm2tb(cT)
  227. except TypeError as e:
  228. if str(e)=="'NoneType' object is not subscriptable":
  229. #do good
  230. resetCityListing(confirm="yes")
  231. cT=hm2tb(cT)
  232. for dt,val,up in V['dt-val-ts']:
  233. rows.append([dt,mmtoday,yytoday,cT,val,up])
  234. #print(rows)
  235. conn = sqlite3.connect(DBLOCATION)
  236. c = conn.cursor()
  237. #delete overlapping rows: dd,mm,yy,ciTy
  238. #for dd,mm,yy,ct,val,up in rows:
  239. # c.execute('delete from data where dd=? and mm=? and yy=? and cTname like ?',[dd,mm,yy,ct])
  240. c.executemany('delete from data where dd=? and mm=? and yy=? and cTname like ?',[[dd,mm,yy,ct] for dd,mm,yy,ct,val,up in rows])
  241. #insert these rows
  242. c.executemany('INSERT INTO data VALUES (?,?,?,?,?,?)',rows)
  243. #c.close()
  244. conn.commit()
  245. conn.close()
  246. setstor({"lastupdateToday":int(__import__('time').time())})
  247. return "Updated"
  248. @app.route('/updateThen')
  249. def updatePast(dmm=None,dcity=None,dyy=None):
  250. mm,yy,city=(dmm or request.args['month']),(dyy or request.args['year']),(dcity or request.args['city'])
  251. if city=="all":
  252. conn = sqlite3.connect(DBLOCATION)
  253. c = conn.cursor()
  254. cities=list(x[0] for x in c.execute('SELECT cthmpgname FROM ctnm'))
  255. c.close()
  256. conn.close()
  257. for citi in cities:updatePast(dcity=citi,dmm=dmm,dyy=dyy)
  258. return "ALLSUCCESS"
  259. if mm=="all":
  260. months=["{:02}".format(m) for m in range(1,13)]
  261. for m in months:updatePast(dmm=m,dcity=city,dyy=dyy)
  262. return "ALLSUCCESS"
  263.  
  264. dateobj={"month":mm,"year":yy}
  265. #find cityurl
  266. conn = sqlite3.connect(DBLOCATION)
  267. c = conn.cursor()
  268. c.execute('SELECT cturl FROM ctnm where cthmpgname like ?', [city])
  269. rt=c.fetchone()
  270. c.close()
  271. #conn.commit()
  272. conn.close()
  273. if not rt:return resetCityListing("yes") and updatePast(mm,city,yy)
  274. cityurl=rt[0]
  275. cityurl=cityurl+"?"+__import__('urllib').parse.urlencode({"month":mm,"year":yy})
  276. #find special ciTynames
  277. conn = sqlite3.connect(DBLOCATION)
  278. c = conn.cursor()
  279. specials=c.execute('SELECT ctblename FROM ctnm where isspecial="1"')
  280. specials=[x[0] for x in specials]
  281. c.close()
  282. #conn.commit()
  283. conn.close()
  284. #scrap cityurl
  285. import requests
  286. from bs4 import BeautifulSoup as bsp
  287. r=requests.get(cityurl)
  288. spi=bsp(r.text,'html.parser')
  289. dates=spi.findAll('td',attrs={'class':'day'})
  290. vals=spi.findAll('td',attrs={'class':'number'})
  291. names=spi.findAll('th',attrs={'class':'name'})
  292. notspecial=names[-1].text if len(names)>len(specials) else ''
  293. specialcity='' if notspecial else hm2tb(city)
  294. ln,ld,objs=len(names),len(dates),[]
  295. for i,iv in enumerate(vals):
  296. if notspecial:
  297. if names[i%ln].text==notspecial:
  298. objs.append([dates[i//ln].text,mm,yy,names[i%ln].text,iv.text,''])
  299. else:
  300. if names[i%ln].text==specialcity:
  301. objs.append([dates[i//ln].text,mm,yy,names[i%ln].text,iv.text,''])
  302. rows=objs
  303. #return str(rows)
  304. conn = sqlite3.connect(DBLOCATION)
  305. c = conn.cursor()
  306. #delete overlapping rows: dd,mm,yy,ciTy
  307. c.executemany('delete from data where dd=? and mm=? and yy=? and cTname like ?',[[dd,mm,yy,ct] for dd,mm,yy,ct,val,up in rows])
  308. ##insert these rows
  309. c.executemany('INSERT INTO data VALUES (?,?,?,?,?,?)',rows)
  310. c.close()
  311. conn.commit()
  312. conn.close()
  313. return "Success"
  314.  
  315. @app.route('/resetCityList')
  316. def resetCityListing(confirm=""):
  317. if request.args.get('confirm',confirm)!="yes":return "As this one truncates scrapped city meta data:GOTO /resetCityList?confirm=yes"
  318. temps=scrapTodayYest()
  319. ctdd=[]
  320. specials={"DESAWAR - DS":"DSWR","FARIDABAD - FB":"FRBD","GHAZIABAD - GB":"GZBD","GALI - GL":"GALI"}
  321. for t in temps:
  322. ctdd.append([temps[t]['url'],t,(t[:-4].strip().title() if t not in specials else specials[t]),t in specials])
  323. corrections={'LUCKY HARUF - LH':'Lucky Huruf',"GALI No.1 - G1":"Gali No. 1"}
  324. for i in range(len(ctdd)):
  325. if ctdd[i][1] in corrections:
  326. ctdd[i][2]=corrections[ctdd[i][1]]
  327. conn = sqlite3.connect(DBLOCATION)
  328. c = conn.cursor()
  329. #todo:dangerous to drop all, instead only delete those which will be replaced by ctdd#DONE
  330. try:
  331. #c.execute("DROP TABLE ctnm")
  332. c.executemany("DELETE from ctnm where cthmpgname=? or ctblename=?",[[cthm,cttb] for _1,cthm,cttb,_2 in ctdd])
  333. except:
  334. pass
  335. #c.execute('''CREATE TABLE ctnm(cturl text, cthmpgname text, ctblename text, isspecial text)''')
  336. c.executemany('INSERT INTO ctnm VALUES (?,?,?,?)', ctdd)
  337. c.close()
  338. conn.commit()
  339. conn.close()
  340. return "resetED. GLHF."
  341.  
  342. @app.route('/initData')
  343. @requires_auth
  344. def initData():
  345. if request.args.get('confirm','')!="yes":return "As this one truncates scrapped data:GOTO /initData?confirm=yes"
  346. conn = sqlite3.connect(DBLOCATION)
  347. c = conn.cursor()
  348. try:c.execute("DROP TABLE data")
  349. except:pass
  350. c.execute('''CREATE TABLE data(dd text,mm text,yy text,cTname text,count text,upTs text)''')
  351. #c.execute('''CREATE TABLE ctnm(cturl text, cthmpgname text, ctblename text, isspecial text)''')
  352. c.close()
  353. conn.commit()
  354. conn.close()
  355. return "Done. All db.data empty now. :("
  356.  
  357. @app.route('/downloaddb')
  358. @requires_auth
  359. def downdb():
  360. return send_file(DBLOCATION, as_attachment=True)
  361.  
  362. @app.route('/uploaddb',methods=['GET','POST'])
  363. @requires_auth
  364. def updb():
  365. if request.method=="GET":
  366. return '<form method="POST" enctype="multipart/form-data"><input type="file" name="db"><input type="submit">'+request.args.get('msg','')
  367. if 'db' in request.files and request.files['db'] and request.files['db'].filename.endswith('.db'):
  368. request.files['db'].save(DBLOCATION)
  369. return "Success"
  370. return redirect("/uploaddb?msg=Retry!")
  371.  
  372. @app.route('/site-map.xml')
  373. @app.route('/sitemap.xml')
  374. def sm():
  375. pages=[]
  376. months = [datetime(2018, i, i).strftime('%d') for i in range(1,13)]
  377. years = list(range(2015,datetime.now(timezone('Asia/Kolkata')).year+1))[::-1]
  378. conn = sqlite3.connect(DBLOCATION)
  379. c = conn.cursor()
  380. cities=list(x[0] for x in c.execute('SELECT cthmpgname FROM ctnm'))
  381. conn.commit()
  382. conn.close()
  383. for mm in months:
  384. for yy in years:
  385. lastmod=datetime(int(yy), int(mm), 1,tzinfo=timezone('Asia/Kolkata'))+timedelta(days=29)
  386. if datetime.now(timezone('Asia/Kolkata'))<lastmod:lastmod=datetime.now(timezone('Asia/Kolkata'))
  387. lastmod=lastmod.isoformat()
  388. for ctyh in cities:
  389. url="{}showFor?{}".format(request.url_root,__import__('urllib').parse.urlencode({"month":mm,"year":yy,"city":ctyh}))
  390. pages.append([url,lastmod])
  391. sitemap_xml = render_template('sitemap_template.xml', pages=pages)
  392. response= make_response(sitemap_xml)
  393. response.headers["Content-Type"] = "application/xml"
  394. return response
  395.  
  396. @app.route('/about')
  397. def about():
  398. return render_template("about.html")
  399.  
  400.  
  401. @app.route('/blog')
  402. def blog():
  403. return render_template("blog.html")
  404.  
  405.  
  406. @app.route('/blog/Satta-Matka-is-a-Kind-of-Gamble')
  407. def article1():
  408. return render_template("article1.html")
  409.  
  410.  
  411. @app.route('/blog/Satta-Matka-2019-is-very-Popular')
  412. def article2():
  413. return render_template("article2.html")
  414.  
  415. @app.route('/blog/Satta-Matka-Satrted-in-India')
  416. def article3():
  417. return render_template("article3.html")
  418.  
  419. @app.route('/knowledge')
  420. def knowledge():
  421. return render_template("knowledge.html")
  422.  
  423. @app.route('/knowledge-world')
  424. def knowledgeword():
  425. return render_template("knowledge-world.html")
  426.  
  427.  
  428. @app.route('/privacypolicy')
  429. def pravcypolicy():
  430. return render_template("pravcypolicy.html")
  431.  
  432. if __name__ == '__main__':
  433. app.run(host='0.0.0.0', port=80, debug=True,threaded=True)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement