亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

基于Python編寫一個有趣的年會抽獎系統(tǒng)

 更新時間:2023年12月20日 08:10:53   作者:努力的小雨  
這篇文章主要為大家詳細介紹了如何使用Python編寫一個簡易的抽獎系統(tǒng),順便幫助大家鞏固一下對Python語法和框架的理解,感興趣的小伙伴可以了解下

引言

馬上就要舉行年會抽獎了,我們都不知道是否有人能夠中獎。我覺得無聊的時候可以嘗試自己寫一個抽獎系統(tǒng),主要是為了娛樂?,F(xiàn)在人工智能這么方便,寫一個簡單的代碼不是一件困難的事情。今天我想和大家一起構(gòu)建一個簡易的抽獎系統(tǒng),這樣也能夠鞏固一下我自己對Python語法和框架的理解。

今天我們將繼續(xù)使用Python語言進行開發(fā),并且使用最簡單的HTML、JS、CSS來配置樣式和界面。在Python中,我們將使用一個名為fastapi的第三方框架,雖然這是我第一次接觸它,但我發(fā)現(xiàn)它真的非常方便使用,簡直就像是把飛機開在馬路上一樣。與使用Spring框架相比,fastapi讓搭建過程變得輕松愉快。

這個抽獎系統(tǒng)的業(yè)務(wù)邏輯其實非常簡單。首先,我們需要一個9宮格的頁面,用戶可以在頁面上添加參與人員。雖然我們可以使用數(shù)據(jù)庫來存儲參與人員的信息,但為了方便演示,我選擇了簡單地使用內(nèi)存存儲。

在這個系統(tǒng)中,除了保證每個人只有一個參與機會外,其他的校驗要求都很少。然后,用戶可以通過點擊開始按鈕,頁面會隨機停下來,然后將停下來的獎項傳給后臺并保存,最后在前端頁面上顯示。

雖然邏輯簡單,但是通過這個抽獎系統(tǒng)的開發(fā),我們可以鞏固自己對Python語法和框架的理解,同時也能夠體驗到人工智能帶來的便利。讓我們一起動手搭建這個簡易版的抽獎系統(tǒng)吧!

前端界面

盡管前端界面寫得不夠出色,但這并非我今天的重點。實際上,我想回顧一下Python的編寫方式和框架的理解。我創(chuàng)建了一個簡單的九宮格,每個格子都設(shè)有不同的獎項,而且用戶還可以手動進行設(shè)置和修改,從而保證了靈活性。

前端代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>抽獎系統(tǒng)</title>
    <link rel="stylesheet" href="/static/css/styles.css" rel="external nofollow" >
    <script src="/static/js/main.js"></script>
</head>
<body>
    <h1>歡迎來到小雨抽獎系統(tǒng)</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個宮格的顯示位置和實現(xiàn)動態(tài)動畫高亮效果。除此之外,并沒有對其他效果進行配置。如果你有興趣,可以在抽獎后自行添加一些炫彩煙花等效果,完全取決于你的發(fā)揮。

代碼如下:

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作為框架來接收請求。這個框架有很多優(yōu)點,其中最重要的是它的速度快、簡單易懂。但唯一需要注意的是,在前端向后端傳遞請求參數(shù)時,請求頭必須包含一個json的標(biāo)識。如果沒有這個標(biāo)識,后端將無法正確接收參數(shù),并可能報錯。

為了更好地優(yōu)化我們的后端,如果你有足夠的時間,可以考慮集成數(shù)據(jù)庫等一些重量級的操作。這樣可以更好地處理數(shù)據(jù),并提供更多功能。

主要的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

效果圖

總結(jié)

在本文中,我們使用Python語言和fastapi框架構(gòu)建了一個簡易的抽獎系統(tǒng)。系統(tǒng)的前端界面使用了HTML、JS和CSS來配置樣式和實現(xiàn)交互效果。后端使用了fastapi框架接收前端的請求,并處理抽獎邏輯。

到此這篇關(guān)于基于Python編寫一個有趣的年會抽獎系統(tǒng)的文章就介紹到這了,更多相關(guān)Python抽獎系統(tǒng)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中合并兩個文本文件并按照姓名首字母排序的例子

    python中合并兩個文本文件并按照姓名首字母排序的例子

    這篇文章主要介紹了python中合并兩個文本文件并按照姓名首字母排序的例子,需要的朋友可以參考下
    2014-04-04
  • Python 單例設(shè)計模式用法實例分析

    Python 單例設(shè)計模式用法實例分析

    這篇文章主要介紹了Python 單例設(shè)計模式用法,結(jié)合實例形式分析了Python單例模式的具體定義與使用操作技巧,需要的朋友可以參考下
    2019-09-09
  • Python使用matplotlib的pie函數(shù)繪制餅狀圖功能示例

    Python使用matplotlib的pie函數(shù)繪制餅狀圖功能示例

    這篇文章主要介紹了Python使用matplotlib的pie函數(shù)繪制餅狀圖功能,結(jié)合實例形式分析了Python使用matplotlib的pie函數(shù)進行餅狀圖繪制的具體操作技巧,注釋中對pie函數(shù)的用法進行了詳細的說明,便于理解,需要的朋友可以參考下
    2018-01-01
  • python?Opencv實現(xiàn)停車位識別思路詳解

    python?Opencv實現(xiàn)停車位識別思路詳解

    這篇文章主要介紹了Opencv實現(xiàn)停車位識別,本文通過示例代碼場景分析給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • Pycharm如何打斷點的方法步驟

    Pycharm如何打斷點的方法步驟

    這篇文章主要介紹了Pycharm如何打斷點的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-06-06
  • Python3實現(xiàn)發(fā)送QQ郵件功能(附件)

    Python3實現(xiàn)發(fā)送QQ郵件功能(附件)

    這篇文章主要為大家詳細介紹了Python3實現(xiàn)發(fā)送QQ郵件功能,附件方面,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • Python漏洞驗證程序Poc利用入門到實戰(zhàn)編寫

    Python漏洞驗證程序Poc利用入門到實戰(zhàn)編寫

    這篇文章主要為大家介紹了Python?Poc利用入門到實戰(zhàn)編寫實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步

    2022-02-02
  • Python中使用logging模塊打印log日志詳解

    Python中使用logging模塊打印log日志詳解

    這篇文章主要介紹了Python中使用logging模塊打印log日志詳解,本文講解了logging模塊介紹、基本使用方法、高級使用方法、使用實例等,需要的朋友可以參考下
    2015-04-04
  • Python中標(biāo)準(zhǔn)模塊importlib詳解

    Python中標(biāo)準(zhǔn)模塊importlib詳解

    這篇文章主要給大家詳細介紹了Python中標(biāo)準(zhǔn)模塊importlib的使用方法和示例,非常簡單,有需要的小伙伴可以參考下
    2017-04-04
  • python實現(xiàn)自動登錄

    python實現(xiàn)自動登錄

    這篇文章主要為大家詳細介紹了python實現(xiàn)自動登錄,填充網(wǎng)頁表單,從而自動登錄WEB門戶,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-09-09

最新評論