经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
手把手教你用python做一个年会抽奖系统
来源:cnblogs  作者:努力的小雨  时间:2023/12/21 9:04:02  对本文有异议

引言

马上就要举行年会抽奖了,我们都不知道是否有人能够中奖。我觉得无聊的时候可以尝试自己写一个抽奖系统,主要是为了娱乐。现在人工智能这么方便,写一个简单的代码不是一件困难的事情。今天我想和大家一起构建一个简易的抽奖系统,这样也能够巩固一下我自己对Python语法和框架的理解。

今天我们将继续使用Python语言进行开发,并且使用最简单的HTML、JS、CSS来配置样式和界面。在Python中,我们将使用一个名为fastapi的第三方框架,虽然这是我第一次接触它,但我发现它真的非常方便使用,简直就像是把飞机开在马路上一样。与使用Spring框架相比,fastapi让搭建过程变得轻松愉快。

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

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

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

前端界面

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

前端代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>抽奖系统</title>
  6. <link rel="stylesheet" href="/static/css/styles.css">
  7. <script src="/static/js/main.js"></script>
  8. </head>
  9. <body>
  10. <h1>欢迎来到小雨抽奖系统</h1>
  11. <form id="participant-form">
  12. <label for="participant-name">参与者姓名:</label>
  13. <input type="text" id="participant-name" name="participant-name" required>
  14. <button type="submit">添加参与者</button>
  15. </form>
  16. <div id="grid">
  17. <div class="grid-item" data-prize="奖项1">奖项1</div>
  18. <div class="grid-item" data-prize="奖项2">奖项2</div>
  19. <div class="grid-item" data-prize="奖项3">奖项3</div>
  20. <div class="grid-item" data-prize="奖项4">奖项4</div>
  21. <div class="grid-item" data-prize="奖项5">奖项5</div>
  22. <div class="grid-item" data-prize="奖项6">奖项6</div>
  23. <div class="grid-item" data-prize="奖项7">奖项7</div>
  24. <div class="grid-item" data-prize="奖项8">奖项8</div>
  25. <div class="grid-item" data-prize="奖项9">奖项9</div>
  26. </div>
  27. <button id="draw-button">抽奖</button>
  28. <h2>获奖名单</h2>
  29. <ul id="prize-list"></ul>
  30. <script>
  31. document.getElementById('participant-form').addEventListener('submit', function(event) {
  32. event.preventDefault();
  33. var participantName = document.getElementById('participant-name').value;
  34. fetch('/participant', {
  35. method: 'POST',
  36. headers: {
  37. 'Content-Type': 'application/json',
  38. },
  39. body: JSON.stringify({name: participantName}),
  40. })
  41. .then(response => response.json())
  42. .then(data => {
  43. console.log(data);
  44. document.getElementById('participant-name').value = '';
  45. })
  46. .catch((error) => {
  47. console.error('Error:', error);
  48. });
  49. });
  50. document.getElementById('draw-button').addEventListener('click', function() {
  51. var items = document.getElementsByClassName('grid-item');
  52. var index = 0;
  53. var interval = setInterval(function() {
  54. items[index].classList.remove('active');
  55. index = (index + 1) % items.length;
  56. items[index].classList.add('active');
  57. }, 100);
  58. setTimeout(function() {
  59. clearInterval(interval);
  60. var prize = items[index].getAttribute('data-prize');
  61. fetch('/draw', {
  62. method: 'POST',
  63. headers: {
  64. 'Content-Type': 'application/json',
  65. },
  66. body: JSON.stringify({prize: prize}),
  67. })
  68. .then(response => response.json())
  69. .then(data => {
  70. console.log(data);
  71. if (data.code !== 1) {
  72. alert(data.message);
  73. } else {
  74. var li = document.createElement("li");
  75. li.appendChild(document.createTextNode(data.message));
  76. document.getElementById('prize-list').appendChild(li);
  77. }
  78. })
  79. .catch((error) => {
  80. console.error('Error:', error);
  81. });
  82. }, Math.floor(Math.random() * (10000 - 3000 + 1)) + 3000);
  83. });
  84. </script>
  85. </body>
  86. </html>
  87. </h2></button></title>

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

