手把手教你用python做一个抽奖系统,python项目实践,python练手项目,源码都写出来了

引言

这个抽奖系统的业务逻辑其实非常简单。首先,我们需要一个9宫格的页面,用户可以在页面上添加参与人员。虽然我们可以使用数据库来存储参与人员的信息,但为了方便演示,我选择了简单地使用内存存储。

在这个系统中,除了保证每个人只有一个参与机会外,其他的校验要求都很少。然后,用户可以通过点击开始按钮,页面会随机停下来,然后将停下来的奖项传给后台并保存,最后在前端页面上显示。

虽然逻辑简单,但是通过这个抽奖系统的开发,我们可以巩固自己对Python语法和框架的理解,同时也能够体验到人工智能带来的便利。让我们一起动手搭建这个简易版的抽奖系统吧!

前端界面

尽管前端界面写得不够出色,但这并非我今天的重点。实际上,我想回顾一下Python的编写方式和框架的理解。我创建了一个简单的九宫格,每个格子都设有不同的奖项,而且用户还可以手动进行设置和修改,从而保证了灵活性。

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>抽奖系统</title>
    <link rel="stylesheet" href="/static/css/styles.css">
    <script src="/static/js/main.js"></script>
</head>
<body>
    <h1>欢迎来到小雨抽奖系统</h1>
    <form id="participant-form">
        <label for="participant-name">参与者姓名:</label>
        <input type="text" id="participant-name" name="participant-name" required>
        <button type="submit">添加参与者</button>
    </form>
    <div id="grid">
        <div class="grid-item" data-prize="奖项1">奖项1</div>
        <div class="grid-item" data-prize="奖项2">奖项2</div>
        <div class="grid-item" data-prize="奖项3">奖项3</div>
        <div class="grid-item" data-prize="奖项4">奖项4</div>
        <div class="grid-item" data-prize="奖项5">奖项5</div>
        <div class="grid-item" data-prize="奖项6">奖项6</div>
        <div class="grid-item" data-prize="奖项7">奖项7</div>
        <div class="grid-item" data-prize="奖项8">奖项8</div>
        <div class="grid-item" data-prize="奖项9">奖项9</div>
    </div>
    <button id="draw-button">抽奖</button>
    <h2>获奖名单</h2>
    <ul id="prize-list"></ul>
    <script>
        document.getElementById('participant-form').addEventListener('submit', function(event) {
            event.preventDefault();
            var participantName = document.getElementById('participant-name').value;
            fetch('/participant', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({name: participantName}),
            })
            .then(response => response.json())
            .then(data => {
                console.log(data);
                document.getElementById('participant-name').value = '';
            })
            .catch((error) => {
                console.error('Error:', error);
            });
        });

        document.getElementById('draw-button').addEventListener('click', function() {
            var items = document.getElementsByClassName('grid-item');
            var index = 0;
            var interval = setInterval(function() {
                items[index].classList.remove('active');
                index = (index + 1) % items.length;
                items[index].classList.add('active');
            }, 100);
            setTimeout(function() {
                clearInterval(interval);
                var prize = items[index].getAttribute('data-prize');
                fetch('/draw', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({prize: prize}),
                })
                .then(response => response.json())
                .then(data => {
                    console.log(data);
                    if (data.code !== 1) {
                        alert(data.message);
                    } else {
                        var li = document.createElement("li");
                        li.appendChild(document.createTextNode(data.message));
                        document.getElementById('prize-list').appendChild(li);
                    }
                })
                .catch((error) => {
                    console.error('Error:', error);
                });
            }, Math.floor(Math.random() * (10000 - 3000 + 1)) + 3000);
        });
    </script>
</body>
</html>
</h2></button></title>

CSS样式主要用于配置9个宫格的显示位置和实现动态动画高亮效果。除此之外,并没有对其他效果进行配置。如果你有兴趣,可以在抽奖后自行添加一些炫彩烟花等效果,完全取决于你的发挥。

代码如下:

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

h1, h2 {
    color: #333;
}

form {
    margin-bottom: 20px;
}

#participant-form {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

#participant-form label {
    margin-right: 10px;
}

#participant-form input {
    margin-right: 10px;
}

#participant-form button {
    background-color: #4CAF50;
    color: white;
    border: none;
    padding: 10px 20px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

#draw-button {
    display: block;
    width: 200px;
    height: 50px;
    margin: 20px auto;
    background-color: #f44336;
    color: white;
    border: none;
    text-align: center;
    line-height: 50px;
    font-size: 20px;
    cursor: pointer;
}

#grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    gap: 10px;
    width: 300px;
    height: 300px;
    margin: 0 auto; /* This will center the grid horizontally */
}

.grid-item {
    width: 100%;
    height: 100%;
    border: 1px solid black;
    display: flex;
    justify-content: center;
    align-items: center;
}

.grid-item.active {
    background-color: yellow;
}

#prize-list {
    list-style-type: none;
    padding: 0;
    width: 80%;
    margin: 20px auto;
}

#prize-list li {
    padding: 10px;
    border-bottom: 1px solid #ccc;
}

Python后台

在我们的Python后端中,我们选择使用了fastapi作为框架来接收请求。这个框架有很多优点,其中最重要的是它的速度快、简单易懂。但唯一需要注意的是,在前端向后端传递请求参数时,请求头必须包含一个json的标识。如果没有这个标识,后端将无法正确接收参数,并可能报错。

