main.py 6.95 KB
Newer Older
1
2
#!/usr/bin/env python3

3
4
import time
import datetime
5
from flask import Flask, render_template, request, url_for, jsonify, session
6
from lib.paf import Paf
7
from config_reader import AppConfigReader
8
from lib.job_manager import JobManager
Floreal Cabanettes's avatar
Floreal Cabanettes committed
9
from lib.functions import *
10
from lib.upload_file import UploadFile
11
from lib.Fasta import Fasta
12
13

import sys
14

15
16
17
18
19
20
app_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, app_folder)
os.environ["PATH"] = os.path.join(app_folder, "bin") + ":" + os.environ["PATH"]

sqlite_file = os.path.join(app_folder, "database.sqlite")

21
22
23
24

# Init config reader:
config_reader = AppConfigReader()

25
26
UPLOAD_FOLDER = config_reader.get_upload_folder()

Floreal Cabanettes's avatar
Floreal Cabanettes committed
27
app_title = "D-GENIES - Dotplot for Genomes Interactive, E-connected and Speedy"
Floreal Cabanettes's avatar
Floreal Cabanettes committed
28

29
# Init Flask:
30
app = Flask(__name__, static_url_path='/static')
31
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
32
app.config['SECRET_KEY'] = 'dsqdsq-255sdA-fHfg52-25Asd5'
33
34

# Folder containing data:
35
36
37
app_data = config_reader.get_app_data()


Floreal Cabanettes's avatar
Floreal Cabanettes committed
38
39
40
41
42
43
@app.context_processor
def get_launched_results():
    cookie = request.cookies.get("results")
    return {"results": cookie.split("|") if cookie is not None else set()}


44
45
46
# Main
@app.route("/", methods=['GET'])
def main():
Floreal Cabanettes's avatar
Floreal Cabanettes committed
47
48
49
50
51
    return render_template("index.html", title=app_title, menu="index")


@app.route("/run", methods=['GET'])
def run():
52
53
    session["user_tmp_dir"] = random_string(5) + "_" + \
                              datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S')
54
55
56
57
58
59
    id_job = random_string(5) + "_" + datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S')
    if "id_job" in request.args:
        id_job = request.args["id_job"]
    email = ""
    if "email" in request.args:
        email = request.args["email"]
Floreal Cabanettes's avatar
Floreal Cabanettes committed
60
61
    return render_template("run.html", title=app_title, id_job=id_job, email=email,
                           menu="run")
62
63
64
65
66
67
68


# Launch analysis
@app.route("/launch_analysis", methods=['POST'])
def launch_analysis():
    id_job = request.form["id_job"]
    email = request.form["email"]
69
70
71
72
    file_query = request.form["query"]
    file_query_type = request.form["query_type"]
    file_target = request.form["target"]
    file_target_type = request.form["target_type"]
73
74
75

    # Check form:
    form_pass = True
76
    errors = []
77
    if id_job == "":
78
        errors.append("Id of job not given")
79
80
81
        form_pass = False

    if email == "":
82
        errors.append("Email not given")
83
        form_pass = False
84
85
    if file_query == "":
        errors.append("No query fasta selected")
86
87
88
89
        form_pass = False

    # Form pass
    if form_pass:
90
91
92
93
94
95
96
97
98
        # Get final job id:
        id_job_orig = id_job
        while os.path.exists(os.path.join(app_data, id_job)):
            id_job = id_job_orig + "_2"

        folder_files = os.path.join(app_data, id_job)
        os.makedirs(folder_files)

        # Save files:
99
100
101
        query_name = os.path.splitext(file_query.replace(".gz", ""))[0] if file_query_type == "local" else None
        query_path = os.path.join(app.config["UPLOAD_FOLDER"], session["user_tmp_dir"], file_query) \
            if file_query_type == "local" else file_query
102
103
104
        query = Fasta(name=query_name, path=query_path, type_f=file_query_type)
        target = None
        if file_target != "":
105
106
107
            target_name = os.path.splitext(file_target.replace(".gz", ""))[0] if file_target_type == "local" else None
            target_path = os.path.join(app.config["UPLOAD_FOLDER"], session["user_tmp_dir"], file_target) \
                if file_target_type == "local" else file_target
