Browse Source

debounced app

master
junikimm717 2 years ago
parent
commit
ea10ee6f00
  1. 19
      app.py
  2. 88
      templates/search.html

19
app.py

@ -50,10 +50,12 @@ class Admin(db.Model):
if not session.get('admin'): if not session.get('admin'):
return redirect(url_for("admin_login")) return redirect(url_for("admin_login"))
def object_as_dict(obj): def object_as_dict(obj):
return {c.key: getattr(obj, c.key) return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs} for c in inspect(obj).mapper.column_attrs}
class Chemical(db.Model): class Chemical(db.Model):
query: db.Query query: db.Query
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
@ -86,7 +88,6 @@ class ChemicalForm(ModelForm):
class Meta: class Meta:
csrf = False csrf = False
model = Chemical model = Chemical
#exclude = ['id']
# Error Handlers # Error Handlers
@ -155,6 +156,7 @@ def home():
# Routes for CRUD operations on chemicals # Routes for CRUD operations on chemicals
@app.route("/chemical/create", methods=['GET', 'POST']) @app.route("/chemical/create", methods=['GET', 'POST'])
def chemical_create(): def chemical_create():
if not session.get('admin'): if not session.get('admin'):
@ -165,16 +167,16 @@ def chemical_create():
new_chemical = Chemical(**form.data) new_chemical = Chemical(**form.data)
db.session.add(new_chemical) db.session.add(new_chemical)
db.session.commit() db.session.commit()
return render_template("create_chemical.html", form=form, success=True)
return render_template("create_chemical.html", form=ChemicalForm(), success=True)
else: else:
return render_template("create_chemical.html", form=ChemicalForm(), invalid=True)
return render_template("create_chemical.html", form=form, invalid=True)
else: else:
form = ChemicalForm() form = ChemicalForm()
return render_template("create_chemical.html", form=form) return render_template("create_chemical.html", form=form)
@app.route("/chemical/<int:id>/update", methods=['GET', 'POST']) @app.route("/chemical/<int:id>/update", methods=['GET', 'POST'])
def chemical_update(id:int):
def chemical_update(id: int):
if not session.get('admin'): if not session.get('admin'):
abort(403) abort(403)
current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404() current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404()
@ -194,8 +196,9 @@ def chemical_update(id:int):
form = ChemicalForm(**dct) form = ChemicalForm(**dct)
return render_template("create_chemical.html", form=form, id=id) return render_template("create_chemical.html", form=form, id=id)
@app.route("/chemical/<int:id>/delete") @app.route("/chemical/<int:id>/delete")
def chemical_delete(id:int):
def chemical_delete(id: int):
if not session.get('admin'): if not session.get('admin'):
abort(403) abort(403)
current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404() current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404()
@ -205,7 +208,7 @@ def chemical_delete(id:int):
@app.route("/chemical/<int:id>/view") @app.route("/chemical/<int:id>/view")
def chemical_view(id:int):
def chemical_view(id: int):
current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404() current_chemical:Chemical = Chemical.query.filter_by(id=id).one_or_404()
dct = object_as_dict(current_chemical) dct = object_as_dict(current_chemical)
return render_template("view_chemical.html", id=id, chemical=dct) return render_template("view_chemical.html", id=id, chemical=dct)
@ -221,6 +224,7 @@ def chemical_all():
data.append({"url": url_for("chemical_view", id=x.id), "name": x.name, "mz": x.final_mz, "rt": x.final_rt}) data.append({"url": url_for("chemical_view", id=x.id), "name": x.name, "mz": x.final_mz, "rt": x.final_rt})
return jsonify(data) return jsonify(data)
@app.route("/chemical/search") @app.route("/chemical/search")
def search_api(): def search_api():
mz_min, mz_max = request.args.get('mz_min'), request.args.get('mz_max') mz_min, mz_max = request.args.get('mz_min'), request.args.get('mz_max')
@ -235,7 +239,7 @@ def search_api():
if rt_min is not None and rt_max is None: if rt_min is not None and rt_max is None:
rt_max = float(rt_min) + 3 rt_max = float(rt_min) + 3
elif rt_max is not None and rt_min is None: elif rt_max is not None and rt_min is None:
rt_min = rt_max - 3
rt_min = float(rt_max) - 3
mz_min, mz_max = float(mz_min), float(mz_max) mz_min, mz_max = float(mz_min), float(mz_max)
rt_min, rt_max = float(rt_min), float(rt_max) rt_min, rt_max = float(rt_min), float(rt_max)
except ValueError: except ValueError:
@ -259,6 +263,7 @@ def search_api():
def search(): def search():
return render_template("search.html") return render_template("search.html")
if __name__ == "__main__": if __name__ == "__main__":
db.init_app(app) db.init_app(app)
with app.app_context(): with app.app_context():

