标签 flask 下的文章

事情是这样的,一个表单,我想把get和post请求放到一个方法里,但是get和post的路由不一样。

@app.route('/markdown', methods=['GET'])
@app.route('/page_create', methods=['POST'])
def create():
    form = PageForm()
    context = {
        'form': form
    }
...


<!--more-->

按理说可以这样搞,但是我希望是不同的路由进来。

@app.route('/markdown', methods=['GET', 'POST'])
def create():
    form = PageForm()
    context = {
        'form': form
    }
...

那么view里可以这样生成链接,其实就是url_for 多个参数,指定用的method

<form method="post" action="{{ url_for('markdown.create', _method='POST') }}">

但事后觉得这样写太乱了,所以最好还是将get和post请求分不同的方法来写。

- 阅读剩余部分 -

class RegexConverter(BaseConverter):
    def __init__(self, map, *args):
        BaseConverter.__init__(self, map)
        self.map = map
        self.regex = args[0]


app.url_map.converters['regex'] = RegexConverter

Define a regex route

@app.route('/go/<regex("[a-zA-Z0-9]+"):url>')
def go(url):
    real_url = redis.get(url)
    return redirect(real_url)

原文是Call a python function from jinja2, 原文中点赞数量最高的并不是完美的答案,我采用的下面的方案。

Variables can easily be created:

@app.context_processor
def example():
    return dict(myexample='This is an example')

The above can be used in a Jinja2 template with Flask like so:

{{ myexample }}

(Which outputs This is an example)

As well as full fledged functions:

@app.context_processor
def utility_processor():
    def format_price(amount, currency=u'€'):
        return u'{0:.2f}{1}'.format(amount, currency)
    return dict(format_price=format_price)

The above when used like so:

{{ format_price(0.33) }}

(Which outputs the input price with the currency symbol)

Alternatively, you can use jinja filters, baked into Flask. E.g. using decorators:

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

Or, without decorators, and manually registering the function:

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

Filters applied with the above two methods can be used like this:

{% for x in mylist | reverse %}
{% endfor %}