108
109
110
111
112
113
            target = Fasta(name=target_name, path=target_path, type_f=file_target_type)

        # Launch job:
        job = JobManager(id_job, email, query, target)
        job.launch()
        return jsonify({"success": True, "redirect": url_for(".status", id_job=id_job)})
114
    else:
115
        return jsonify({"success": False, "errors": errors})
116
117
118
119
120
121


# Status of a job
@app.route('/status/<id_job>', methods=['GET'])
def status(id_job):
    job = JobManager(id_job)
122
123
    j_status, error = job.status()
    return render_template("status.html", title=app_title, status=j_status, error=error, id_job=id_job,
Floreal Cabanettes's avatar
Floreal Cabanettes committed
124
                           menu="results")
125
126


Floreal Cabanettes's avatar
Floreal Cabanettes committed
127
# Results path
128
@app.route("/result/<id_res>", methods=['GET'])
129
def result(id_res):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
130
131
132
133
134
135
136
137
    my_render = render_template("results.html", title=app_title, id=id_res, menu="results", current_result=id_res)
    response = app.make_response(my_render)
    cookie = request.cookies.get("results")
    cookie = cookie.split("|") if cookie is not None else []
    if id_res not in cookie:
        cookie.insert(0, id_res)
    response.set_cookie(key="results", value="|".join(cookie), path="/")
    return response
138
139


Floreal Cabanettes's avatar
Floreal Cabanettes committed
140
# Get graph (ajax request)
141
142
143
@app.route('/get_graph', methods=['POST'])
def get_graph():
    id_f = request.form["id"]
144
    paf = os.path.join(app_data, id_f, "map.paf")
145
146
    idx1 = os.path.join(app_data, id_f, "query.idx")
    idx2 = os.path.join(app_data, id_f, "target.idx")
147

148
    paf = Paf(paf, idx1, idx2)
149

150
151
    if paf.parsed:
        res = paf.get_d3js_data()
152
        res["success"] = True
153
154
155
156
157
158
        return jsonify(res)
    return jsonify({"success": False, "message": paf.error})


@app.route('/sort/<id_res>', methods=['POST'])
def sort_graph(id_res):
Floreal Cabanettes's avatar
Floreal Cabanettes committed
159
160
161
162
163
164
165
166
167
168
169
    paf = os.path.join(app_data, id_res, "map.paf")
    idx1 = os.path.join(app_data, id_res, "query.idx")
    idx2 = os.path.join(app_data, id_res, "target.idx")
    paf = Paf(paf, idx1, idx2)
    paf.sort()
    if paf.parsed:
        res = paf.get_d3js_data()
        res["success"] = True
        return jsonify(res)
    return jsonify({"success": False, "message": paf.error})

Floréal Cabanettes's avatar
Floréal Cabanettes committed
170

171
172
@app.route("/upload", methods=['POST'])
def upload():
173
174
175
176
177
178
179
180
181
182
183
184
185
    if "user_tmp_dir" in session and session["user_tmp_dir"] != "":
        folder = session["user_tmp_dir"]
        files = request.files[list(request.files.keys())[0]]

        if files:
            filename = files.filename
            folder_files = os.path.join(app.config["UPLOAD_FOLDER"], folder)
            if not os.path.exists(folder_files):
                os.makedirs(folder_files)
            filename = get_valid_uploaded_filename(filename, folder_files)
            mime_type = files.content_type

            if not allowed_file(files.filename):
186
                result = UploadFile(name=filename, type_f=mime_type, size=0, not_allowed_msg="File type not allowed")
187
188
189
190
191
192
193
194
195
196

            else:
                # save file to disk
                uploaded_file_path = os.path.join(folder_files, filename)
                files.save(uploaded_file_path)

                # get file size after saving
                size = os.path.getsize(uploaded_file_path)

                # return json for js call back
197
                result = UploadFile(name=filename, type_f=mime_type, size=size)
198
199
200
201
202

            return jsonify({"files": [result.get_file()], "success": "OK"})

        return jsonify({"files": [], "success": "404", "message": "No file provided"})
    return jsonify({"files": [], "success": "ERR", "message": "Session not initialized. Please refresh the page."})
203
204


Floréal Cabanettes's avatar
Floréal Cabanettes committed
205
206
if __name__ == '__main__':
    app.run()