Day16-flask1

1安装虚拟环境

跳转到安装路径:


安装虚拟环境:


跳转到虚拟环境:


安装flask:


2.调试模式

1)app.run方法

app.run()
修改启动的ip和端口
app.run(host='0.0.0.0',port=8080)
修改启动的ip和端口,debug模式
app.run(host='0.0.0.0',port=8080,debug=True)

2)manager.run方法

导入包 pip install flask_script
ip和端口没有在原代码中写死
添加:from flask_script import Manager
添加:manager=Manager(app=app)
manager.run()
修改启动的ip和端口,debug模式
在terminal中输入:python xxx.py runserver -h 0.0.0.0 -p 8080 -d 启动xxx.py

3.匹配路由规则

1)<id>:默认结束的类型为str

2)<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str

3)<int:id>,指定id的类型为int

4)<float:id>,指定id的类型为浮点数

5)<path:paht>,指定接收的paht为URL中的路径

@app.route('/get_id/<id>/')
def get_id(id):
    # 匹配str类型的id值
    return  'id: %s' % id


@ app.route('/get_int_id/<int:id>/')
def get_int_id(id):
    # 匹配int类型的id值
    return  'id: %d' % id\


@ app.route('/get_float/<float:uid>/')
def get_float(uid):
    # 匹配float类型的id值
    return  'id: %.2f' % uid


@app.route('/get_path/<path:upath>')
def get_path(upath):
    #匹配URL路径
    return 'path:%s' % upath

4.运行中的调试器

Debugger PIN: 165-343-513


点击右边的小黑屏幕


输入:在PIN中输入Debugger PIN的值

5.蓝图

  1. 什么是蓝图

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

  1. 使用蓝图

2.1 安装

pip install flask_blueprint

2.2 实例化蓝图应用

blue = Blueprint(‘first’,\_\_name\_\_)

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

2.3 注册

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

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

#设置secret_key
app.config['SECRET_KEY']='123'

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

3 使用蓝图

修改视图上的装饰器,修改为@blue.router(‘/’)

@blue.route('/', methods=['GET', 'POST'])
def hello():
    # 视图函数
    return 'Hello World'

注意:该方法对应的url为127.0.0.1:5000/user/
4 url_for反向解析

语法:

url_for('蓝图中定义的第一个参数.函数名', 参数名=value)

定义跳转:

from flask import url_for, redirect

@blue.route('/redirect/')
def make_redirect():
    # 第一种方法
    return redirect('/hello/index/')
    # 第二种方法
    return redirect(url_for('first.index'))

6.跳转

@blue.route('/redirect/')
def redirect_hello():
    # 实现跳转
    # 1.硬编码URL(将路径写死)
    # return redirect('/app/')
    # 2.反向解析redirect(url_for('蓝图别名.跳转的函数名称'))
    # return redirect(url_for('app.hello_world'))
    return redirect(url_for('app.get_id',id=3))

7.请求

@blue.route('/request/',methods=['GET','POST','PUT'])
def get_request():
    # 请求上下文
    # 获取GET请求的传递的参数,request.args.get(key)/request.args.getlist(key)
    # 获取POST、PUT、PATCH、DELETE请求的传递的参数,request.form.get(key)/request.form.getlist(key)
    # 判断HTTP请求方式:request.method
    pass

8.响应

@blue.route('/response/',methods=['GET'])
def get_response():
    # 200是状态码
    # res=make_response('人身苦短,我也python',200)
    # 响应绑定cookie,set_cookie(key,value,max_age.expires)
    # 删除cookie,delete_cookie(key)
    # set_cookie('key', value, max_ages='', expires='')
    res_index=render_template('index.html')
    res=make_response(res_index,200)
    return res

9.异常处理

···
@blue.route('/index/',methods=['GET'])
def index():
a=int(request.args.get('a'))
b=int(request.args.get('b'))
try:
a/b
except Exception as e:
print(e)
abort(500)
return render_template('index.html')

@blue.errorhandler(500)
def error500(exception):
return '捕捉异常,错误信息为:%s' % exception

···

manage.py

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


app=Flask(__name__)

# 第二步:绑定蓝图blue和app的关系
app.register_blueprint(blueprint=blue,url_prefix='/app')

# 设置secret_key
app.config['SECRET_KEY']='123'

# 将flask对象交给Manager管理,并且启动方式修改为manager
manager=Manager(app=app)

