質問

I am using Flask, Werkzeug to serve an application (a blog). In this blog, an editor can change the slug of the URL. Well, it is ok, but I need a way to redirect that old URL to the new URL. Example: /music/rock-in-rio-2012 Oh no, it was 2013. Let's change: /music/rock-in-rio-2013

Nice, now the request above is performing a query with rock-in-rio-2013 slug.

But that is important to me that URLs do not break. I think this could be done by catching the requested URL before raise any exception (404 for example if the model is issuing an "get the record or 404").

My model Redirect would store these fields:

old_url = string
new_url = string
created_at = datetime

How can I catch that URL? I would like a generic way (werkzeug rules). It means that adding a call function in evey view costs too much and seems redundant.

役に立ちましたか?

解決

In your Post model (where you have the slug) you can redefine the .first_or_404 or .get_or_404 methods to deal with this and rising accordingly. But I suggest to define a new method to use in these circumstances.

This is a clean solution. The logic is in the right place (the place that knows what the information is).

The problem is how to manage the redirects.

You can pass a redirect instance to the abort call.

Like in the following pseudo-python-code:

class Post(db.Model):
  def get_or_redirect_or_404(self, slug):
    r = self.query.filter_by(new_url, old_url)
    if not r:
      # there's no model. abort normally
      abort(404)
    elseif r.old_url == slug:
      # old url used, we need redirect
      # 
      abort(redirect(... r.new_url ...))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top