[英]How do I cleanly do slugs in Python / Flask?
I have a simple web service in Python / Flask against MongoDB: https://github.com/rjurney/Collecting-Data/blob/master/src/python/web/index.py 我在针对MongoDB的Python / Flask中有一个简单的Web服务: https : //github.com/rjurney/Collecting-Data/blob/master/src/python/web/index.py
It repeats @app.route code, like this, over and over: 它一遍又一遍地重复@ 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)
This is ugly and offends me. 这太丑了,冒犯了我。 It is repeat junk.
这是重复的垃圾。 How can I make this slug handling cleaner, such that it doesn't repeat for each controller?
我该如何使这种弹头处理更清洁,以免每个控制器都不重复?
How about something like this: 这样的事情怎么样:
@app.route('/')
@app.route('/emails')
@app.route('/emails/')
@app.route("/emails/<int:offset1>/<int:offset2>")
def list_emaildb(offset1=0, offset2=config.EMAIL_RANGE):
...
Btw, not sure if @app.route('/emails')
needed, because Flask should redirect /emails
to /emails/
if you do have a second one. 顺便说一句,不确定
@app.route('/emails')
需要,因为如果您还有第二个,Flask应该将/emails
重定向到/emails/
。 But maybe you need also /emails
(depends really on your needs) so I left it there. 但是也许您还需要
/emails
(实际上取决于您的需求),所以我把它留在了那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.