You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

427 lines
14 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. #!/usr/bin/env python3
  2. import os
  3. from flask import Flask, render_template, session, request, abort, redirect, url_for, jsonify
  4. from flask_sqlalchemy import SQLAlchemy
  5. from sqlalchemy import inspect, and_
  6. from flask_wtf import FlaskForm
  7. import bcrypt
  8. from wtforms_alchemy import model_form_factory
  9. from flask_migrate import Migrate
  10. from uuid import uuid4
  11. import csv
  12. import validate
  13. import secrets
  14. from dotenv import load_dotenv
  15. load_dotenv()
  16. # from datetime import date
  17. app = Flask(__name__)
  18. app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
  19. app.secret_key = os.getenv('SECRET_KEY', secrets.token_hex(16))
  20. db: SQLAlchemy = SQLAlchemy()
  21. migrate = Migrate()
  22. db.init_app(app)
  23. migrate.init_app(app, db)
  24. # Helper Methods
  25. def object_as_dict(obj):
  26. return {c.key: getattr(obj, c.key)
  27. for c in inspect(obj).mapper.column_attrs}
  28. # Model Forms
  29. BaseModelForm = model_form_factory(FlaskForm)
  30. class ModelForm(BaseModelForm):
  31. @classmethod
  32. def get_session(cls):
  33. return db.session
  34. class User(db.Model):
  35. id = db.Column(db.Integer, primary_key=True)
  36. username = db.Column(db.String, unique=True, nullable=False)
  37. email = db.Column(db.String, unique=True, nullable=False)
  38. name = db.Column(db.String, unique=True, nullable=False)
  39. password = db.Column(db.String, nullable=False)
  40. institution = db.Column(db.String, unique=True, nullable=False)
  41. position = db.Column(db.String, unique=True, nullable=False)
  42. admin = db.Column(db.Boolean)
  43. # for type annotations
  44. query: db.Query
  45. @classmethod
  46. def generate_password(cls, pw: str):
  47. return bcrypt.hashpw(pw, bcrypt.gensalt(12))
  48. @classmethod
  49. def authenticate(cls, username: str, pw: str):
  50. user = User.query.filter_by(username=username).one_or_none()
  51. if user and bcrypt.checkpw(pw, user.password):
  52. session['user'] = user.username
  53. if user.admin:
  54. session['admin'] = user.username
  55. return user
  56. else:
  57. return None
  58. @classmethod
  59. def admin_exists(cls):
  60. user = User.query.filter_by(admin=True).first()
  61. return True if user else False
  62. @classmethod
  63. def authorize_or_redirect(cls, admin=True):
  64. if (admin and "admin" not in session) or "user" not in session:
  65. return redirect(url_for("login"))
  66. else:
  67. return None
  68. class Chemical(db.Model):
  69. query: db.Query
  70. id = db.Column(db.Integer, primary_key=True)
  71. person_id = db.Column(db.Integer, nullable=False)
  72. standard_grp = db.Column(db.String, nullable=False)
  73. # all fields after here are included in the database
  74. chemical_db_id = db.Column(db.String)
  75. library = db.Column(db.String)
  76. # important fields
  77. metabolite_name = db.Column(db.String, nullable=False)
  78. formula = db.Column(db.String, nullable=False)
  79. mass = db.Column(db.Float, nullable=False)
  80. pubchem_cid = db.Column(db.Integer)
  81. pubmed_refcount = db.Column(db.Integer)
  82. standard_class = db.Column(db.String)
  83. inchikey = db.Column(db.String, nullable=False)
  84. inchikey14 = db.Column(db.String)
  85. final_mz = db.Column(db.Float, nullable=False)
  86. final_rt = db.Column(db.Float, nullable=False)
  87. final_adduct = db.Column(db.String, nullable=False)
  88. adduct = db.Column(db.String)
  89. detected_adducts = db.Column(db.String)
  90. adduct_calc_mz = db.Column(db.String)
  91. msms_detected = db.Column(db.Boolean, nullable=False)
  92. msms_purity = db.Column(db.Float)
  93. # serialized into datetime.date
  94. createdAt = db.Column(db.Date)
  95. class ChemicalForm(ModelForm):
  96. class Meta:
  97. csrf = False
  98. model = Chemical
  99. # Error Handlers
  100. @app.errorhandler(404)
  101. def handler_404(msg):
  102. return render_template("errors/404.html")
  103. @app.errorhandler(403)
  104. def handler_403(msg):
  105. return render_template("errors/403.html")
  106. # Admin routes
  107. @app.route('/dashboard')
  108. def admin_root():
  109. if 'admin' in session:
  110. return render_template("admin.html", user=session.get("admin"))
  111. if 'user' in session:
  112. return render_template("user.html", user=session.get("user"))
  113. return User.authorize_or_redirect(admin=False) or ""
  114. @app.route('/accounts/create', methods=['GET', 'POST'])
  115. def accounts_create():
  116. if User.admin_exists():
  117. if login := User.authorize_or_redirect():
  118. return login
  119. if request.method == "GET":
  120. return render_template("register.html")
  121. else:
  122. username, pw = request.form.get(
  123. 'username'), request.form.get('password')
  124. if username is None or pw is None:
  125. return render_template("register.html", fail="Invalid Input.")
  126. elif db.session.execute(db.select(User).filter_by(username=username)).fetchone():
  127. return render_template("register.html", fail="Username already exists.")
  128. else:
  129. # because the IDE complains about type mismatches
  130. form = {} | request.form
  131. form['password'] = User.generate_password(pw)
  132. form['admin'] = (True if form.get('admin') == 'y' else False)
  133. form.pop('reconfirm')
  134. user = User(**form)
  135. db.session.add(user)
  136. db.session.commit()
  137. return render_template("register.html", success=True)
  138. @app.route('/accounts/edit', methods=['GET', 'POST'])
  139. def accounts_edit():
  140. if login := User.authorize_or_redirect(admin=False):
  141. return login
  142. user = User.query.filter_by(username=session.get('user')).one_or_404()
  143. if request.method == "GET":
  144. return render_template("account_edit.html", user=object_as_dict(user))
  145. else:
  146. dct = object_as_dict(user)
  147. # update all of the changes
  148. for key in request.form:
  149. if key in dct:
  150. setattr(user, key, request.form[key])
  151. db.session.commit()
  152. return render_template("account_edit.html", user=object_as_dict(user), success=True)
  153. @app.route('/accounts/view/<int:id>')
  154. def accounts_view(id):
  155. user = User.query.filter_by(id=id).one_or_404()
  156. return render_template("account_view.html", user=object_as_dict(user))
  157. @app.route('/accounts/login', methods=['GET', 'POST'])
  158. def login():
  159. if request.method == "POST":
  160. username, pw = request.form.get(
  161. 'username', ''), request.form.get('password', '')
  162. if User.authenticate(username, pw):
  163. return render_template("login.html", success=True)
  164. else:
  165. return render_template("login.html", fail="Could not authenticate.")
  166. else:
  167. return render_template("login.html")
  168. @app.route('/accounts/logout', methods=['GET'])
  169. def logout():
  170. if "admin" in session:
  171. session.pop('admin')
  172. if "user" in session:
  173. session.pop('user')
  174. return redirect(url_for('home'))
  175. @app.route("/")
  176. def home():
  177. if User.admin_exists():
  178. return render_template("index.html")
  179. else:
  180. return redirect(url_for("accounts_create"))
  181. # Routes for CRUD operations on chemicals
  182. @app.route("/chemical/create", methods=['GET', 'POST'])
  183. def chemical_create():
  184. if not session.get('admin'):
  185. abort(403)
  186. user = User.query.filter_by(username=session.get('user')).one_or_404()
  187. if request.method == "POST":
  188. form = ChemicalForm(**(request.form | {"person_id": user.id}))
  189. if form.validate():
  190. new_chemical = Chemical(**form.data)
  191. db.session.add(new_chemical)
  192. db.session.commit()
  193. return render_template("create_chemical.html", form=ChemicalForm(), user=object_as_dict(user), success=True)
  194. else:
  195. return render_template("create_chemical.html", form=form, invalid=True), 400
  196. else:
  197. form = ChemicalForm(person_id=user.id)
  198. return render_template("create_chemical.html", form=form, user=object_as_dict(user))
  199. @app.route("/chemical/<int:id>/update", methods=['GET', 'POST'])
  200. def chemical_update(id: int):
  201. if not session.get('admin'):
  202. abort(403)
  203. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  204. dct = object_as_dict(current_chemical)
  205. if request.method == "POST":
  206. form = ChemicalForm(**request.form)
  207. if form.validate():
  208. # take the row with id and update it.
  209. for k in form.data:
  210. setattr(current_chemical, k, form.data[k])
  211. db.session.commit()
  212. return render_template("create_chemical.html", form=form, success=True, id=id)
  213. else:
  214. form = ChemicalForm(**dct)
  215. return render_template("create_chemical.html", form=form, invalid=True, id=id), 400
  216. else:
  217. form = ChemicalForm(**dct)
  218. return render_template("create_chemical.html", form=form, id=id)
  219. @app.route("/chemical/<int:id>/delete")
  220. def chemical_delete(id: int):
  221. if not session.get('admin'):
  222. abort(403)
  223. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  224. db.session.delete(current_chemical)
  225. db.session.commit()
  226. return render_template("delete_chemical.html", id=id)
  227. @app.route("/chemical/<int:id>/view")
  228. def chemical_view(id: int):
  229. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  230. dct = object_as_dict(current_chemical)
  231. return render_template("view_chemical.html", id=id, chemical=dct)
  232. @app.route("/chemical/all")
  233. def chemical_all():
  234. if not session.get('admin'):
  235. abort(403)
  236. result: list[Chemical] = Chemical.query.all()
  237. data = []
  238. for x in result:
  239. data.append({c.name: getattr(x, c.name) for c in x.__table__.columns})
  240. return jsonify(data)
  241. @app.route("/chemical/search", methods=["POST"])
  242. def search_api():
  243. query = request.json
  244. if query is None:
  245. return jsonify([])
  246. for field in query:
  247. query[field] = float(query[field])
  248. mz_min, mz_max = query.get('mz_min'), query.get('mz_max')
  249. rt_min, rt_max = query.get('rt_min'), query.get('rt_max')
  250. year_max, month_max, day_max = int(query.get(
  251. 'year_max')), int(query.get('month_max')), int(query.get('day_max'))
  252. try:
  253. mz_filter = and_(mz_max > Chemical.final_mz,
  254. Chemical.final_mz > mz_min)
  255. rt_filter = and_(rt_max > Chemical.final_rt,
  256. Chemical.final_rt > rt_min)
  257. # date_filter = date(year_max, month_max, day_max) >= Chemical.createdAt
  258. except ValueError as e:
  259. return jsonify({"error": str(e)}), 400
  260. result = Chemical.query.filter(
  261. and_(mz_filter, rt_filter)
  262. ).limit(20).all()
  263. data = []
  264. for x in result:
  265. data.append({"url": url_for("chemical_view", id=x.id),
  266. "name": x.metabolite_name, "mz": x.final_mz, "rt": x.final_rt})
  267. return jsonify(data)
  268. # Utilities for doing add and search operations in batch
  269. # no file over 3MB is allowed.
  270. app.config['MAX_CONTENT_LENGTH'] = 3 * 1000 * 1000
  271. @app.route("/chemical/batchadd", methods=["GET", "POST"])
  272. def batch_add_request():
  273. if not session.get('admin'):
  274. abort(403)
  275. user = User.query.filter_by(username=session.get('user')).one_or_404()
  276. if request.method == "POST":
  277. if "input" not in request.files or request.files["input"].filename == '':
  278. return render_template("batchadd.html", invalid="Blank file included")
  279. # save the file to RAM
  280. file = request.files["input"]
  281. os.makedirs("/tmp/walkerdb", exist_ok=True)
  282. filename = os.path.join("/tmp/walkerdb", str(uuid4()))
  283. file.save(filename)
  284. # perform cleanup regardless of what happens.
  285. def cleanup(): return os.remove(filename)
  286. # read it as a csv
  287. with open(filename, "r") as csvfile:
  288. reader = csv.DictReader(csvfile, delimiter="\t")
  289. results, error = validate.validate_insertion_csv_fields(reader)
  290. if error:
  291. cleanup()
  292. return render_template("batchadd.html", invalid=error)
  293. else:
  294. chemicals = [Chemical(**result, person_id=user.id)
  295. for result in results]
  296. db.session.add_all(chemicals)
  297. db.session.commit()
  298. cleanup()
  299. return render_template("batchadd.html", success=True)
  300. else:
  301. return render_template("batchadd.html")
  302. # regular users can batch search.
  303. @app.route("/chemical/batch", methods=["GET", "POST"])
  304. def batch_query_request():
  305. if not session.get('user'):
  306. abort(403)
  307. if request.method == "POST":
  308. if "input" not in request.files or request.files["input"].filename == '':
  309. return render_template("batchadd.html", invalid="Blank file included")
  310. # save the file to RAM
  311. file = request.files["input"]
  312. os.makedirs("/tmp/walkerdb", exist_ok=True)
  313. filename = os.path.join("/tmp/walkerdb", str(uuid4()))
  314. file.save(filename)
  315. # perform cleanup regardless of what happens.
  316. def cleanup(): return os.remove(filename)
  317. # read it as a csv
  318. with open(filename, "r") as csvfile:
  319. reader = csv.DictReader(csvfile, delimiter="\t")
  320. queries, error = validate.validate_query_csv_fields(reader)
  321. if error:
  322. cleanup()
  323. return render_template("batchquery.html", invalid=error)
  324. else:
  325. # generate the queries here.
  326. data = []
  327. for query in queries:
  328. mz_filter = and_(query["mz_max"] > Chemical.final_mz,
  329. Chemical.final_mz > query["mz_min"])
  330. rt_filter = and_(query["rt_max"] > Chemical.final_rt,
  331. Chemical.final_rt > query["rt_min"])
  332. # date_filter = query["date"] >= Chemical.createdAt
  333. result = Chemical.query.filter(
  334. and_(mz_filter, rt_filter)
  335. ).limit(5).all()
  336. hits = []
  337. for x in result:
  338. hits.append({"url": url_for("chemical_view", id=x.id),
  339. "name": x.metabolite_name, "mz": x.final_mz, "rt": x.final_rt})
  340. data.append(dict(
  341. query=query,
  342. hits=hits,
  343. ))
  344. cleanup()
  345. return render_template("batchquery.html", success=True, data=data)
  346. return render_template("batchquery.html")
  347. @app.route("/search")
  348. def search():
  349. return render_template("search.html")
  350. if __name__ == "__main__":
  351. with app.app_context():
  352. db.create_all()
  353. app.run(debug=True)