2018-07-09-flask-01-Flask介绍

Flask介绍

什么是flask

  • 是web应用开发的一个轻量级的框架
  • 依赖的外部扩展的库:Werlzueg/Jinja2
  • Werkzueg是WSGI(Web Server Gateway Interface)的工具集,Jinja2是渲染引擎
WSGI标准
接口就是WSGI:Web Server Gateway Interface

flask工程介绍

  • app.py 程序的入口(创建服务,启动服务,建立路由匹配)
  • static 文件夹(放置一些今天资源,图片、html、CSS)
  • templates文件夹(放置HTML模板)

Flask插件

flask-script

  • 安装插件: pip install flask-script

  • 使用:

    1. 创建一个manager对象,并且把app对象传入

    2. 运行时,使用manager.run()

    3. 使用脚本 python manager.py runserver

      -r(自动启动)

      -d(打开debug开关)

      -h 0.0.0.0(设置服务器地址)

      -p 8000(修改端口号)

blueprint蓝图

  • 不用安装,是flask自带的

  • 使用

    1.创建一个Blueprint对象 blue = Blueprint('blueprint_name',__name__)

    2.使用blueprint建立路由匹配 @blue.route('/')

    3.使用app注册blueprint app.register_blueprint(blueprint=blue)

  • 注意事项:

    1. 蓝图的初始化要放在views里面
    2. 蓝图在初始化是需要指定一个名字
    3. 蓝图使用之前必须要在app里进行注册(注册要在服务启动之前完成)

    路由匹配规则:

    • convert:变量名
      1. string:str --> 允许字符串,不能使用\
      2. path:p --> 本质就是字符串,允许\
      3. int/float:value --> 允许uuid
      4. any(a,b,c):value -->允许规定里的任意一个

    例子:

    —manager.py-----

    from flask_script import Manager
    from my_app import create_app
    
    app = create_app()
    #创建一个Manager对象
    manager = Manager(app)
    
    if name == 'main':
       manager.run()
      
    
      """
      run方法里可以添加参数
      host    用来指定服务器地址,port用来指定端口
      
      问题1:如果想要改端口号或者服务器地址或者开关debug,必须修改源码
      问题2:修改源码以后,没有自动重启
      app.run(host='127.0.0.1',port=7000,debug=True)
      
      使用flask-script插件以后运行项目
      就变成了manager.run()   (manager就是我们Manager实例化的一个对象)
      manager = Manager(app)
      不是原来的app.run  (app就是我们Flask实例化的一个对象)
      app = Flask(__name__)
      """
    

—myapp/init.py

from my_app.views import blue
from flask import Flask


def create_app():
  app = Flask(__name__)
  #app必须要注册一个蓝图才能使用
  app.register_blueprint(blueprint=blue)
  return app

—views.py—

from flask import (Blueprint, request, render_template, redirect,url_for, make_response, abort)

blue = Blueprint('my_blueprint', __name__)

@blue.route('/')
def index():
  #1/0
  print(request.cookies)
  return 'hello flask project'

@blue.route('/hello/')
def hello():
  return 'hello happy body'
"""
  默认的参数类型是字符串
  @blue.route('/simplestr/<name>/')
  需要的是一个字符串类型的参数 string:写和不写一样,可以忽略
  string里不能出现 /
"""

@blue.route('/simplestr/<string:name>/')
def simple_str(name):
  print(type(name))
  return name


# path本质其实就是string,但是允许出现 /
@blue.route('/testpath/<path:p>')
def test_path(p):
  print(type(p))
  return p

#要求只能是int型
@blue.route('/testint/<int:num>/<float:f>/')
def test_int(num,f):
  print(num)
  print(f)
  print(type(num))
  return 'test int'


#要求的参数必须是float类型
@blue.route('/testfloat/<float:f>/')
def test_float(f):
  print(f)
  print(type(f))
  return 'test float'
#只接受UUID
@blue.route('/testuu/<uuid:uu>/')
def test_uuid(uu):
  return 'test_uuid'

