02-flask 基本使用

  • 安装flask
pip install flask

  • 创建项目

  • 添加路由规则和视图函数


# 字符串

@app.route('/hello/')

def home():

return 'hello world'

# 模板

@app.route('/home/')

def home():

return render_template('home.html')

  • 启动项目

python app.py

五 flask-script 插件

  • 作用

用于命令行接收参数

  • 官方文档
[https://flask-script.readthedocs.io/en/latest/](https://flask-script.readthedocs.io/en/latest/)
  • 步骤

  • 安装插件


pip install Flask-script

  • 实例化

manager = Manager(app)

  • 使用

manager.run()

  • 说明

python manager.py runserver # 基本操作,启动项目

python manager.py runserver -- help    # 查看帮助

python manager.py runserver -h HOST  # 主机名

python manager.py runserver -p  PORT  # 端口号

python manager.py runserver -d  # 开启debug

python manager.py runserver -r # 重新加载

六 flask-blueprint 插件

  • 蓝图作用

主要用来规划urls

  • 官网

[http://flask.pocoo.org/docs/1.0/blueprints/](http://flask.pocoo.org/docs/1.0/blueprints/)

  • 步骤

  • 安装


pip install flask-blueprint

  • 初始化配置

  • 实例化对象(在views中)


blue  = Blueprint('simple_page', __name__)

  • 注册(在init)中

app.register_blueprint(blueprint = blue)

七 、视图之request

  • 请求参数

路劲参数、get请求参数、post请求参数

  • 路径参数

路径:<类型:变量名>

例如:

类型:int/string/float/uuid/any/path

路由参数名和视图函数参数名,应该一一对应

  • 请求方式

GET/POST/DELETE.....

默认支持GET、HEAD、OPTIONS

请求测试工具:谷歌:Linux-postman、Windows-postman、Mac-postman

火狐: 火狐流浪器-RESTClient插件

pycha-tools

  • 反向解析

格式: url_for('蓝图名.函数名')

例如: path = url_for('blueapp.hello')

重定向: redirect('/index/')

  • request 对象

服务器接收到客户端请求后,会自动创建Request对象,不能被修改!【全局变量】


@blue.route('/requestsettest/',methods=['GET','POST'])

def requestsettest():

# 请求方式

if reques.method == 'GET':

return 'get请求'

elif request.method == 'POST':

return 'post请求'

request.method    请求方式

request.path        请求路径

request.url            请求url

request.args        get 请求参数

request.form        post请求参数

request.files          文件参数

request.headers  请求头

request.cookies    cookie内容

ImmutableMultiDict 类字典

request.args.get('age') 不存在返回None【推荐使用】

八、 视图之response

  • response创建

手动创建,服务器返回客户端的!

- 直接返回字符串

- 返回模板render_template    [也是字符串]

- make_response()    [response对象]

- Response()      [response对象]

response = Response('响应', 208)

return response

  • 返回配置

2xx: 成功

3xx: 重定向

4xx: 客户端错误

5xx:  服务器错误

return 'hello',555

response = make_response('响应', 208)

response = Response('响应', 208)

九、会话技术之cookie

  • 概述

- 会话技术(状态保持, HTTP短链接, HTTP无状态)

- cookie 客户端会话技术

- cookie 数据是全部保存在客户端

- cookie 存储方式key-value

- cookies 支持过期

- cookie 默认会自动携带本站点的所有cookie

  • 方法

- 设置cookie

response.set_cookie(key,value)

- 获取cookie

request.cookies.get(key)

- 删除cookie

response.delete_cookie(key)

你可能感兴趣的:(02-flask 基本使用)