python - 我如何在 Python/Flask 中干净地做 slugs?

标签 python web-services mongodb flask slug

我在 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 处理更干净,这样它就不会为每个 Controller 重复?

最佳答案

这样的事情怎么样:

@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(完全取决于您的需要)所以我把它留在那里。

关于python - 我如何在 Python/Flask 中干净地做 slugs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13814237/

相关文章:

Python 元类困惑

python - Python中的Powerset算法: difference between + and append on lists

java - 在 JSF2.0 中动态创建和填充 DataTable

mongodb - 如何在 Mongo 中合并列

python - 像 python 控制台中的 ipython 一样默认制表符补全

python - matplotlib.mlab.griddata 非常慢并且在输入有效数据时返回 nan 数组

java - 无法发送 SOAP 消息

java - 如何根据多个参数过滤Web服务结果?

javascript - Mongodb父引用树获取当前位置和完整路径

ruby-on-rails - Mongoid 命名空间模型和继承