一、flask入门和视图

run启动参数

模板渲染

  • 后端给前端页面传参

  • 前端页面设置css
python 复制代码
from flask import Flask, render_template,jsonify

# 创建flask对象
app = Flask(__name__)

# 视图函数 + 路由route
@app.route("/")
def hello_world():
    # 响应,返回给前端的数据
    return "hello world"


# 模板渲染  templates名字固定,存放html静态文件;static名字固定,存放css和js文件
@app.route("/index")
def index():
    # 会自动寻找templates文件夹下的内容
    return render_template("index.html",name="zhangsan ")
    #  返回json
    #  return jsonify({"name":"jj","age":12}) 序列化


if  __name__ ==  '__main__':
    app.run(debug=True)

路由参数

  • 路由:将从客户端发送过来的请求分发到指定函数上。

    路由参数:
    string 接收任何没有斜杠('/')的字符串(默认)
    int 接收整型
    float 接收浮点型
    path 接收路径,可接收斜线('/')
    uuid 只接受uuid字符串,唯一码,一种生成规则
    any 可以同时指定多种路径,进行限定

python 复制代码
# views.py: 路由 + 视图函数

from flask import Blueprint
from .models import *

# 蓝图
# 第一个参数:蓝图名称,第二个参数:模块名称
blue = Blueprint('user', __name__) # 使用蓝图可以模块化管理路由


@blue.route('/') # 不能使用@app.route 因为@app依赖app = Flask(__name__)
def index():
    return 'index'


# 路由参数
#     string 接收任何没有斜杠('/')的字符串(默认)
#     int	接收整型
#     float	接收浮点型
#     path	接收路径,可接收斜线('/')
#     uuid	只接受uuid字符串,唯一码,一种生成规则
#     any	可以同时指定多种路径,进行限定

# string: 重点
# @blue.route('/string/<string:username>/')
@blue.route('/string/<username>/')
def get_string(username): # 路由的参数必须由函数的参数接收且参数名一致
    print(type(username))  # <class 'str'>
    return username


# int  类型:参数名
@blue.route('/int/<int:id>/')
def get_int(id):
    print(type(id))  # <class 'int'>
    return str(id) # 返回值类型只能是string,dict,list,tuple或者WISG callable

# float
@blue.route('/float/<float:money>/')
def get_float(money):
    print(type(money))  # <class 'float'>
    return str(money)


# path: 支持/的字符串
# localhost:5000/path/he/llo/  返回:he/llo
@blue.route('/path/<path:name>/')
def get_path(name):
    print(type(name))  # <class 'str'>
    return str(name)

# uuid:d12fda71-e885-444a-8cbd-5cdcbcb7c232
@blue.route('/uuid/<uuid:id>/')
def get_uuid(id):
    print(type(id))  # <class 'uuid.UUID'>
    return str(id)

@blue.route('/getuuid/')
def get_uuid2():
    import uuid
    return str(uuid.uuid4())


# any: 从列出的项目中选择一个
@blue.route('/any/<any(apple, orange, banana):fruit>/')
def get_any(fruit):
    print(type(fruit))  # <class 'str'>
    return str(fruit)


# methods: 请求方式
#   默认不支持POST
#   如果需要同时支持GET和POST,就设置methods
@blue.route('/methods/', methods=['GET', 'POST'])
def get_methods():
    return 'methods'

指定请求方法

python 复制代码
# methods: 请求方式
#   默认不支持POST
#   如果需要同时支持GET和POST,就设置methods
@blue.route('/methods/', methods=['GET', 'POST'])
def get_methods():
    return 'methods'

请求和响应

请求

  • Request请求:服务器在接收到客户端的请求后,会自动创建Request对象

python 复制代码
from flask import Blueprint, request, render_template, \
    jsonify, make_response, Response, redirect, url_for, abort
from .models import *

# 蓝图
blue = Blueprint('user', __name__)
# http一次前后端交互:先请求,后响应

