-
Notifications
You must be signed in to change notification settings - Fork 0
/
flask_main.py
167 lines (140 loc) · 4.9 KB
/
flask_main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from flask import Flask, render_template, request, flash
from werkzeug.utils import redirect
import requests
from datetime import datetime
import socket
import os
import psycopg2
import validators
from config import config
app = Flask(__name__, template_folder='templates')
app.secret_key = os.urandom(12)
def connectdb(): #connect to database
conn = None
try:
params = config()
conn = psycopg2.connect(**params)
except (Exception, psycopg2.DatabaseError) as error:
print(error)
return conn
def get_ip(): # get auto ip so all devices at the same LAN can access to the site
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
return IP
def getSites(): # get sites from db
db = connectdb()
data = []
cur = db.cursor()
cur.execute("SELECT sitename FROM sites")
data = cur.fetchall()
cur.close()
db.close()
return data
def splitted(data): #split site names
datasplitted = []
for x in data:
if(x[0][:8] == "https://"):
if(x[0][len(x[0])-1:]=='/'):
datasplitted.append(x[0][8:len(x[0])-1])
else:
datasplitted.append(x[0][8:])
return datasplitted
def getImgurl(): # get image urls from db
db = connectdb()
data = []
cur = db.cursor()
cur.execute("SELECT imgurl FROM sites")
data = cur.fetchall()
cur.close()
db.close()
return data
def is_url_image(image_url): #Checks if the given string is url and image
if(validators.url(image_url)):
image_formats = ("image/png", "image/jpeg", "image/jpg")
r = requests.head(image_url)
if r.headers["content-type"] in image_formats:
return True
return False
def getCurrentTime(): # get curren time
now = datetime.now()
current_time = now.strftime("%H:%M")
return current_time
def getRequest(site): # Send request to a site
req = requests.get(str(site))
return req
@app.route("/home") # homepage of the website
def home():
data = getSites()
return render_template('home.html', data=data, len=len(data), splitted=splitted(data), imgurl=getImgurl())
# return render_template('home.html', data=data, len=len(data), eltime=request.args.get('eltime'),
# statuscode=request.args.get('statuscode'), currenttime=request.args.get('currenttime'))
@app.route("/plot", methods=['POST']) # plotting datas
def plotting():
plot_str = request.form['plot_str']
data_eltime = []
data_statuscode = []
data_currenttime = []
db = connectdb()
cur = db.cursor()
cur.execute("""SELECT datas FROM sitedatas WHERE datasite=%s""", (plot_str,))
data_x = cur.fetchall()
for item in data_x:
data_eltime.append(float(item[0]['el_time']))
data_statuscode.append(int(item[0]['status_code']))
data_currenttime.append(item[0]['current_time'])
cur.close()
db.close()
try:
return render_template("home.html", data=getSites(), splitted=splitted(getSites()), imgurl=getImgurl(),
len=len(getSites()), eltime=data_eltime, statuscode=data_statuscode,
currenttime=data_currenttime, plot_title=plot_str)
except:
return redirect("/home")
@app.route("/adding", methods=['GET'])
def routeToAdd():
return render_template('add.html')
@app.route("/add", methods=['POST'])
def addSites():
site = request.form['adding']
imgurl = request.form['addingImage']
try:
requests.get(site)
except:
flash("The given site does not exist or is not accessible.")
return redirect("/home")
db = connectdb()
cur = db.cursor()
if (is_url_image(imgurl)):
pass
else:
imgurl = "https://kariyer.ariteknokent.com.tr/Content/img/default-logo.png"
cur.execute("""INSERT INTO sites(sitename,imgurl)
VALUES(%s,%s);""", (str(site), str(imgurl)))
db.commit()
cur.close()
db.close()
flash("Site added successfully.")
return redirect("/home")
@app.route("/delete", methods=['POST'])
def deleteSites():
selected = request.form['delete']
db = connectdb()
cur = db.cursor()
try:
cur.execute(
"""DELETE FROM sites WHERE sites.sitename=%s""", (selected,))
cur.execute(
"""DELETE FROM sitedatas WHERE sitedatas.datasite=%s""", (selected,))
db.commit()
cur.close()
db.close()
flash("The site has been deleted.")
return redirect("/home")
except:
cur.close()
db.close()
flash("The site couldn't be deleted.")
return redirect("/home")
if(__name__ == '__main__'):
app.run(host=str(get_ip()), port=5000, debug=True)