我在 Python / Flask 中有一个针对 MongoDB 的简单 Web 服务:https ://github.com/rjurney/Collecting-Data/blob/master/src/python/web/index.py
它一遍又一遍地重复@app.route 代码,就像这样:
@app.route("/email/<message_id>")
def email(message_id):
email = emaildb.find_one({"message_id": message_id})
print email
return render_template('partials/email.html', email=email)
# Enable /emails and /emails/ to serve the last 20 emaildb in our inbox unless otherwise specified
default_offsets={'offset1': 0, 'offset2': 0 + config.EMAIL_RANGE}
@app.route('/', defaults=default_offsets)
@app.route('/emails', defaults=default_offsets)
@app.route('/emails/', defaults=default_offsets)
@app.route("/emails/<int:offset1>/<int:offset2>")
def list_emaildb(offset1, offset2):
offset1 = int(offset1)
offset2 = int(offset2)
emails = emaildb.find()[offset1:offset2] # Uses a MongoDB cursor
nav_offsets = get_offsets(offset1, offset2, config.EMAIL_RANGE)
data = {'emails': emails, 'nav_offsets': nav_offsets, 'nav_path': '/emails/'}
return render_template('partials/emails.html', data=data)
default_search={'offset1': 0, 'offset2': 0 + config.EMAIL_RANGE, 'query': False}
@app.route("/emails/search", defaults=default_search)
@app.route("/emails/search/", defaults=default_search)
@app.route("/emails/search/<string:query>", defaults=default_search)
@app.route("/emails/search/<string:query>/<int:offset1>/<int:offset2>")
def search_email(query, offset1, offset2):
if query == False:
query = request.args.get('query')
return redirect('/emails/search/' + query + '/' + str(offset1) + '/' + str(offset2))
doc_count = offset2 - offset1
results = elastic.search(query, {'from': offset1, 'size': doc_count}, indexes=["email"])
emails = process_results(results)
nav_offsets = get_offsets(offset1, offset2, config.EMAIL_RANGE)
data = {'emails': emails, 'nav_offsets': nav_offsets, 'nav_path': '/emails/search/', 'query': query}
return render_template('partials/emails.html', data=data)
这很丑陋,冒犯了我。这是重复的垃圾。我怎样才能使这个蛞蝓处理更清洁,这样它就不会为每个控制器重复?