会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132384个问题
Python 全系列/第一阶段:Python入门/面向对象 17762楼
Python 全系列/第九阶段:前端进阶-高效开发Vue框架/ES6新特性 17763楼
微服务/第十四阶段:容器管理技术/(旧)Docker 17765楼

yolov8网络架构的代码实现

1. 环境准备

硬件需求

  • GPU:推荐使用 NVIDIA GPU(如 RTX 30 系列),显存至少 8GB。

  • CPU:如果没有 GPU,可以使用 CPU,但训练和推理速度会较慢。

依赖安装

YOLOv8 依赖于 ultralytics 库,可以通过以下命令安装:

bash

pip install ultralytics


其他依赖

  • Python 3.8 或更高版本

  • PyTorch 1.8 或更高版本

  • OpenCV(用于图像处理)

安装 PyTorch 和 OpenCV:

bash

pip install torch torchvision torchaudio
pip install opencv-python


2. YOLOv8 网络架构概述

YOLOv8 的网络架构基于 CSPDarknet 骨干网络,结合了 PANet(Path Aggregation Network)和 SPP(Spatial Pyramid Pooling)模块,具有以下特点:

  1. CSPDarknet:高效的骨干网络,提取图像特征。

  2. PANet:增强特征金字塔,提升多尺度目标检测能力。

  3. SPP:增加感受野,提升模型对目标的全局理解能力。



3. YOLOv8 代码实现

步骤 1:加载预训练模型

YOLOv8 提供了多种预训练模型(如 yolov8n.ptyolov8s.pt 等),我们可以直接加载并使用。

from ultralytics import YOLO
# 加载预训练模型(YOLOv8n 是最小的模型)
model = YOLO("yolov8n.pt")
# 打印模型结构
print(model)


步骤 2:推理(目标检测)

使用加载的模型对图像或视频进行目标检测。

