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.

424 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("accounts_create"))
  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_name = db.Column(db.String, 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('/admin')
  108. def admin_root():
  109. if login := User.authorize_or_redirect():
  110. return login
  111. return render_template("admin.html", user=session.get("admin"))
  112. @app.route('/accounts/create', methods=['GET', 'POST'])
  113. def accounts_create():
  114. if User.admin_exists():
  115. if login := User.authorize_or_redirect():
  116. return login
  117. if request.method == "GET":
  118. return render_template("register.html")
  119. else:
  120. username, pw = request.form.get(
  121. 'username'), request.form.get('password')
  122. if username is None or pw is None:
  123. return render_template("register.html", fail="Invalid Input.")
  124. elif db.session.execute(db.select(User).filter_by(username=username)).fetchone():
  125. return render_template("register.html", fail="Username already exists.")
  126. else:
  127. # because the IDE complains about type mismatches
  128. form = {} | request.form
  129. form['password'] = User.generate_password(pw)
  130. form['admin'] = (True if form['admin'] == 'y' else False)
  131. form.pop('reconfirm')
  132. user = User(**form)
  133. db.session.add(user)
  134. db.session.commit()
  135. return render_template("register.html", success=True)
  136. @app.route('/accounts/edit', methods=['GET', 'POST'])
  137. def accounts_edit():
  138. if login := User.authorize_or_redirect(admin=False):
  139. return login
  140. user = User.query.filter_by(username=session.get('user')).one_or_404()
  141. if request.method == "GET":
  142. return render_template("account_edit.html", user=object_as_dict(user))
  143. else:
  144. dct = object_as_dict(user)
  145. # update all of the changes
  146. for key in request.form:
  147. if key in dct:
  148. setattr(user, key, request.form[key])
  149. db.session.commit()
  150. return render_template("account_edit.html", user=object_as_dict(user), success=True)
  151. @app.route('/accounts/view/<int:id>')
  152. def accounts_edit_admin(id):
  153. if login := User.authorize_or_redirect(admin=True):
  154. return login
  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. if request.method == "POST":
  187. form = ChemicalForm(**request.form)
  188. if form.validate():
  189. new_chemical = Chemical(**form.data)
  190. db.session.add(new_chemical)
  191. db.session.commit()
  192. return render_template("create_chemical.html", form=ChemicalForm(), success=True)
  193. else:
  194. return render_template("create_chemical.html", form=form, invalid=True), 400
  195. else:
  196. form = ChemicalForm()
  197. return render_template("create_chemical.html", form=form)
  198. @app.route("/chemical/<int:id>/update", methods=['GET', 'POST'])
  199. def chemical_update(id: int):
  200. if not session.get('admin'):
  201. abort(403)
  202. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  203. dct = object_as_dict(current_chemical)
  204. if request.method == "POST":
  205. form = ChemicalForm(**request.form)
  206. if form.validate():
  207. # take the row with id and update it.
  208. for k in form.data:
  209. setattr(current_chemical, k, form.data[k])
  210. db.session.commit()
  211. return render_template("create_chemical.html", form=form, success=True, id=id)
  212. else:
  213. form = ChemicalForm(**dct)
  214. return render_template("create_chemical.html", form=form, invalid=True, id=id), 400
  215. else:
  216. form = ChemicalForm(**dct)
  217. return render_template("create_chemical.html", form=form, id=id)
  218. @app.route("/chemical/<int:id>/delete")
  219. def chemical_delete(id: int):
  220. if not session.get('admin'):
  221. abort(403)
  222. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  223. db.session.delete(current_chemical)
  224. db.session.commit()
  225. return render_template("delete_chemical.html", id=id)
  226. @app.route("/chemical/<int:id>/view")
  227. def chemical_view(id: int):
  228. current_chemical: Chemical = Chemical.query.filter_by(id=id).one_or_404()
  229. dct = object_as_dict(current_chemical)
  230. return render_template("view_chemical.html", id=id, chemical=dct)
  231. @app.route("/chemical/all")
  232. def chemical_all():
  233. if not session.get('admin'):
  234. abort(403)
  235. result: list[Chemical] = Chemical.query.all()
  236. data = []
  237. for x in result:
  238. data.append({c.name: getattr(x, c.name) for c in x.__table__.columns})
  239. return jsonify(data)
  240. @app.route("/chemical/search", methods=["POST"])
  241. def search_api():
  242. query = request.json
  243. if query is None:
  244. return jsonify([])
  245. for field in query:
  246. query[field] = float(query[field])
  247. mz_min, mz_max = query.get('mz_min'), query.get('mz_max')
  248. rt_min, rt_max = query.get('rt_min'), query.get('rt_max')
  249. year_max, month_max, day_max = int(query.get(
  250. 'year_max')), int(query.get('month_max')), int(query.get('day_max'))
  251. try:
  252. mz_filter = and_(mz_max > Chemical.final_mz,
  253. Chemical.final_mz > mz_min)
  254. rt_filter = and_(rt_max > Chemical.final_rt,
  255. Chemical.final_rt > rt_min)
  256. # date_filter = date(year_max, month_max, day_max) >= Chemical.createdAt
  257. except ValueError as e:
  258. return jsonify({"error": str(e)}), 400
  259. result = Chemical.query.filter(
  260. and_(mz_filter, rt_filter)
  261. ).limit(20).all()
  262. data = []
  263. for x in result:
  264. data.append({"url": url_for("chemical_view", id=x.id),
  265. "name": x.metabolite_name, "mz": x.final_mz, "rt": x.final_rt})
  266. return jsonify(data)
  267. # Utilities for doing add and search operations in batch
  268. # no file over 3MB is allowed.
  269. app.config['MAX_CONTENT_LENGTH'] = 3 * 1000 * 1000
  270. @app.route("/chemical/batchadd", methods=["GET", "POST"])
  271. def batch_add_request():
  272. if not session.get('admin'):
  273. abort(403)
  274. if request.method == "POST":
  275. if "input" not in request.files or request.files["input"].filename == '':
  276. return render_template("batchadd.html", invalid="Blank file included")
  277. # save the file to RAM
  278. file = request.files["input"]
  279. os.makedirs("/tmp/walkerdb", exist_ok=True)
  280. filename = os.path.join("/tmp/walkerdb", str(uuid4()))
  281. file.save(filename)
  282. # perform cleanup regardless of what happens.
  283. def cleanup(): return os.remove(filename)
  284. # read it as a csv
  285. with open(filename, "r") as csvfile:
  286. reader = csv.DictReader(csvfile, delimiter="\t")
  287. results, error = validate.validate_insertion_csv_fields(reader)
  288. if error:
  289. cleanup()
  290. return render_template("batchadd.html", invalid=error)
  291. else:
  292. chemicals = [Chemical(**result) for result in results]
  293. db.session.add_all(chemicals)
  294. db.session.commit()
  295. cleanup()
  296. return render_template("batchadd.html", success=True)
  297. else:
  298. return render_template("batchadd.html")
  299. # regular users can batch search.
  300. @app.route("/chemical/batch", methods=["GET", "POST"])
  301. def batch_query_request():
  302. if not session.get('user'):
  303. abort(403)
  304. if request.method == "POST":
  305. if "input" not in request.files or request.files["input"].filename == '':
  306. return render_template("batchadd.html", invalid="Blank file included")
  307. # save the file to RAM
  308. file = request.files["input"]
  309. os.makedirs("/tmp/walkerdb", exist_ok=True)
  310. filename = os.path.join("/tmp/walkerdb", str(uuid4()))
  311. file.save(filename)
  312. # perform cleanup regardless of what happens.
  313. def cleanup(): return os.remove(filename)
  314. # read it as a csv
  315. with open(filename, "r") as csvfile:
  316. reader = csv.DictReader(csvfile, delimiter="\t")
  317. queries, error = validate.validate_query_csv_fields(reader)
  318. if error:
  319. cleanup()
  320. return render_template("batchquery.html", invalid=error)
  321. else:
  322. # generate the queries here.
  323. data = []
  324. for query in queries:
  325. mz_filter = and_(query["mz_max"] > Chemical.final_mz,
  326. Chemical.final_mz > query["mz_min"])
  327. rt_filter = and_(query["rt_max"] > Chemical.final_rt,
  328. Chemical.final_rt > query["rt_min"])
  329. # date_filter = query["date"] >= Chemical.createdAt
  330. result = Chemical.query.filter(
  331. and_(mz_filter, rt_filter)
  332. ).limit(5).all()
  333. hits = []
  334. for x in result:
  335. hits.append({"url": url_for("chemical_view", id=x.id),
  336. "name": x.metabolite_name, "mz": x.final_mz, "rt": x.final_rt})
  337. data.append(dict(
  338. query=query,
  339. hits=hits,
  340. ))
  341. cleanup()
  342. return render_template("batchquery.html", success=True, data=data)
  343. return render_template("batchquery.html")
  344. @app.route("/search")
  345. def search():
  346. return render_template("search.html")
  347. if __name__ == "__main__":
  348. with app.app_context():
  349. db.create_all()
  350. app.run(debug=True)