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.

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