-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
245 lines (192 loc) · 7.13 KB
/
app.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!flask/bin/python
import glob
import json
from os import environ
from sys import path
from src.settings import ROOT_DIR
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
from src.helper.commands import compare, overwrite
from src.helper.helper import Connection
from src.media_content import load_web_content
from ast import literal_eval
from dotenv import load_dotenv
from logging import basicConfig, INFO
from src.settings import ROOT_DIR, LOG_FILE
from src.crawler.company import Company
from waitress import serve
from logging import exception
basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
filename=LOG_FILE, level=INFO, datefmt='%Y-%m-%d %H:%M:%S')
load_dotenv() # take environment variables from .env.
app = Flask(__name__, static_folder='static', static_url_path='')
app.config['JSON_SORT_KEYS'] = False
cors = CORS(app)
path.append(ROOT_DIR)
DEFAULT_LANGUAGE = "pt_BR"
DEFAULT_ERROR_MESSAGE = "Unexpected error. Try again later."
class SessionData:
def __init__(self):
self.__language = None
@property
def language(self):
return self.__language
@language.setter
def language(self, value):
self.__language = value
session_data = SessionData()
def __search(resume, condition, language={}):
limit = 5000
result = {}
if not resume:
result = {"status": "failed", "message": language.get(
"api_no_curriculum", DEFAULT_ERROR_MESSAGE)}
return jsonify(result), 500
if not condition:
result = {"status": "failed", "message": language.get(
"api_no_condition", DEFAULT_ERROR_MESSAGE)}
return jsonify(result), 500
if len(resume.strip()) == 0:
result = {"status": "failed", "message": language.get(
"api_invalid_curriculum", DEFAULT_ERROR_MESSAGE)}
return jsonify(result), 500
if condition.lower() not in ["and", "or"]:
result = {"status": "failed", "message": language.get(
"api_invalid_condition", DEFAULT_ERROR_MESSAGE)}
return jsonify(result), 500
resume = (resume[:limit]) if len(resume) > limit else resume
try:
comparison = compare(Connection.get_connection_string(), resume, condition)
except Exception as error:
exception(str(error))
result = {"status": "failed", "message": DEFAULT_ERROR_MESSAGE}
return jsonify(result), 500
if not comparison:
result = {"status": "failed", "message": language.get(
"api_no_result", DEFAULT_ERROR_MESSAGE)}
return jsonify(result), 404
result = {"status": "ok", "message": comparison}
return jsonify(result), 200
def __check_informed_language(language):
if (language not in language_keys):
language = DEFAULT_LANGUAGE
return language
def __set_language(request):
language = request.form.get('language')
if language:
session_data.language = language
else:
if not session_data.language:
session_data.language = DEFAULT_LANGUAGE
return __check_informed_language(session_data.language)
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route("/", methods=["GET", "POST"])
def home():
try:
language = __set_language(request)
images_data = load_web_content()
return render_template(
'index.html',
images_data=images_data,
**languages[language],
)
except Exception as error:
exception(error)
return render_template("error.html")
@app.route('/search', methods=['POST'])
def search():
try:
language = __set_language(request)
resume = request.form.get('message')
condition = request.form.get('condition')
comparison = literal_eval(
__search(
resume,
condition,
languages[language]
)[0].response[0].decode('utf-8'))
return render_template(
'search-result.html',
comparison=comparison,
resume=resume,
**languages[language],
)
except Exception as error:
exception(error)
return render_template("error.html")
@app.route("/about", methods=["GET", "POST"])
def about():
try:
language = __set_language(request)
return render_template('about.html', **languages[language])
except Exception as error:
exception(error)
return render_template("error.html")
@app.route("/disclaimer", methods=["GET", "POST"])
def disclaimer():
try:
return render_template('disclaimer.html')
except Exception as error:
exception(error)
return render_template("error.html")
@app.route("/contact", methods=["GET", "POST"])
def contact():
try:
language = __set_language(request)
return render_template('contact.html', **languages[language])
except Exception as error:
exception(error)
return render_template("error.html")
@app.route("/spec")
def spec():
return render_template('spec.html')
@app.route('/api/images')
def api_images():
return jsonify(load_web_content())
@app.route('/api/overwrite', methods=['POST'])
def api_overwrite():
password = request.json.get('password')
if environ.get("PASSWORD") == password:
try:
overwrite(Connection.get_connection_string(), Company().get_all())
result = {"status": "ok", "message": "overwrite finished"}
return jsonify(result), 200
except Exception as error:
exception(error)
result = {"status": "failed", "message": DEFAULT_ERROR_MESSAGE}
return jsonify(result), 500
result = {"status": "failed", "message": "nothing to overwrite"}
return jsonify(result), 404
@app.route('/api/logs', methods=["POST"])
def api_logs():
password = request.json.get('password')
if environ.get("PASSWORD") == password:
try:
with open(LOG_FILE, "r") as log:
result = {"status": "ok", "message": log.read()}
return jsonify(result), 200
except Exception as error:
exception(error)
result = {"status": "failed", "message": DEFAULT_ERROR_MESSAGE}
return jsonify(result), 500
result = {"status": "failed", "message": "nothing to log"}
return jsonify(result), 404
if __name__ == '__main__':
# run!
port = int(environ.get('PORT', 5001))
languages = {}
language_paths = glob.glob("language/*.json")
language_keys = [
language.replace("language/", "").replace(".json", "")
for language in language_paths
]
for language in language_paths:
filename = language.split("/")
lang_code = filename[1].split(".")[0]
with open(language, "r", encoding="utf8") as file:
languages[lang_code] = json.loads(file.read())
print("Server running")
serve(app, host="0.0.0.0", port=port)