Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2。

中文官网:http://dormousehole.readthedocs.io/en/latest/

一、Flask的安装

http://flask.pocoo.org/docs/0.10/installation/#installation
pip install --user virtualenv
mkdir myproject
cd myproject
virtualenv venv
. venv/bin/activate

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:
flask run --host=0.0.0.0
This tells your operating system to listen on all public IPs.

二、简单的技巧
1.模板和静态文件 存放在应用的 Python 源代码树的子目录中,名称分别为 templates 和 static

2.引入外部Html

{% include 'footer.html' %}

因为Flask是基于Jinjia2的模板引擎

{% extends "layout.html" %}
{% block body %}
  < ul >
  {% for user in users %}
    < li >< a href = " {{ user.url }} " >  {{ user.username }} < /a > < /li >
  {% endfor %}
  < /ul>
{% endblock %}

3.调用模板以及参数的引入
render_template
参数的引入:http://www.programcreek.com/python/example/51521/flask.render_template

@app.route('/feedback/view/')
def one_feedback(feedback_id):
    feedback_info = get_one_feedback(feedback_id)
    feedback_info["api_loc"] = api_id
    feedback_info["feedback_id"] = feedback_id

    logger.info("zzz")
    return render_template('one_result.html', feedback=feedback_info)

one_result.html中需加入参数的地方:
{{ feedback["feedback_id"] }}

4.插入参数避免转义
Flask 的模板 Jinja2 会将所有的 html 转义,我想让输出的 等指定的标签不进行转义,让他们正常输出

{{ some html string|safe }}

5.多线程

app.run(host=host, debug=True, port=port ,threaded = True)

三、报错:
1.socket.error: [Errno 48] Address already in use
解决办法:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

The command arguments are included, so you can spot the one running SimpleHTTPServer if more than one python process is active. You may want to test if http://localhost:8000/ still shows a directory listing for local files.
The second number is the process number; stop the server by sending it a signal:

kill 81651

参考资料:
http://stackoverflow.com/questions/19071512/socket-error-errno-48-address-already-in-use

发表评论

电子邮件地址不会被公开。 必填项已用*标注