代码如下:

  1. body {
  2. font-family: Arial, sans-serif;
  3. margin: 0;
  4. padding: 0;
  5. background-color: #f4f4f4;
  6. }
  7. h1, h2 {
  8. color: #333;
  9. }
  10. form {
  11. margin-bottom: 20px;
  12. }
  13. #participant-form {
  14. display: flex;
  15. justify-content: center;
  16. margin-top: 20px;
  17. }
  18. #participant-form label {
  19. margin-right: 10px;
  20. }
  21. #participant-form input {
  22. margin-right: 10px;
  23. }
  24. #participant-form button {
  25. background-color: #4CAF50;
  26. color: white;
  27. border: none;
  28. padding: 10px 20px;
  29. text-align: center;
  30. text-decoration: none;
  31. display: inline-block;
  32. font-size: 16px;
  33. margin: 4px 2px;
  34. cursor: pointer;
  35. }
  36. #draw-button {
  37. display: block;
  38. width: 200px;
  39. height: 50px;
  40. margin: 20px auto;
  41. background-color: #f44336;
  42. color: white;
  43. border: none;
  44. text-align: center;
  45. line-height: 50px;
  46. font-size: 20px;
  47. cursor: pointer;
  48. }
  49. #grid {
  50. display: grid;
  51. grid-template-columns: repeat(3, 1fr);
  52. grid-template-rows: repeat(3, 1fr);
  53. gap: 10px;
  54. width: 300px;
  55. height: 300px;
  56. margin: 0 auto; /* This will center the grid horizontally */
  57. }
  58. .grid-item {
  59. width: 100%;
  60. height: 100%;
  61. border: 1px solid black;
  62. display: flex;
  63. justify-content: center;
  64. align-items: center;
  65. }
  66. .grid-item.active {
  67. background-color: yellow;
  68. }
  69. #prize-list {
  70. list-style-type: none;
  71. padding: 0;
  72. width: 80%;
  73. margin: 20px auto;
  74. }
  75. #prize-list li {
  76. padding: 10px;
  77. border-bottom: 1px solid #ccc;
  78. }

Python后台

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

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

主要的Python代码如下:

  1. from fastapi import FastAPI, Request
  2. from fastapi.templating import Jinja2Templates
  3. from fastapi.staticfiles import StaticFiles
  4. # from models import Participant, Prize
  5. # from database import SessionLocal, engine
  6. from pydantic import BaseModel
  7. from random import choice
  8. app = FastAPI()
  9. app.mount("/static", StaticFiles(directory="static"), name="static")
  10. templates = Jinja2Templates(directory="templates")
  11. prizes = []
  12. participants = []
  13. class Participant(BaseModel):
  14. name: str
  15. class Prize(BaseModel):
  16. winner: str
  17. prize: str
  18. class DatePrize(BaseModel):
  19. prize: str
  20. @app.get("/")
  21. async def root(request: Request):
  22. return templates.TemplateResponse("index.html", {"request": request})
  23. @app.post("/participant")
  24. async def add_participant(participant: Participant):
  25. participants.append(participant)
  26. return {"message": "Participant added successfully"}
  27. @app.post("/draw")
  28. async def draw_prize(date_prize: DatePrize):
  29. if not participants:
  30. return {"message": "No participants available","code":0}
  31. winner = choice(participants)
  32. prize = Prize(winner=winner.name,prize=date_prize.prize)
  33. prizes.append(prize)
  34. participants.remove(winner)
  35. return {"message": f"Congratulations {winner.name}, you have won a prize : {date_prize.prize}!","code":1}
  36. @app.get("/prizes")
  37. async def get_prizes():
  38. return {"prizes": [prize.winner for prize in prizes]}
  39. @app.get("/participants")
  40. async def get_participants():
  41. return {"participants": [participant.name for participant in participants]}

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

  1. [tool.poetry]
  2. name = "python-lottery"
  3. version = "0.1.0"
  4. description = "python 抽奖"
  5. authors = ["努力的小雨"]
  6. [tool.poetry.dependencies]
  7. python = "^3.10"
  8. fastapi = "^0.105.0"
  9. jinja2 = "^3.1.2"
  10. [[tool.poetry.source]]
  11. name = "aliyun"
  12. url = "https://mirrors.aliyun.com/pypi/simple/"
  13. default = true
  14. secondary = false

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

效果图

image

总结

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

说实话,虽然我们有能力开发一个简易的抽奖系统,但既然我们都是程序员,为何要费力去搞一个抽奖系统呢?我们可以采用更简单的方式,将每个人的序号写在纸条上,放进一个纸箱子里,然后让领导亲自用手抓取。这样做不仅更可靠,还能增加年会的活跃氛围。

原文链接:https://www.cnblogs.com/guoxiaoyu/p/17914771.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号