9篇 flask related articles

flask: serve static file

Send a file from a given directory with :func:send_file. This
is a secure way to quickly expose static files from an upload folder or something similar.

from flask import Flask, request, send_from_directory

# set the project root directory as the static folder, you can set others.
app = Flask(__name__, static_url_path='')

@app.route('/js/<path:path>')
def send_js(path):
    return send_from_directory('js', path)

if __name__ == "__main__":
    app.run()
More ~

使用flask-babel实现flask应用国际化

安装 Flask-Babel

Flask-Babel 是 Flask 的翻译扩展工具。安装命令如下:

pip install flask-babel

安装它的时候会顺便安装 Babelpytzspeaklater 这三个包,其中 Babel 是 Python 的一个国际化工具包。pytz 是处理时区的工具包,speaklater 相当于是 Babel 的一个辅助工具。

More ~

authlib - python OAuth/OpenID library

The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

这个库可以用做oauth/openid的客户端,或者自建oauth/openid server端。
flask 和 django都有文档示例。

还有个flask 的oauth server 库, https://flask-oauthlib.readthedocs.io/en/latest/oauth2.html , 不过官方建议使用上述的authlib.

More ~

[Flask] multiple routes on same function 多个路由对应同一方法

事情是这样的,一个表单,我想把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请求分不同的方法来写。

More ~

Regex url route in Flask

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)

More ~

Define global function using in jinja templates

原文是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 %}
More ~