-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathapp.py
More file actions
167 lines (140 loc) · 5.14 KB
/
app.py
File metadata and controls
167 lines (140 loc) · 5.14 KB
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
#import sys
import os
import sys
from flask import Flask, jsonify, request, session, render_template
from flask_cors import CORS
from datetime import timedelta
# from pathlib import Path
#import json
from Classes.Base import Config
# from API.Classes.Base.SyncS3 import SyncS3
from Routes.Upload.UploadRoute import upload_api
from Routes.Case.CaseRoute import case_api
from Routes.Case.SyncS3Route import syncs3_api
from Routes.Case.ViewDataRoute import viewdata_api
from Routes.DataFile.DataFileRoute import datafile_api
#RADI
template_dir = os.path.abspath('WebAPP')
static_dir = os.path.abspath('WebAPP')
# template_dir = Config.WebAPP_PATH.resolve()
# static_dir = Config.WebAPP_PATH.resolve()
# template_dir = os.path.join(sys._MEIPASS, 'WebAPP')
# static_dir = os.path.join(sys._MEIPASS, 'WebAPP')
#gets absolute path
# template_dir = Path('WebAPP').resolve()
# static_dir = Path('../WebAPP').resolve()
# template_dir = 'WebAPP'
# static_dir = '../WebAPP'
print(template_dir)
print(static_dir)
print(sys.executable)
print(__name__)
app = Flask(__name__, static_url_path='', static_folder=static_dir, template_folder=template_dir)
app.permanent_session_lifetime = timedelta(days=5)
app.config['SECRET_KEY'] = '12345'
app.config["MAX_CONTENT_LENGTH"] = None
app.register_blueprint(upload_api)
app.register_blueprint(case_api)
app.register_blueprint(viewdata_api)
app.register_blueprint(datafile_api)
app.register_blueprint(syncs3_api)
CORS(app)
#potrebno kad je front end na drugom serveru 127.0.0.1
@app.after_request
def add_headers(response):
if Config.HEROKU_DEPLOY == 0:
#localhost
response.headers.add('Access-Control-Allow-Origin', 'http://127.0.0.1')
else:
#HEROKU
response.headers.add('Access-Control-Allow-Origin', 'https://osemosys.herokuapp.com/')
response.headers.add('Access-Control-Allow-Credentials', 'true')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization')
#response.headers['Content-Type'] = 'application/javascript'
return response
@app.errorhandler(404)
def not_found_error(error):
# If the request expects JSON or is an API route, return JSON 404
if request.path.startswith('/api/') or request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html:
return jsonify({
"status": "error",
"message": "Resource not found"
}), 404
# Otherwise fallback to the frontend (React/SPA) router
return render_template('index.html'), 404
@app.errorhandler(500)
@app.errorhandler(Exception)
def internal_error(error):
# Depending on the exception, error.code might not exist
status_code = getattr(error, 'code', 500)
if status_code == 404:
return not_found_error(error)
return jsonify({
"status": "error",
"message": "Internal server error",
"details": str(error)
}), status_code
# @app.errorhandler(CustomException)
# def handle_invalid_usage(error):
# response = jsonify(error.to_dict())
# response.status_code = error.status_code
# return response
#entry point to frontend
@app.route("/", methods=['GET'])
def home():
#sync bucket with local storage
# if Config.AWS_SYNC == 1:
# syncS3 = SyncS3()
# cases = syncS3.getCasesSyncInit()
# for case in cases:
# syncS3.downloadSync(case, Config.DATA_STORAGE, Config.S3_BUCKET)
# #downoload param file from S3 bucket
# syncS3.downloadSync('Parameters.json', Config.DATA_STORAGE, Config.S3_BUCKET)
return render_template('index.html')
@app.route("/health", methods=['GET'])
def health_check():
"""Simple backend health check endpoint."""
return jsonify({"status": "ok"}), 200
@app.route("/mock-error", methods=['GET'])
def mock_error():
"""Endpoint to trigger a 500 Internal Server Error for testing."""
raise Exception("This is a mock error for testing 500 handler")
@app.route("/getSession", methods=['GET'])
def getSession():
try:
ses = session.get('osycase', None) or None
response = {
"session":ses
}
return jsonify(response), 200
except( KeyError ):
return jsonify('No selected parameters!'), 404
@app.route("/setSession", methods=['POST'])
def setSession():
try:
cs = request.json['case']
#session.permanent= True
session['osycase'] = cs
response = {"osycase": session['osycase']}
return jsonify(response), 200
except( KeyError ):
return jsonify('No selected parameters!'), 404
if __name__ == '__main__':
# if __name__ == 'app':
#potrebno radi module js importa u index.html ES6 modules
#Flask.__version__
import mimetypes
mimetypes.add_type('application/javascript', '.js')
port = int(os.environ.get("PORT", 5002))
print("PORTTTTTTTTTTT")
if Config.HEROKU_DEPLOY == 0:
#localhost
#app.run(host='127.0.0.1', port=port, debug=True)
#waitress server
#prod server
from waitress import serve
serve(app, host='127.0.0.1', port=port)
else:
#HEROKU
app.run(host='0.0.0.0', port=port, debug=True)
#app.run(host='127.0.0.1', port=port, debug=True)