# 路由copy到views中,在manage.py中不用写路由,
# @app.route('/')
# def hello_world():
#     1/0
#     return  'Hello World'
#
# # 路由匹配规则
# # 1.<id>:默认结束的类型为str
# # 2.<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str
# # 3.<int:id>,指定id的类型为int
# # 4.<float:id>,指定id的类型为浮点数
# # 5.<path:paht>,指定接收的paht为URL中的路径
#
#
# @app.route('/get_id/<id>/')
# def get_id(id):
#     # 匹配str类型的id值
#     return  'id: %s' % id
#
#
# @ app.route('/get_int_id/<int:id>/')
# def get_int_id(id):
#     # 匹配int类型的id值
#     return  'id: %d' % id\
#
#
# @ app.route('/get_float/<float:uid>/')
# def get_float(uid):
#     # 匹配float类型的id值
#     return  'id: %.2f' % uid
#
#
# @app.route('/get_path/<path:upath>')
# def get_path(upath):
#     #匹配URL路径
#     return 'path:%s' % upath


if __name__=='__main__':
    # 使用app
    # app.run()
    # 修改启动的ip和端口
    # app.run(host='0.0.0.0',port=8080)
    # 修改启动的ip和端口,debug模式
    # app.run(host='0.0.0.0',port=8080,debug=True)

    #使用manager
    manager.run()
    # 修改启动的ip和端口,debug模式
    #python xxx.py runserver -h 0.0.0.0 -p 8080 -d

views.py

from flask import Blueprint, redirect, \
    url_for, make_response, render_template, \
    request, abort, session

from utils.functions import is_login

# 第一步:获取蓝图对象,指定蓝图别名为app
blue=Blueprint('app',__name__)


@blue.route('/')
@is_login
def hello_world():
    # 1/0
    return  'Hello World'

# 路由匹配规则
# 1.<id>:默认结束的类型为str
# 2.<string:id(‘id’可以用任意字符串表示)>,指定id的类型为str
# 3.<int:id>,指定id的类型为int
# 4.<float:id>,指定id的类型为浮点数
# 5.<path:paht>,指定接收的paht为URL中的路径


@blue.route('/get_id/<id>/')
def get_id(id):
    # 匹配str类型的id值
    return  'id: %s' % id


@ blue.route('/get_int_id/<int:id>/')
def get_int_id(id):
    # 匹配int类型的id值
    return  'id: %d' % id\


@ blue.route('/get_float/<float:uid>/')
def get_float(uid):
    # 匹配float类型的id值
    return  'id: %.2f' % uid


@blue.route('/get_path/<path:upath>')
def get_path(upath):
    #匹配URL路径
    return 'path:%s' % upath


@blue.route('/redirect/')
def redirect_hello():
    # 实现跳转
    # 1.硬编码URL(将路径写死)
    # return redirect('/app/')
    # 2.反向解析redirect(url_for('蓝图别名.跳转的函数名称'))
    # return redirect(url_for('app.hello_world'))
    return redirect(url_for('app.get_id',id=3))


@blue.route('/request/',methods=['GET','POST','PUT'])
def get_request():
    # 请求上下文
    # 获取GET请求的传递的参数,request.args.get(key)/request.args.getlist(key)
    # 获取POST、PUT、PATCH、DELETE请求的传递的参数,request.form.get(key)/request.form.getlist(key)
    # 判断HTTP请求方式:request.method
    pass


@blue.route('/response/',methods=['GET'])
def get_response():
    # 200是状态码
    # res=make_response('人身苦短,我也python',200)
    # 响应绑定cookie,set_cookie(key,value,max_age.expires)
    # 删除cookie,delete_cookie(key)
    # set_cookie('key', value, max_ages='', expires='')
    res_index=render_template('index.html')
    res=make_response(res_index,200)
    return res

@blue.route('/index/',methods=['GET'])
def index():
    a=int(request.args.get('a'))
    b=int(request.args.get('b'))
    try:
        a/b
    except Exception as e:
        print(e)
        abort(500)
    return render_template('index.html')


@blue.errorhandler(500)
def error500(exception):
    return '捕捉异常,错误信息为:%s' % exception


@blue.route('/login/',methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template('login.html')
    if request.method=='POST':
        username=request.form.get('username')
        password=request.form.get('password')
        # 验证用户名和密码是否正确
        if username=='coco' and password=='123456':
            # 验证通过,登录成功向session中存入登录成功的标识符
            session['login_status']=1

            return redirect(url_for('app.get_response'))
        else:
            return render_template('login.html')
        pass
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容