# 只能接收指定的值
@blue.route('/testany/<any(a,b,c,):value>/')
def test_any(value):
  return 'test any'

@blue.route('/testrequest/',methods=['GET','POST'])
def test_request():
  #request 是flask里的一个内置对象,它表示每一次的请求
  print('method = '+ request.method)
  #method = GET
  print(request.args)
  ## ImmutableMultiDict 不可变的允许重复key的字典
  #ImmutableMultiDict([('age', '18'), ('username', 'zhangsan'), ('username', 'lisi')])
  print(request.args.get('username'))
  #zhangsan
  print(request.args.getlist('username'))
  #['zhangsan', 'lisi']
  print(request.cookies)
  #{'csrftoken': 'FSNbDt4ZUm5rREocxnQWENBcWGCKOTwjAHu78I84YomhuaTKAgxmIW9pmAzpGgnX',
  #  'sessionid': 'r9rkd2so4v9un420hxjm1mq5ylm4jwdq'}
  print(request.form)
  #ImmutableMultiDict([])
  print(request.files)
  #ImmutableMultiDict([])
  return '获取请求成功'

#可以返回一个字符串,加状态码
@blue.route('/simpleres/')
def simple_resp():
  return '这是一个简单的响应',200

@blue.route('/templateresp/')
def template_resp():
  #加载一个模板并且返回
  result = render_template('hello.html',msg='张三')
  print(result)
  #渲染一个模板并且返回,其实本质就是一个字符串
  print(type(result)) #<class 'str'>
  return result

@blue.route('/redirectresp/')
def redirect_resp():
  #返回一个重定向。一般情况下,重定向的路径都是用url_for反向解析
  return redirect(url_for('my_blueprint.simple_resp'))

@blue.route('/makeresp/')
def make_resp():
  resp = make_response(redirect(url_for('my_blueprint.simple_resp')))
  print('--->',resp)
  #不会执行到这里,在url_for直接就被重定向拦截了
  return resp

@blue.route('/docalculate/<int:num>/')
def claculate(num):
  if num == 0:    #用户传入的是0
      abort(400)  # 400 Bad Request
  result = 1 / num
  return '您传入的字倒数是%.2f' % result

#使用蓝图处理指定的错误
@blue.errorhandler(400)
def handle_400(e):  #errorhandler对应的方法,必须有一个参数
  print(e)
  return '请求错误'

@blue.errorhandler(500)
def handle_500(exception):
  return '请求网络'


@blue.route('/writecookie/')
def write_cookie():
  resp = make_response('写入成功')
  # 使用响应写入cookie. 键值对的形式
  #max_age 指定cookiede 过期时间,单位是秒
  resp.set_cookie('username','lisi',max_age=30)
  return resp

启动服务:python manager.py runserver -r -d -h 0.0.0.0 -p 8000

访问mhh4399.com:8000/hello/显示

hello happy body

注意:

配置路由的时候
开头要加/  斜线
结尾不加斜线  访问的时候url就不要加斜线
结尾加斜线    访问的时候url加不加斜线都能匹配到

Request对象

1.flask有一个内置的对象request,每一次请求都会生成一个独立的request对象

print('host = '+request.host)	#主机地址+端口号
print('host_url = '+request.host_url)	#协议头+主机地址+端口号
print('base_url = '+request.base_url())	#请求的路径,不包含请求参数
print('url = '+request.url)	#请求的完整路径,包含参数
#remote_addr	#表示客户端的地址
print('remote_addr = '+request.remote_addr)

response的使用

​ 1.返回一个字符串

​ 2.渲染一个模板并返回,本质其实就是返回一个字符串

​ 3.返回一个重定向

​ 4.使用make_response方法,返回一个Response对象那个(对上面三种方式的封装)

​ 5.异常情况需要中断执行abort(404)

​ 6.使用蓝图可以处理异常中断

@blue.error_handler(404)	#需要处理的异常代码
def handler_404(exception):	
#需要有一个参数接收异常信息,这里的exception是一个形参
	return '界面丢失了'

猜你喜欢

转载自blog.csdn.net/github_38970218/article/details/88696612