88
templates/search.html

@ -1,50 +1,85 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block content %} {% block content %}
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.min.js"></script>
<script type="module"> <script type="module">
import { createApp } from 'https://unpkg.com/petite-vue?module'
//import { createApp } from 'https://unpkg.com/petite-vue?module'
//import { createApp } from 'https://unpkg.com/vue@2.7.14/dist/vue.esm-browser.prod.js'
createApp({
mz_min:0,
mz_max:0,
rt_min:0,
rt_max:0,
results: [],
error: null,
// methods
async fetch_data() {
try {
console.log("called...")
const json = (await fetch(`/chemical/search?mz_min=${mz_min.value}&mz_max=${mz_max.value}&rt_min=${rt_min.value}&rt_max=${rt_max.value}`))
this.results = await json.json();
} catch(e) {
console.error(e);
error = true;
function valid(str) {
return !isNaN(str) && !isNaN(parseFloat(str))
}
function debounce(func, timeout = 300){
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => { func.apply(this, args); }, timeout);
};
}
const app = new Vue({
el: "#search",
data() {
return {
mz_min: 0,
mz_max: 0,
rt_min: 0,
rt_max: 0,
results: [],
error: null,
} }
},
methods: {
// methods
async fetch_data() {
if (!(valid(this.mz_min) && valid(this.mz_max) && valid(this.rt_max) && valid(this.rt_min))) {
return
}
const url = `/chemical/search?mz_min=${this.mz_min}&mz_max=${this.mz_max}&rt_min=${this.rt_min}&rt_max=${this.rt_max}`
fetch(url).then(res => {
if (res.status !== 200) {
console.log(`Error Status, ${res.status}`)
}
return res.json()
}).then(json => {
this.results = json;
this.error = null;
}).catch(e => {
console.error(e);
this.error = true;
})
},
//debounced_fetch: debounce(this.fetch_data.bind(this), 300)
},
created() {
this.fetch_data = debounce(this.fetch_data, 300)
} }
}).mount()
});
</script> </script>
<h1>Search Box</h1> <h1>Search Box</h1>
<div id="search">
<main> <main>
<label for="mz_min">Mz Min</label> <label for="mz_min">Mz Min</label>
<input id="mz_min" type="number" name="mz_min" v-model="mz_min">
<input id="mz_min" type="number" name="mz_min" v-model="mz_min" @input="fetch_data()" value="0">
<label for="mz_min">Mz Max</label> <label for="mz_min">Mz Max</label>
<input id="mz_max" type="number" name="mz_max" v-model="mz_max">
<input id="mz_max" type="number" name="mz_max" v-model="mz_max" @input="fetch_data()" value="0">
<label for="mz_min">RT Min</label> <label for="mz_min">RT Min</label>
<input id="rt_min" type="number" name="rt_min" v-model="rt_min">
<input id="rt_min" type="number" name="rt_min" v-model="rt_min" @input="fetch_data()" value="0">
<label for="mz_min">RT Max</label> <label for="mz_min">RT Max</label>
<input id="rt_max" type="number" name="rt_max" v-model="rt_max">
<input id="rt_max" type="number" name="rt_max" v-model="rt_max" @input="fetch_data()" value="0">
<!--
<br> <br>
<button @click="fetch_data()">Search</button> <button @click="fetch_data()">Search</button>
-->
</main> </main>
<hr> <hr>
{% raw %} {% raw %}
<div id="search"> <div id="search">
<div v-if="error" style="background-color: red;">
<div v-if="error" style="color: red;">
Uh Oh! There is an Error! Uh Oh! There is an Error!
</div> </div>
<div v-for="result in results"> <div v-for="result in results">
@ -65,5 +100,6 @@
</div> </div>
</div> </div>
{% endraw %} {% endraw %}
</div>
{% endblock %} {% endblock %}
Loading…
Cancel
Save