# Request: 客户端向服务器发送的请求
@blue.route('/request/', methods=['GET', 'POST'])
def get_request():
    pass
    # print(request)  # <Request 'http://127.0.0.1:5000/request/' [GET]>

    # 重要属性
    print(request.method)  # 请求方式,'GET'或'POST'...
    # GET请求的参数
    #  ImmutableMultiDict: 类字典对象,区别是可以出现重复的key
    # http://127.0.0.1:5000/request/?name=lisi&name=wangwu&age=33
    print(request.args)  # ImmutableMultiDict([('name', 'lisi'), ('name', 'wangwu'), ('age', '33')])
    # print(request.args['name'], request.args['age'])  # lisi 33
    # print(request.args.get('name'))  # lisi
    # print(request.args.getlist('name'))  # ['lisi', 'wangwu']

    # POST请求的参数
    # res = requests.post('http://127.0.0.1:5000/request/',data={'name': 'lucy', 'age': 33})
    print(request.form)  # ImmutableMultiDict([('name', 'lucy'), ('age', '33')])
    # print(request.form.get('name'))  # lucy

    # cookie
    # res = requests.post('http://127.0.0.1:5000/request/',data={'name': 'lucy', 'age': 33},cookies={'name': 'hello'})
    print(request.cookies)  # ImmutableMultiDict([('name', 'hello')])

    # 路径
    print(request.path)  # /request/
    print(request.url)   # http://127.0.0.1:5000/request/?name=lisi&name=wangwu&age=33
    print(request.base_url)  # http://127.0.0.1:5000/request/
    print(request.host_url)  # http://127.0.0.1:5000/
    print(request.remote_addr)  # 127.0.0.1,客户端的ip

    print(request.files)  # 文件内容 ,ImmutableMultiDict([])
    print(request.headers)  # 请求头
    print(request.user_agent)  # 用户代理,包括浏览器和操作系统的信息 , python-requests/2.28.2

    return 'request ok!'

响应

  • Response响应:服务器返回客户端数据
python 复制代码
from flask import Blueprint, request, render_template, \
    jsonify, make_response, Response, redirect, url_for, abort
from .models import *

# 蓝图
blue = Blueprint('user', __name__)
# Response: 服务器端向客户端发送的响应
@blue.route('/response/')
def get_response():
    pass
    # 响应的几种方式
    # 1. 返回字符串(不常用)
    # return 'response OK!'

    # 2. 模板渲染 (前后端不分离)
    # return render_template('index.html', name='张三', age=33)

    # 3. 返回json数据 (前后端分离)
    data = {'name': '李四', 'age': 44}
    # return data

    # jsonify(): 序列化,字典=>字符串
    # return jsonify(data)

    # 4. 自定义Response对象
    html = render_template('index.html', name='张三', age=33)
    print(html, type(html))  # <class 'str'>

    # res = make_response(html, 200)
    res = Response(html)
    return res

重定向

python 复制代码
# Redirect: 重定向
@blue.route('/redirect/')
def make_redirect():
    pass
    # 重定向的几种方式
    # return redirect('https://www.qq.com')
    # return redirect('/response/')

    # url_for():反向解析,通过视图函数名反过来找到路由
    #    url_for('蓝图名称.视图函数名')
    # ret = url_for('user.get_response')
    # print('ret:', ret)  # /response/
    # return redirect(ret)

    # url_for传参
    ret2 = url_for('user.get_request', name='王五', age=66)
    return redirect(ret2)
相关推荐
黄俊懿7 分钟前
【深入理解SpringCloud微服务】手写实现各种限流算法——固定时间窗、滑动时间窗、令牌桶算法、漏桶算法
java·后端·算法·spring cloud·微服务·架构
易辰君8 分钟前
python爬虫 - 深入requests模块
开发语言·爬虫·python
人工智障调包侠9 分钟前
基于深度学习多层感知机进行手机价格预测
人工智能·python·深度学习·机器学习·数据分析
2401_8574396934 分钟前
“衣依”服装销售平台:Spring Boot技术应用与优化
spring boot·后端·mfc
计算机编程-吉哥42 分钟前
计算机毕业设计 基于Python的智能文献管理系统的设计与实现 Python+Django+Vue 前后端分离 附源码 讲解 文档
python·django·毕业设计·计算机毕业论文·计算机毕业设计选题·软件工程毕业设计论文·文献管理系统
Jerry.ZZZ1 小时前
系统设计,如何设计一个秒杀功能
后端
笃励1 小时前
Java面试题二
java·开发语言·python
一颗星星辰2 小时前
Python | 第九章 | 排序和查找
服务器·网络·python
打码人的日常分享2 小时前
企业人力资源管理,人事档案管理,绩效考核,五险一金,招聘培训,薪酬管理一体化管理系统(源码)
java·数据库·python·需求分析·规格说明书
27669582922 小时前
京东e卡滑块 分析
java·javascript·python·node.js·go·滑块·京东