flask基础

1. flask介绍

Flask是一个基于Python实现的web开发的’微’框架

中文文档地址

Flask和Django一样,也是一个基于MVC设计模式的Web框架

flask流行的主要原因:

a)有非常齐全的官方文档,上手非常方便

b) 有非常好的拓展机制和第三方的拓展环境,工作中常见的软件都有对应的拓展,自己动手实现拓展也很容易

c) 微型框架的形式给了开发者更大的选择空间

2. 安装flask

2.1虚拟环境搭建
创键虚拟文件下安装:virtualenv --no-site-packages flaskenv

激活windows下虚拟环境
cd Scripts
activate
2.2 安装
pip install flask

3. 基于flask的最小的应用

创建hello.py文件

from flask import Flask
from flask_script import Manager
from app.views import blueprint

# 初始化一个Flask对象
app = Flask(__name__)
# 第二步:注册蓝图,定义URL
app.register_blueprint(blueprint=blueprint,url_prefix = '/user')
# 使用Manage管理Flask的对象
manage = Manager(app=自定义app)

# 启动项目,run()
if __name__ == '__main__':
    # 更改端口port,host:IP地址,debug调试 模式
    # app.run(port=8080,host='0.0.0.0',debug=True)
    # python hello.py runserver -d -p 8080 -h 0.0.0.0
    manage.run()

运行:python hello.py runserver

3.1 初始化
from flask import Flask

app = Flask(__name__)

Flask类构造函数唯一需要的参数就是应用程序的主模块或包。对于大多数应用程序,Python的name变量就是那个正确的、你需要传递的值。Flask使用这个参数来确定应用程序的根目录,这样以后可以相对这个路径来找到资源文件。

3.2 路由
@app.route('/')

客户端例如web浏览器发送 请求 给web服务,进而将它们发送给Flask应用程序实例。应用程序实例需要知道对于各个URL请求需要运行哪些代码,所以它给Python函数建立了一个URLs映射。这些在URL和函数之间建立联系的操作被称之为 路由 。

在Flask应程序中定义路由的最便捷的方式是通过显示定义在应用程序实例之上的app.route装饰器,注册被装饰的函数来作为一个 路由

3.3 视图函数

在上一个示例给应用程序的根URL注册gello_world()函数作为事件的处理程序。如果这个应用程序被部署在服务器上并绑定了 www.example.com 域名,然后在你的浏览器地址栏中输入 http://www.example.com 将触发gello_world()来运行服务。客户端接收到的这个函数的返回值被称为 响应 。如果客户端是web浏览器,响应则是显示给用户的文档。

类似于gello_world()的函数被称作 视图函数

视图文件设置:views.py

from flask import Blueprint, url_for, redirect

# 第一步:初始化蓝图,定义两个参数
blueprint = Blueprint('first',__name__)
# 定义路由
@blueprint.route('/')
# 视图函数
def hello():
    return 'hello world'

# 路由地址
@blueprint.route('redirect/')
def index():
    # 蓝图第一个参数,视图名,跳转到hello函数执行hello
    return redirect(url_for('first.hello'))

# route匹配规则
# 1.<string:xx>获取到xx参数的值为字符串类型
# 2.<xx>默认取到的xx的参数是一个字符串类型
@blueprint.route('name/<string:s_name>/')
def get_name(name):
    return '姓名:%s'%name

# 默认接收参数是一个字符串类型
@blueprint.route('age/<age>/')
def get_age(age):
    return '年龄:%s'% age

# 把年龄字符串的类型强行指定为int类型
@blueprint.route('int_age/<int:age>/')
def get_int_age(age):
    return '年龄:%d' % age
@blueprint.route('float/<float:number>/')
def get_float(number):
    return '获取浮点数为:%.2f'% number


# 了解:
@blueprint.route('path/<path:s_path>')
def get_path(s_path):
    return '获取path路径:%s'% s_path


# 了解
@blueprint.route('get_uuid/')
def get_uuid():
    a = uuid.uuid4()
    return 'uuid:%s'% str(a)

# 了解
@blueprint.route('uuid/<uuid:s_uuid>')
def get_by_uuid(s_uuid):
    return '获取uuid值:%s'% s_uuid

