Flask 开发环境设置

Python web框架 Flask开发环境设置,引入venv虚拟环境,能很好的避免各程序版本冲突。

1
2
3
4
5
6
cd ~
mdkir weatherapp
cd weatherapp
mkdir templates
touch index.py
touch templates/index.html

安装虚拟环境virtualenv,Mac OS X 下:

1
2
3
4
5
6
7
$sudo easy_install virtualenv
$cd weatherapp
$virtualenv venv
New python executable in venv/bin/python2.7
lso creating executable in venv/bin/python
Installing setuptools............done.
Installing pip...............done.

应用根目录会生成一个venv目录
激活venv

1
2
$source venv/bin/activate
(venv)$

在venv下安装相关的软件包

1
2
3
4
(venv)$pip install flask
(venv)$python
>>>import falsk
>>>

没有错误,就说明你的flask装好了

1
2
3
4
5
6
7
8
9
10
$vim index.py
from flask import Flask
import os
app = Flask(__name__)
@app.route("/")
def index():
return "Hello,World!"
if __name__ == '__main__':
port = int(os.environ.get('PORT',5000))
app.run(host='0.0.0.0',port=port,debug=True)

运行flaskweb服务

1
2
3
(venv)$python index.py
* Running on http://0.0.0.0:5000/
* Restarting with reloader

浏览器输入http://localhost:5000 就可以看到你的helloworld页面了。

所有的Flask应用程序都需要创建一个app实例。服务响应客户端请求使用WSGI(Web Server Gateway Interace)。
路由和视图函数:
路由就是用来保持URL地址和函数的关系。可以使用装饰器@app.route 来暴露路由。URL 可以有静态和动态的方式声明。
/user/ ,/user/

模板
from flask import render_template

变量:
变量
undefined 字典
undefined 列表
undefined 带变量的列表
对象的方法
管道: safe ,lower,upper,title,trim,striptags

控制:
判断:

Hello,Stranger!

循环

‘’’bash
macro

‘’’



支持在外部文件定义:
‘’’bash
{ macros.render_ct(comment) }
‘’’
支持将重复的内容抽象,然后include

支持继承:

评论