为了更好地优化我们的后端,如果你有足够的时间,可以考虑集成数据库等一些重量级的操作。这样可以更好地处理数据,并提供更多功能。

主要的Python代码如下:

from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
# from models import Participant, Prize
# from database import SessionLocal, engine
from pydantic import BaseModel
from random import choice

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

templates = Jinja2Templates(directory="templates")
prizes = []
participants = []

class Participant(BaseModel):
    name: str

class Prize(BaseModel):
    winner: str
    prize: str
    
class DatePrize(BaseModel):
    prize: str

@app.get("/")
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/participant")
async def add_participant(participant: Participant):
   participants.append(participant)
   return {"message": "Participant added successfully"}

@app.post("/draw")
async def draw_prize(date_prize: DatePrize):
    if not participants:
        return {"message": "No participants available","code":0}
    winner = choice(participants)
    prize = Prize(winner=winner.name,prize=date_prize.prize)
    prizes.append(prize)
    participants.remove(winner)
    return {"message": f"Congratulations {winner.name}, you have won a prize : {date_prize.prize}!","code":1}


@app.get("/prizes")
async def get_prizes():
    return {"prizes": [prize.winner for prize in prizes]}

@app.get("/participants")
async def get_participants():
    return {"participants": [participant.name for participant in participants]}

由于我使用的是poetry作为项目的运行工具,因此在使用之前,你需要进行一些配置工作。

[tool.poetry]
name = "python-lottery"
version = "0.1.0"
description = "python 抽奖"
authors = ["努力的小雨"]

[tool.poetry.dependencies]
python = "^3.10"
fastapi = "^0.105.0"
jinja2 = "^3.1.2"


[[tool.poetry.source]]
name = "aliyun"
url = "https://mirrors.aliyun.com/pypi/simple/"
default = true
secondary = false

启动项目命令:poetry run uvicorn main:app --reload --port 8081

效果图

image

总结

在本文中,我们使用Python语言和fastapi框架构建了一个简易的抽奖系统。系统的前端界面使用了HTML、JS和CSS来配置样式和实现交互效果。后端使用了fastapi框架接收前端的请求,并处理抽奖逻辑。
在这里插入图片描述

如有侵权,请联系删除。

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常好的问题!以下是一个简单的手把手教程,介绍如何使用Python实现人脸识别。 1. 安装必要的库 首先,您需要安装OpenCV和face_recognition库。您可以使用以下命令在终端上安装它们: ``` pip install opencv-python pip install face_recognition ``` 2. 准备样本图像 您需要准备一些人脸图像,以便训练和测试您的模型。您可以从互联网上下载一些图像,或者使用您自己的照片。将这些图像保存在一个文件夹中,文件夹的名称应该是人物的名字。 3. 训练模型 接下来,您需要训练一个模型来识别人脸。您可以使用face_recognition库中的train函数来训练模型。以下是一个简单的代码示例: ``` import os import face_recognition # 从文件夹中加载人脸图像并进行训练 def train_faces(directory): known_faces = [] known_names = [] for filename in os.listdir(directory): image = face_recognition.load_image_file(directory + "/" + filename) face_encoding = face_recognition.face_encodings(image)[0] known_faces.append(face_encoding) known_names.append(filename.split(".")[0]) return known_faces, known_names # 训练模型 faces_dir = "./faces" known_faces, known_names = train_faces(faces_dir) ``` 该函数将从指定的文件夹中加载所有人脸图像,并使用face_recognition库的face_encodings函数将每个图像编码为一个128维向量。然后,它将这些向量存储在known_faces列表中,并将每个人物的名称存储在known_names列表中。 4. 进行人脸识别 现在,您已经训练好了模型,可以开始进行人脸识别了。以下是一个简单的代码示例: ``` import cv2 import face_recognition # 打开摄像头 video_capture = cv2.VideoCapture(0) # 对每一帧进行处理 while True: # 获取当前帧 ret, frame = video_capture.read() # 将当前帧转换为RGB格式 rgb_frame = frame[:, :, ::-1] # 在当前帧中查找所有人脸位置 face_locations = face_recognition.face_locations(rgb_frame) # 对每个人脸进行编码 face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) # 对于每个编码,查找最佳匹配 for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_faces, face_encoding) name = "Unknown" # 如果有一个匹配,则使用匹配的名称 if True in matches: first_match_index = matches.index(True) name = known_names[first_match_index] # 在人脸周围绘制一个矩形和名称 top, right, bottom, left = face_location cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2) # 显示当前帧 cv2.imshow('Video', frame) # 按'q'键退出循环 if cv2.waitKey(1) & 0xFF == ord('q'): break # 关闭摄像头和窗口 video_capture.release() cv2.destroyAllWindows() ``` 该代码将打开计算机上的摄像头,并对每一帧进行处理。它将使用face_recognition库的face_locations函数查找每个帧中的所有人脸位置,然后使用face_encodings函数对每个人脸进行编码。接下来,它将对每个编码进行比较,并使用最佳匹配的名称来标记每个人脸。最后,它将在每个人脸周围绘制一个矩形和名称,并在屏幕上显示当前帧。 这就是用Python实现人脸识别的基本步骤。当然,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值