# 请求与响应
# 请求:是客服端传到服务端
# 响应:是服务端返回给客户端的,比如设置cookie值
@blueprint.route('request/', methods=['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
def get_request():
    # 如果是GET请求:获取get请求中的参数,使用request.args.get(key)
    # 如果是POST/PUT.PATCH/DELETE请求:获取post请求中的参数,使用request.form.get(key)
    # 获取key重复的Value值,使用request.form.getlist(key),获取的值是一个列表
    return '我是请求'

@blueprint.route('response/', methods=['GET'])
def get_response():
    # make_response:创建响应,返回给页面
    # res = make_response('<h2>我是响应</h2>',400)
    # 逗号后必须要写状态码,不然会报错
    return 'hello ',300
    # return res

@blueprint.route('error/', methods=['GET'])
def error():
    a=9
    b=1
    try:
        c = a/b
    except:
        abort(500)
    return '%s/%s=%s' % (a, b, c)

# 接收异常
@blueprint.errorhandler(500)
def handler_500(exception):
    return '捕获异常信息:%s'% exception


# 设置cookies
@blueprint.route('cookies/', methods=['GET'])
def get_cookies():
    response = make_response('<h3>hello word</h3>', 200)
    # set_cookie中参数,key,value,max_age/expires
    response.set_cookie('session_id', '1234567890', max_age=1000)
    return response

# 删除cookies
@blueprint.route('del_cookies', methods=['GET'])
def del_cookies():
    response = make_response('<h3>hello word</h3>', 200)
    # delete_cookies删除cookie中的key
    # response.delete_cookie('session_id')
    #第二种方法删除cookies
    response.set_cookie('session_id', '', max_age=0)
    return response

3.4 动态名称组件路由

你的Facebook个人信息页的URL是 http://www.facebook.com/ ,所以你的用户名是它的一部分。Flask在路由装饰器中使用特殊的语法支持这些类型的URLs。下面的示例定义了一个拥有动态名称组件的路由:

@app.route('/hello/<name>')

def gello_world(name):

    return 'Hello World %s' % name

用尖括号括起来的部分是动态的部分,所以任何URLs匹配到静态部分都将映射到这个路由。当视图函数被调用,Flask发送动态组件作为一个参数。在前面的示例的视图函数中,这个参数是用于生成一个个性的问候作为响应。

在路由中动态组件默认为字符串,但是可以定义为其他类型。例如,路由/user/int:id只匹配有一个整数在id动态段的URLs。Flask路由支持int、float

如下:

@app.route('/hello/<int:id>')

def gello_stu_id(id):

  return 'Hello World id: %s' % id
3.5 服务启动
if __name__ == '__main__':

    app.run()

注意: name == ‘main‘在此处使用是用于确保web服务已经启动当脚本被立即执行。当脚本被另一个脚本导入,它被看做父脚本将启动不同的服务,所以app.run()调用会被跳过。

一旦服务启动,它将进入循环等待请求并为之服务。这个循环持续到应用程序停止,例如通过按下Ctrl-C。

有几个选项参数可以给app.run()配置web服务的操作模式。在开发期间,可以很方便的开启debug模式,将激活 debugger 和 reloader 。这样做是通过传递debug为True来实现的。

run()中参数有如下:

debug 是否开启调试模式,开启后修改python的代码会自动重启

port 启动指定服务器的端口号

host主机,默认是127.0.0.1

4. 修改启动方式,使用命令行参数启动服务

4.1 安装插件
pip install flask-script --->更改IP地址
from flask_script import Manager-->导入模块

调整代码

manager = Manager(app=‘自定义的app对象’)

启动的地方 manager.run()

4.2 启动命令
python hellow.py runserver -h 地址 -p 端口 -d -r

其中:-h表示地址。-p表示端口。-d表示debug模式。-r表示自动重启

快速启动按钮设置:

Script path:D:\wordspace\falsk\day01\hello.py –>

Parameters: runserver -d -p 8080 h(可以不写默认Ip地址127.0.0.1)

或者在启动项目中直接设置:

# 启动项目,run()
if __name__ == '__main__':
    # 更改端口port,host:IP地址,debug调试 模式
    # app.run(port=8080,host='0.0.0.0',debug=True)
    # python hello.py runserver -d -p 8080 -h 0.0.0.0--设置启动
    manage.run()

启动命令:

python hellow.py runserver

1. 什么是蓝图

在Flask项目中可以用Blueprint(蓝图)实现模块化的应用,使用蓝图可以让应用层次更清晰,开发者更容易去维护和开发项目。蓝图将作用于相同的URL前缀的请求地址,将具有相同前缀的请求都放在一个模块中,这样查找问题,一看路由就很快的可以找到对应的视图,并解决问题了。

2. 使用蓝图

2.1 安装
pip install flask_blueprint
2.2 实例化蓝图应用
blue = Blueprint(‘first’,__name__)

注意:Blueprint中传入了两个参数,第一个是蓝图的名称,第二个是蓝图所在的包或模块,name代表当前模块名或者包名

注册
app = Flask(\_\_name\_\_)

app.register_blueprint(blue, url_prefix='/user')

注意:第一个参数即我们定义初始化定义的蓝图对象,第二个参数url_prefix表示该蓝图下,所有的url请求必须以/user开始。这样对一个模块的url可以很好的进行统一管理

5. route规则

5.1 规则

写法:converter:variable_name

converter类型:

string 字符串
int 整形
float 浮点型
path 接受路径,接收的时候是str,/也当做字符串的一个字符
uuid 只接受uuid字符串
any 可以同时指定多种路径,进行限定

例子:

@app.route('/helloint/<int:id>/')

@app.route('/getfloat/<float:price>/')

@app.route('/getstr/<string:name>/',methods=['GET', 'POST'])

@app.route('/getpath/<path:url_path>/')

@app.route('/getbyuuid/<uuid:uu>/',methods=['GET', 'POST'])

实现对应的视图函数:

@blue.route('/hello/<name>/')
def hello_man(name):
    print(type(name))
    return 'hello name:%s type:%s' % (name, type(name))

@blue.route('/helloint/<int:id>/')
def hello_int(id):
    print(id)
    print(type(id))
    return 'hello int: %s' % (id)

@blue.route('/index/')
def index():
    return render_template('hello.html')

@blue.route('/getfloat/<float:price>/')
def hello_float(price):

    return 'float: %s' % price

@blue.route('/getstr/<string:name>/')
def hello_name(name):

    return 'hello name: %s' % name

@blue.route('/getpath/<path:url_path>/')
def hello_path(url_path):

    return 'path: %s' % url_path

@blue.route('/getuuid/')
def gello_get_uuid():
    a = uuid.uuid4()
    return str(a)

@blue.route('/getbyuuid/<uuid:uu>/')
def hello_uuid(uu):

    return 'uu:%s' % uu
5.2 methods请求方法

常用的请求类型有如下几种

GET : 获取
POST : 创建
PUT : 修改(全部属性都修改)
DELETE : 删除
PATCH : 修改(修改部分属性)

定义url的请求类型:

@blue.route('/getrequest/', methods=['GET', 'POST'])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值