# 对单张图片进行推理
results = model(" 
# 可视化结果
results[0].show()
# 保存结果
results[0].save("output.jpg")


步骤 3:训练自定义数据集

YOLOv8 支持训练自定义数据集。首先需要准备数据集,格式为 YOLO 格式(每张图片对应一个 .txt 文件,包含目标类别和边界框信息)。

# 加载自定义数据集配置文件(data.yaml)model = YOLO("yolov8n.pt")  # 加载模型model.train(data="data.yaml", epochs=100, imgsz=640)  # 训练模型

步骤 4:验证模型

训练完成后,可以使用验证集评估模型性能。

# 验证模型
metrics = model.val()
print(metrics.box.map)  # 打印 mAP(平均精度)


步骤 5:导出模型

YOLOv8 支持将模型导出为多种格式(如 ONNX、TensorRT 等),以便在不同平台上部署。

# 导出模型为 ONNX 格式
model.export(format="onnx")


4. YOLOv8 网络架构详解

CSPDarknet 骨干网络

  • CSP(Cross Stage Partial):通过部分连接减少计算量,同时保持特征提取能力。

  • Darknet:基于卷积神经网络的特征提取器。

PANet 特征金字塔

  • FPN(Feature Pyramid Network):提取多尺度特征。

  • PANet:在 FPN 基础上增加自底向上的路径,增强特征融合。

SPP 模块

  • Spatial Pyramid Pooling:通过不同尺度的池化操作,增加感受野,提升模型对目标的全局理解能力。



5. 参考链接


6. 总结

YOLOv8 是一个高效、灵活的目标检测模型,适用于多种任务(如目标检测、实例分割、姿态估计等)。通过 ultralytics 库,我们可以轻松实现模型的加载、推理、训练和部署。


人工智能/第十四阶段:深度学习-目标检测YOLO(V8正在更新中)实战/YOLOv5项目实战 17766楼
JAVA 全系列/第一阶段:JAVA 快速入门/面向对象详解和JVM底层内存分析 17767楼

'''
新增功能:
1,敌方子弹与我方坦克的碰撞
2,添加爆炸效果
'''
import time

import pygame,random
from pygame.sprite import Sprite

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
BG_COLOR = pygame.Color(0,0,255)
TEXT_COLOR = pygame.Color(255,0,0)
class BaseItem(Sprite):
    def __init__(self,color,wieth,height):
        pygame.sprite.Sprite.__init__(self)
class Maingame():
    windows = None
    my_tank = None
    #初始化敌方坦克列表
    enemyTankList = []
    #初始化敌方坦克数量
    enemyTankCount = 5
    #初始化我方坦克子弹列表
    myBulletList = []
    #初始化敌方坦克列表
    enemyBulletList = []
    #初始化爆炸列表
    exployedList = []
    def __init__(self):
        pass

    #开始游戏
    def startgame(self):
        #加载主窗口
        #初始化窗口
        pygame.display.init()
        #设置窗口的大小及显示
        Maingame.windows = pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
        #初始化我方坦克
        Maingame.my_tank = Tank(350,250)
        #初始化敌方坦克
        self.creatEnemyTank()
        pygame.display.set_caption('坦克大战1.0')
        Maingame.windows.fill(BG_COLOR)
        while True:
            #让循环慢一点,使坦克不要移动的太快
            time.sleep(0.02)
            Maingame.windows.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            Maingame.windows.blit(self.textSurface('敌方剩余坦克数:{}'.format(len(Maingame.enemyTankList))),(10,10))
            #调用我方坦克显示的方法
            self.blitMyTank()
            #调用敌方坦克显示方法
            self.blitEnemyTank()
            #调用坦克移动的方法,如果坦克的开关是开启,才可以移动
            if not Maingame.my_tank.stop:
                Maingame.my_tank.move()
            #调用我方子弹显示方法
            self.blitBullet()
            #调用敌方子弹显示方法
            self.blitEnemyBullet()
            #调用子弹爆炸展示的方法
            self.blitExplode()
            pygame.display.update()

    #初始化敌方坦克并将敌方坦克添加到列表中
    def creatEnemyTank(self):
        top = 100
        for i in range(Maingame.enemyTankCount):
            left = random.randint(1,600)
            speed = random.randint(1,4)
            enemy = EnemyTank(left,top,speed)
            Maingame.enemyTankList.append(enemy)
    #定义循环遍历敌方坦克并展示坦克方法
    def blitEnemyTank(self):
        for enemyTank in Maingame.enemyTankList:
            # 判断敌方坦克状态是否活着
            if enemyTank.live:
                enemyTank.displayTank()
                enemyTank.randMove()
                enemybullet = enemyTank.shot()
                # 判断子弹是否为none,如果不为none,则添加到列表中
                if enemybullet:
                    Maingame.enemyBulletList.append(enemybullet)
            else:#如果没活着,则从敌方坦克列表中删除敌方坦克
                Maingame.enemyTankList.remove(enemyTank)
    #定义循环遍历我方坦克子弹列表并显示子弹的方法
    def blitBullet(self):
        for mybullet in Maingame.myBulletList:
            #通过子弹的状态判断子弹显示还是消失
            if mybullet.live:
                mybullet.displayBullet()
                mybullet.moveBullet()
                mybullet.myBullet_hit_enemyBullet()
            else:
                Maingame.myBulletList.remove(mybullet)
    #定义循环遍历敌方坦克子弹列表并显示子弹的方法
    def blitEnemyBullet(self):
        for enemybullet in Maingame.enemyBulletList:
            # 通过子弹的状态判断子弹显示还是消失
            if enemybullet.live:
                enemybullet.displayBullet()
                enemybullet.moveBullet()
                enemybullet.enemyBullet_hit_myTank()
            else:
                Maingame.enemyBulletList.remove(enemybullet)
    #定义我方子弹爆炸效果展示的方法
    def blitExplode(self):
        for exployed in Maingame.exployedList:
            if exployed.live:
                exployed.disExplode()
            else:
                Maingame.exployedList.remove(exployed)
    #定义我方坦克显示方法
    def blitMyTank(self):
        if Maingame.my_tank.live:
            Maingame.my_tank.displayTank()
    #结束游戏
    def endgame(self):
        print('游戏结束')
        exit()
    #绘制文本
    def textSurface(self,text):
        pygame.font.init()
        # print(pygame.font.get_fonts())
        font = pygame.font.SysFont('fangsong',14)
        textSurface = font.render(text,True,TEXT_COLOR)
        return textSurface
    #获取事件
    def getEvent(self):
        self.eventList = pygame.event.get()
        #如果按下的是退出键,则退出游戏
        for event in self.eventList:
            # 遍历事件,判断事件是退出还是向上、下、左、右移动
            if event.type == pygame.QUIT:
                self.endgame()
            #判断坦克状态
            if Maingame.my_tank.live:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        Maingame.my_tank.direction = 'L'
                        Maingame.my_tank.stop = False
                        print('按下左键,坦克向左移动')
                    elif event.key == pygame.K_RIGHT:
                        Maingame.my_tank.direction = 'R'
                        Maingame.my_tank.stop = False
                        print('按下右键,坦克向右移动')
                    elif event.key == pygame.K_UP:
                        Maingame.my_tank.direction = 'U'
                        Maingame.my_tank.stop = False
                        print('按下上键,坦克向上移动')
                    elif event.key == pygame.K_DOWN:
                        Maingame.my_tank.direction = 'D'
                        Maingame.my_tank.stop = False
                        print('按下下键,坦克向下移动')
                    elif event.key == pygame.K_SPACE:
                        print('按下空格键,坦克发射子弹')
                        # 创建我方坦克发射的子弹,并且一次最多发射3颗子弹
                        if len(Maingame.myBulletList) < 3:
                            my_Bullet = Bullet(Maingame.my_tank)
                            Maingame.myBulletList.append(my_Bullet)
                # 松开按键,修改移动状态为true
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
                        Maingame.my_tank.stop = True



class Tank(BaseItem):
    #创建坦克距离左边left,距离上边top
    def __init__(self,top,left):
        #创建字典保存图片
        self.images = {
            'U': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/p1tankU.gif'),
            'D': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/p1tankD.gif'),
            'L': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/p1tankL.gif'),
            'R': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/p1tankR.gif')
        }
        #方向
        self.direction = 'U'
        #根据当前图片的方向获取图片
        self.image = self.images[self.direction]
        #根据图片获取区域
        self.rect = self.image.get_rect()
        #设置区域的left和top
        self.rect.left = left
        self.rect.top = top
        #定义坦克移动的速度
        self.speed = 5
        self.stop = True
        #定义坦克的状态
        self.live = True


    #移动
    def move(self):
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif self.direction == 'D':
            if self.rect.top + self.rect.height < SCREEN_HEIGHT:
                self.rect.top += self.speed
        elif self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        else:
            if self.rect.left + self.rect.height < SCREEN_WIDTH:
                self.rect.left += self.speed

    #射击
    def shot(self):
        return Bullet(self)

    #显示坦克
    def displayTank(self):
        #获取展示的对象
        self.image = self.images[self.direction]
        Maingame.windows.blit(self.image, self.rect)
#我方坦克
class MyTank(Tank):
    def __init__(self):
        pass
#敌方坦克
class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        #调用父类的初始化方法
        super(EnemyTank, self).__init__(left,top)
        #加载图片集
        self.images = {
            'U': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/enemy1U.gif'),
            'L': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/enemy1L.gif'),
            'D': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/enemy1D.gif'),
            'R': pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/enemy1R.gif')
        }
        #定义敌方坦克方向
        self.direction = self.ranDirection()
        #根据方向加载敌方坦克
        self.image = self.images[self.direction]
        #区域
        self.rect = self.image.get_rect()
        #对left和top进行赋值
        self.rect.left = left
        self.rect.top = top
        #速度
        self.speed = speed
        #开关
        self.flag = True
        #步数
        self.step = 60

    #定义随机生成敌方坦克方向的方法
    def ranDirection(self):
        self.num = random.randint(1,4)
        if self.num == 1:
            return 'U'
        elif self.num == 2:
            return 'L'
        elif self.num == 3:
            return 'D'
        elif self.num == 4:
            return 'R'
    #定义敌方坦克随机移动的方法
    def randMove(self):
        if self.step <= 0:
            self.direction = self.ranDirection()
            self.step = 60
        else:
            self.move()
            self.step -= 1
    #重写shot方法
    def shot(self):
        num = random.randint(1,100)
        if num <= 5:
            return Bullet(self)
#子弹类
class Bullet(BaseItem):
    def __init__(self,tank):
        #加载子弹图片
        self.image = pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/enemymissile.gif')
        #坦克的方向决定子弹的方向
        self.direction = tank.direction
        #获取区域
        self.rect = self.image.get_rect()
        #子弹的top和left取决于方向
        if self.direction == 'U':
            self.rect.left = tank.rect.left + tank.rect.width/2 - self.rect.width/2
            self.rect.top = tank.rect.top - self.rect.height
        elif self.direction == 'D':
            self.rect.left = tank.rect.left + tank.rect.width/2 -self.rect.width/2
            self.rect.top = tank.rect.top + tank.rect.height
        elif self.direction == 'L':
            self.rect.left = tank.rect.left - self.rect.width
            self.rect.top = tank.rect.top + tank.rect.width/2 - self.rect.width/2
        elif self.direction == 'R':
            self.rect.left = tank.rect.left + tank.rect.width
            self.rect.top = tank.rect.top + tank.rect.width/2 - self.rect.width/2
        #子弹的速度
        self.speed = 6
        #子弹的状态
        self.live = True
    #子弹移动的方法
    def moveBullet(self):
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
            else:
                self.live = False
        elif self.direction == 'D':
            if self.rect.top + self.rect.height < SCREEN_HEIGHT:
                self.rect.top += self.speed
            else:
                self.live = False
        elif self.direction == 'R':
            if self.rect.left + self.rect.width < SCREEN_WIDTH:
                self.rect.left += self.speed
            else:
                self.live = False
        elif self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
            else:
                self.live = False
    #子弹展示的方法
    def displayBullet(self):
        #将子弹图片surface加载到窗口
        Maingame.windows.blit(self.image,self.rect)
    #定义我方子弹与敌方坦克的碰撞的方法
    def myBullet_hit_enemyBullet(self):
        for enemyTank in Maingame.enemyTankList:
            if pygame.sprite.collide_rect(enemyTank, self):
                #修改敌方坦克和我方子弹的状态
                enemyTank.live = False
                self.live = False
                #创建爆炸对象并添加到列表中
                exployeTank = Explode(enemyTank)
                Maingame.exployedList.append(exployeTank)
    #定义敌方子弹与我方坦克的碰撞的方法
    def enemyBullet_hit_myTank(self):
        if pygame.sprite.collide_rect(Maingame.my_tank,self):
            Maingame.my_tank.live = False
            self.live = False
            #创建爆炸对象并添加到列表中
            myexployed = Explode(Maingame.my_tank)
            Maingame.exployedList.append(myexployed)



#墙壁类
class Wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displayWall(self):
        pass
#爆炸类
class Explode():
    def __init__(self,tank):
        #子弹爆炸的位置由当前打中坦克的位置决定
        self.rect = tank.rect
        self.images = [
            pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/blast0.gif'),
            pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/blast1.gif'),
            pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/blast2.gif'),
            pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/blast3.gif'),
            pygame.image.load('E:/xjp/PycharmProjects/mypro01/imgs/blast4.gif')
        ]
        self.step = 0
        self.image = self.images[self.step]
        self.live = True
    #展示爆炸效果方法
    def disExplode(self):
        #循环遍历爆炸图片
        if self.step < len(self.images):
            self.image = self.images[self.step]
            self.step += 1
            #添加到主窗口
            Maingame.windows.blit(self.image,self.rect)
        else:
            self.live = False
            self.step = 0
class Music():
    def __init__(self):
        pass
    #播放音乐
    def play(self):
        pass

if __name__ == '__main__':
    Maingame().startgame()

老师,我的代码有什么问题吗?为啥我方坦克消亡的情况下敌方子弹如果出现在右下角的位置还会爆炸呀

image.png







Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 17769楼

// pages/food/food.js
var productData = require('../../utils/productData.js');
var request = require('../../utils/request.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    location: '',
    productType: [],
    listdata: [],
    num: 1,
    latitude:'',
    longitude:''


  },
 


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      productType: productData
    });
    //进入食疗方 获取定位 
    wx.getLocation({
      success:  res=>{
               console.log(res.latitude);
               console.log(res.longitude);
             
               this.setData({
                   latitude: res.latitude,
                   longitude:res.longitude
               });
               
               wx.request({
                   url: 'http://iwenwiki.com:3002/api/lbs/location',
                   data: {
                       latitude:  this.data.latitude,
                       longitude: this.data.longitude
                   },
                   success: result => {
                       console.log(result.data.result.address_component.city);
                       var cityName = result.data.result.address_component.city.slice(0,2);
                     
                       this.setData({
                         location:cityName
                       });
                       console.log(this.data.location);
                   }
               })
  
  
  
           },
           fail: err => {
               console.log(err);
           }
       });
       console.log(this.data.location);
    // console.log(productData);
   
    var data1 = {
      city: this.data.location,
      page: this.data.num
    }
    request('get', '/api/foods/list', data1, true, (res) => {
      console.log(res.data.result);
      this.setData({
        listdata: res.data.result
      })
    }, function (error) {
      console.log(error);
    }, function () {
      console.log('已经没有数据可以加载了');
    })
    // console.log(request);

    // 获取食疗方数据
    // wx.request({
    //   url: 'http://iwenwiki.com:3002/api/foods/list',
    //   data:{
    //       city:this.data.location,
    //       page:this.data.num
    //   },
    //   success:res=>{
    //       console.log(res.data.data);
    //       wx.showLoading({
    //         title: '加载中',
    //       })
    //      if(res.data.status==200){
    //         console.log(res.data.data.result);
    //         this.setData({
    //             listdata:res.data.data.result,
    //             isShow:true
    //         })
    //      }
    //   },
    //   complete:res=>{
    //     wx.hideLoading()
    //   }
    // })
  },

  // 点击分类,进入相对应页面
  productType: function (e) {
    console.log(e);
    wx.navigateTo({
      url: '../productType/productType?ID=' + e.currentTarget.dataset.mark,
    })
  },



  // 按钮--加载更多数据
  getMore: function () {
    this.data.num++;
    console.log(this.data.num);
    request('get', '/api/foods/list', data1, true, (res) => {
        console.log(res.data.result);
        this.setData({
          listdata: this.data.listdata.concat(res.data.result),
        });
        this.setData({
          isShow: true
        })
      }, (error) => {
        console.log(error);
      },
      function () {
        this.setData({
          isShow: false
        })
        console.log('已经没有数据可以加载了');
      })

    //----------------------------
    // wx.request({
    //   url: 'http://iwenwiki.com:3002/api/foods/list',
    //   data:{
    //       city:this.data.location,
    //       page:this.data.num,
    //       isShow:false
    //   },
    //   success:res=>{
    //       console.log(res.data.data);
    //       wx.showLoading({
    //         title: '加载中',
    //       })
    //      if(res.data.status==200){
    //         console.log(res.data.data.result);
    //         this.setData({
    //             listdata:this.data.listdata.concat(res.data.data.result),

    //         })
    //      }else{
    //        this.setData({
    //          isShow:false
    //        })
    //        console.log('没有数据了,加载完了');
    //      }
    //   },
    //   complete:res=>{
    //     wx.hideLoading()
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
console.log(11);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  //下拉刷新
  onPullDownRefresh: function () {
    this.setData({
      num: 1
    })
    var data1 = {
      city: this.data.location,
      page: this.data.num
    }
    request('get', '/api/foods/list', data1, true, (res) => {
      console.log(res.data.result);
      this.setData({
        listdata: res.data.result
      })
    }, function (error) {
      console.log(error);
    }, function () {
      console.log('已经没有数据可以加载了');
    })
    //----------------------------------------------
    // wx.request({
    //   url: 'http://iwenwiki.com:3002/api/foods/list',
    //   data:{
    //       city:this.data.location,
    //       page:this.data.num
    //   },
    //   success:res=>{
    //       console.log(res.data.data);
    //       wx.showLoading({
    //         title: '加载中',
    //       })
    //      if(res.data.status==200){
    //         console.log(res.data.data.result);
    //         this.setData({
    //             listdata:res.data.data.result,
    //             // isShow:true
    //         })
    //      }
    //   },
    //   complete:res=>{
    //     wx.hideLoading()
    //   }
    // })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //下拉加载更多
    this.data.num++;
    console.log('下拉到底了');
    var data1 = {
      city: this.data.location,
      page: this.data.num,
    }
    request('get', '/api/foods/list', data1, true, (res) => {
        console.log(res.data.result);
        this.setData({
          listdata: this.data.listdata.concat(res.data.result),
        })
      }, (error) => {
        console.log(error);
      },
      function () {
        console.log('已经没有数据可以加载了');
      })
    //  wx.request({

    //   url: 'http://iwenwiki.com:3002/api/foods/list',
    //   data:{
    //       city:this.data.location,
    //       page:this.data.num,
    //       isShow:false
    //   },
    //   success:res=>{
    //       console.log(res.data.data);
    //       wx.showLoading({
    //         title: '加载中',
    //       })
    //      if(res.data.status==200){
    //         console.log(res.data.data.result);
    //         this.setData({
    //             listdata:this.data.listdata.concat(res.data.data.result),

    //         })
    //      }else{
    //        this.setData({
    //          isShow:false
    //        })
    //        console.log('没有数据了,加载完了');
    //      }
    //   },
    //   complete:res=>{
    //     wx.hideLoading()
    //   }

    //  })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

老师 视频讲课时一开始进入食疗方页面是默认北京的现在改成一进入食疗方这个页面就获取当前城市  我看后台输出data数据已经改成了当前城市 当时那个请求数据列表的请求没返回任何东西也没报错

image.png


WEB前端全系列/第十三阶段:微信小程序-安心食疗(旧)/安心食疗-定位-搜索 17770楼
JAVA 全系列/第九阶段:权限控制与安全认证/Shiro(旧) 17771楼

from flask import Flask,Response
from datetime import datetime,timedelta
from cmsblueprint import bp

app = Flask(__name__)
app.register_blueprint(bp)
app.config['SERVER_NAME']="momo.com:5000"

@app.route('/')
def hello_world():
    return 'Hello World!'
@app.route('/createCookie/')
def createCookie():
    resp = Response('由服务器端创建cookie信息,数据是少量的,服务器端把信息返回到客户端的request Headers,并且由客户端进行cookie信息的保存')
    # resp.set_cookie("uname","momo")
    # resp.set_cookie("pwd",'123456')

    #设置Cookie的有效期【存活时间】方式1 :max_age=以秒为单位【距离现在多少秒后cookie会过期】
    # resp.set_cookie("uname", "momo",max_age=20)
    # resp.set_cookie("pwd","123")

    #设置Cookie的有效期【存活时间】方式2 : expires= datetime类型。
    #这个时间需要设置为格林尼治时间,相对北京时间来说 会自动+8小时
    # ex = datetime(year=2020,month=4,day=29,hour=12,minute=0,second=0)
    ex = datetime(year=2020,month=4,day=29,hour=4,minute=0,second=0)
    # resp.set_cookie("uname","momo",expires=ex)
    # resp.set_cookie("pwd","1234")

    #如果max_age 和expires同时设置,系统会采用max_age
    # resp.set_cookie("unlame","momo",expires=ex,max_age=20)
    # resp.set_cookie("pwd","123")
    ex2 = datetime.now()+timedelta(days=29,hours=16)
    resp.set_cookie("pwd","123")
    # resp.set_cookie("uname","momo",expires=ex2)
    resp.set_cookie("uname","lulu",expires=ex2,domain=".momo.com")
    return resp
@app.route('/deleteCookie/')
def deleteCookie():
    resp = Response('删除cookie消息')
    resp.delete_cookie('uname')
    return resp

if __name__ == '__main__':
    app.run(debug=True)
from flask import Blueprint,request


bp = Blueprint('cms',__name__,subdomain='cms')

@bp.route('/')
def index():
    uname = request.cookies.get('uname')
        return uname or "没有获取到cookie"
老师,我和视频上的代码一样,为什么;运行出来的结果却不一样,我的结果是

OG}BE97EQ`U)YB0`XCG7{@1.png

Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/Flask高级 17775楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637