1. flask
1.1 安装: pip install Flask
1.2 Ubuntu16.04 运行
1.2.1安装Python3.6.5
安装Python3.6.5的步骤:
sudo apt-get install openssl
sudo apt-get install libssl-dev
sudo apt-get install libc6-dev gcc
sudo apt-get install -y make build-essential zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm tk-dev
sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
sudo rm python3
sudo ln -s python3.6 python3
1.2.2 安装Python虚拟环境
virtualenv --version
sudo apt-get install python-virtualenv
pip3 install virtualenvwrapper
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=$HOME/.virtualenvs
source ~/.local/bin/virtualenvwrapper.sh
source ~/.bashrc
mkvirtualenv -p /usr/bin/python3 虚拟环境目录名
workon env_name
workon + 两次tab键可以显示所有的虚拟环境
deactivate
rmvirtualenv env_name
sudo apt-get install python3.6-gdbm
2. Hello Flask
from flask impport Flask
app = Flask(__name__)
@app.route("/hello/"):
def hello():
return "Hello,Flask";
if __name__ == "__main__":
app.run(host="localhost",port=8080,debug=True)
3.URL捕获参数
'''
通过尖括号<> 捕获URL中的参数,并可以在捕获后转换参数的数据类型,最后传递到修饰的视图函数
'''
from flask import Flask
app = Flask(__name__)
@app.route("/greet/<name>/<int:age>")
def greet_view(age,name):
age += 1
result = "<h3>我叫" + name + ", 明年" + str(age) + "岁了</h3>"
return result
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8888,debug=True)
4. flask-script 插件
app = Flask(__name__)
manager = Manager(app)
manager.run()
'''
python 启动脚本名称 runserver 选项参数
启动参数
-h 允许访问的主机
-p 开放的端口号
-d 开启调试
-r 自动监测程序改动,自动重启服务器
-R 不监测程序改动
'''
app = Flask(__name__)
manager = Manager(app)
@manager.command
def hello():
return "Manager的hello方法"
5. 创建响应对象(make_response)
@app.route("/cookies/")
def add_cookie():
response = make_response("Cookie信息设置成功")
response.set_cookie("fruit","orange",30)
return response
6. 重定向
6.1 redirect
redirect("重定向的路径") # 也可以重定向到外网
6.2 反向解析 url_for(endpoint,**kwargs)
不直接硬编码路由,而是动态获取路由
url_for(endpoint,**kwargs)
endpoint: 视图函数,通过此视图函数名获取对应的路由
**kwargs: 对应的路由需要传递参数,通过关键字传递
|