我在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)
这很难看,冒犯了我。这是重复的垃圾。如何使这个slug处理更清洁,这样每个控制器都不会重复?
答案 0 :(得分:5)
这样的事情怎么样:
@app.route('/')
@app.route('/emails')
@app.route('/emails/')
@app.route("/emails/<int:offset1>/<int:offset2>")
def list_emaildb(offset1=0, offset2=config.EMAIL_RANGE):
...
顺便说一下,不确定是否需要@app.route('/emails')
,因为如果您确实有第二个,则Flask会将/emails
重定向到/emails/
。但也许你还需要/emails
(实际上取决于你的需要),所以我把它留在那里。