用openresty和lua实现壁纸投票功能

背景

之前做了一个随机壁纸接口,但是不知道大家喜欢对壁纸的喜好,所以干脆在实现一个投票功能,让用户给自己喜欢的壁纸进行投票。

原理说明

1.当访问http://demo.com/vote/时,会从/home/jobs/webs/imgs及子目录下获取图片列表,然后生成一个投票的vote.html页面,并自动跳转到http://demo.com/vote/vote.html,点击图片即可选中/取消选中,在右下角始终有个悬浮按钮"投票"

2.当点击"投票"之后,会POST调用http://demo.com/vote/,把结果记录到home/data/vote_stats.json,里面记录了得票的图片路径和票数。

3.之后会生成一个result.html页面,并自动跳转到http://demo.com/vote/result.html,壁纸根据得票数自动排序,最下方有个"返回投票页"的按钮

实战

创建vote目录,存放vote.html和result.html

mkdir /home/jobs/webs/vote
chmod 755  /home/jobs/webs/vote -R
chown nginx:nginx  /home/jobs/webs/vote -R

编写lua脚本
cat /etc/nginx/conf.d/vote.lua

package.path = package.path .. ";/usr/local/share/lua/5.1/?.lua;/usr/share/lua/5.1/?.lua"
package.cpath = package.cpath .. ";/usr/local/lib/lua/5.1/?.so;/usr/lib64/lua/5.1/?.so"local cjson = require "cjson"
local lfs = require "lfs"-- 获取图片列表
local function get_images(path)local images = {}for file in lfs.dir(path) doif file ~= "." and file ~= ".." thenlocal full_path = path .. "/" .. filelocal attr = lfs.attributes(full_path)if attr.mode == "file" and (file:match("%.jpg$") or file:match("%.png$")) thentable.insert(images, file)elseif attr.mode == "directory" thenlocal sub_images = get_images(full_path)for _, sub_image in ipairs(sub_images) dotable.insert(images, file .. "/" .. sub_image)endendendendreturn images
end-- 读取统计结果
local function read_stats()local stats_path = "/home/data/vote_stats.json"local stats = {}local file = io.open(stats_path, "r")if file thenlocal content = file:read("*a")file:close()stats = cjson.decode(content) or {}endreturn stats
end-- 保存统计结果
local function save_stats(stats)local stats_path = "/home/data/vote_stats.json"local file = io.open(stats_path, "w")if file thenfile:write(cjson.encode(stats))file:close()elsengx.log(ngx.ERR, "Failed to open file: ", stats_path)end
end-- 生成投票页面 HTML
local function generate_vote_html()local images = get_images("/home/jobs/webs/imgs")-- 生成 HTML 内容local html = [[<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>壁纸投票</title><style>body { font-family: Arial, sans-serif; }img { width: 200px; margin: 10px; border: 3px solid transparent; cursor: pointer; }img.selected { border: 3px solid #007bff; }.image-container { display: flex; flex-wrap: wrap; }.image-item { margin: 10px; text-align: center; }.floating-button {position: fixed;bottom: 20px;right: 20px;padding: 10px 20px;background-color: #007bff;color: white;border: none;border-radius: 5px;cursor: pointer;}.floating-button:hover {background-color: #0056b3;}</style><script>function toggleSelection(img) {img.classList.toggle("selected");var checkbox = img.parentElement.querySelector('input[type="checkbox"]');checkbox.checked = !checkbox.checked;}</script></head><body><h1>壁纸投票</h1><form method="post" action="/vote/"><div class="image-container">]]-- 添加图片和复选框for _, img in ipairs(images) dohtml = html .. string.format([[<div class="image-item"><input type="checkbox" name="%s" id="%s" style="display: none;"><label for="%s"><img src="/vote/imgs/%s" alt="%s" onclick="toggleSelection(this)"></label></div>]], img, img, img, img, img)endhtml = html .. [[</div><button type="submit" class="floating-button">提交投票</button></form></body></html>]]-- 将 HTML 内容写入文件local html_file_path = "/home/jobs/webs/vote/vote.html"local file = io.open(html_file_path, "w")if file thenfile:write(html)file:close()elsengx.log(ngx.ERR, "Failed to open file: ", html_file_path)end
end-- 生成投票结果页面 HTML
local function generate_result_html()local stats = read_stats()-- 按票数排序local sorted_stats = {}for img, data in pairs(stats) dotable.insert(sorted_stats, {img = img, count = data.count})endtable.sort(sorted_stats, function(a, b)return a.count > b.countend)-- 生成 HTML 内容local html = [[<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>投票结果</title><style>body { font-family: Arial, sans-serif; }.stats { margin-top: 20px; }img { width: 200px; margin: 10px; border: 1px solid #ccc; }.image-container { display: flex; flex-wrap: wrap; }.image-item { margin: 10px; text-align: center; }</style></head><body><h1>投票结果</h1><div class="image-container">]]-- 显示投票结果for _, data in ipairs(sorted_stats) doif data.count > 0 thenhtml = html .. string.format([[<div class="image-item"><img src="/vote/imgs/%s" alt="%s"><p>%s: %d 票</p></div>]], data.img, data.img, data.img, data.count)endendhtml = html .. [[</div><a href="/vote/vote.html">返回投票页面</a></body></html>]]-- 将 HTML 内容写入文件local result_file_path = "/home/jobs/webs/vote/result.html"local file = io.open(result_file_path, "w")if file thenfile:write(html)file:close()elsengx.log(ngx.ERR, "Failed to open file: ", result_file_path)end
end-- 处理投票
local function handle_vote()-- 确保请求体已读取ngx.req.read_body()-- 获取 POST 参数local args, err = ngx.req.get_post_args()if not args thenngx.log(ngx.ERR, "Failed to get POST args: ", err)ngx.exit(ngx.HTTP_BAD_REQUEST)end-- 获取投票人 IPlocal voter_ip = ngx.var.remote_addr-- 读取统计结果local stats = read_stats()-- 更新投票数据for img, _ in pairs(args) doif not stats[img] thenstats[img] = {count = 0, voters = {}}endstats[img].count = stats[img].count + 1end-- 保存统计结果save_stats(stats)-- 生成 HTML 文件generate_vote_html()  -- 更新投票页面generate_result_html()  -- 生成投票结果页面-- 重定向到投票结果页面ngx.redirect("/vote/result.html")
end-- 处理请求
if ngx.var.request_method == "POST" thenhandle_vote()
elsegenerate_vote_html()  -- 生成投票页面ngx.redirect("/vote/vote.html")  -- 重定向到投票页面
end

对应的openresty配置

location /vote/vote.html {try_files /vote/vote.html =404;
}
location /vote/result.html {try_files /vote/result.html =404;
}location /vote/ {lua_need_request_body on;  # 启用请求体读取        content_by_lua_file /etc/nginx/conf.d/vote.lua;
}
# 静态图片服务,用于展示壁纸
location /vote/imgs/ {alias /home/jobs/webs/imgs/;
}

效果

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/21360.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【保姆级教程】DeepSeek R1+RAG,基于开源三件套10分钟构建本地AI知识库

一、总体方案 目前在使用 DeepSeek 在线环境时&#xff0c;页面经常显示“服务器繁忙&#xff0c;请稍后再试”&#xff0c;以 DeepSeek R1 现在的火爆程度&#xff0c;这个状况可能还会持续一段时间&#xff0c;所以这里给大家提供了 DeepSeek R1 RAG 的本地部署方案。最后实现…

Java 常用类 10. Java System类

简介&#xff1a; 主要用于获取系统的属性数据和其他操作&#xff0c;构造方法&#xff08;私有的&#xff09;实际上 System 类是一些与系统相关属性和方法的集合&#xff0c;而且在System 类中所有的属性&#xff0c;都是静态的&#xff0c;要想引用这些属性和方法&#xff0…

从零开始构建一个语言模型中vocab_size(词汇表大小)的设定规则

从零开始构建一个语言模型就要设计一个模型框架,其中要配置很多参数。在自然语言处理任务中,vocab_size(词汇表大小) 的设定是模型设计的关键参数之一,它直接影响模型的输入输出结构、计算效率和内存消耗。 本文是在我前文的基础上讲解的:从零开始构建一个小型字符级语言…

python小项目编程-初级(5、词频统计,6、简单得闹钟)

1、词频统计 统计文本文件中每个单词出现的频率。 实现 import tkinter as tk from tkinter import filedialog, messagebox from collections import Counter import reclass WordFrequencyCounter:def __init__(self, master):self.master masterself.master.title("…

一文讲解Redis为什么读写性能高以及I/O复用相关知识点

Redis为什么读写性能高呢&#xff1f; Redis 的速度⾮常快&#xff0c;单机的 Redis 就可以⽀撑每秒十几万的并发&#xff0c;性能是 MySQL 的⼏⼗倍。原因主要有⼏点&#xff1a; ①、基于内存的数据存储&#xff0c;Redis 将数据存储在内存当中&#xff0c;使得数据的读写操…

计算机网络安全之一:网络安全概述

1.1 网络安全的内涵 随着计算机和网络技术的迅猛发展和广泛普及&#xff0c;越来越多的企业将经营的各种业务建立在Internet/Intranet环境中。于是&#xff0c;支持E-mail、文件共享、即时消息传送的消息和协作服务器成为当今商业社会中的极重要的IT基础设施。然而&#xff0…

程函方程的详细推导

以下是基于非均匀介质弹性波方程&#xff08;无纵波假设&#xff09;推导程函方程的详细过程&#xff0c;完整考虑纵波&#xff08;P 波&#xff09;和横波&#xff08;S 波&#xff09;的耦合效应&#xff1a;

【JavaEE进阶】MyBatis通过注解实现增删改查

目录 &#x1f343;前言 &#x1f340;打印日志 &#x1f334;传递参数 &#x1f38b;增(Insert) &#x1f6a9;返回主键 &#x1f384;删(Delete) &#x1f332;改(Update) &#x1f333;查(Select) &#x1f6a9;起别名 &#x1f6a9;结果映射 &#x1f6a9;开启驼…

[AHOI2018初中组] 分组---贪心算法

贪心没套路果真如此。 题目描述 小可可的学校信息组总共有 n 个队员&#xff0c;每个人都有一个实力值 ai​。现在&#xff0c;一年一度的编程大赛就要到了&#xff0c;小可可的学校获得了若干个参赛名额&#xff0c;教练决定把学校信息组的 n 个队员分成若干个小组去参加这场…

DeepSeek动画视频全攻略:从架构到本地部署

DeepSeek 本身并不直接生成动画视频,而是通过与一系列先进的 AI 工具和传统软件协作,完成动画视频的制作任务。这一独特的架构模式,使得 DeepSeek 在动画视频创作领域发挥着不可或缺的辅助作用。其核心流程主要包括脚本生成、画面设计、视频合成与后期处理这几个关键环节。 …

用deepseek学大模型08-长短时记忆网络 (LSTM)

deepseek.com 从入门到精通长短时记忆网络(LSTM),着重介绍的目标函数&#xff0c;损失函数&#xff0c;梯度下降 标量和矩阵形式的数学推导&#xff0c;pytorch真实能跑的代码案例以及模型,数据&#xff0c; 模型应用场景和优缺点&#xff0c;及如何改进解决及改进方法数据推导…

以ChatGPT为例解析大模型背后的技术

目录 1、大模型分类 2、为什么自然语言处理可计算&#xff1f; 2.1、One-hot分类编码&#xff08;传统词表示方法&#xff09; 2.2、词向量 3、Transformer架构 3.1、何为注意力机制&#xff1f; 3.2、注意力机制在 Transformer 模型中有何意义&#xff1f; 3.3、位置编…

鸿道Intewell操作系统:赋能高端装备制造,引领国产数控系统迈向新高度

在当今全球制造业竞争日益激烈的时代&#xff0c;高端装备制造作为国家核心竞争力的重要组成部分&#xff0c;其发展水平直接影响着一个国家的综合实力。而CNC数控系统&#xff0c;作为高端装备制造的“大脑”&#xff0c;对于提升装备的精度、效率和智能化水平起着关键作用。鸿…

mac开发环境配置笔记

1. 终端配置 参考&#xff1a; Mac终端配置笔记-CSDN博客 2. 下载JDK 到 oracle官网 下载jdk: oracle官网 :Java Downloads | Oraclemac的芯片为Intel系列下载 x64版本的jdk&#xff1b;为Apple Mx系列使用 Arm64版本&#xff1b;oracle官网下载时报错&#xff1a;400 Bad R…

【Python爬虫(29)】爬虫数据生命线:质量评估与监控全解

【Python爬虫】专栏简介&#xff1a;本专栏是 Python 爬虫领域的集大成之作&#xff0c;共 100 章节。从 Python 基础语法、爬虫入门知识讲起&#xff0c;深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑&#xff0c;覆盖网页、图片、音频等各类数据爬取&#xff…

大模型工具大比拼:SGLang、Ollama、VLLM、LLaMA.cpp 如何选择?

简介&#xff1a;在人工智能飞速发展的今天&#xff0c;大模型已经成为推动技术革新的核心力量。无论是智能客服、内容创作&#xff0c;还是科研辅助、代码生成&#xff0c;大模型的身影无处不在。然而&#xff0c;面对市场上琳琅满目的工具&#xff0c;如何挑选最适合自己的那…

测评雷龙出品的CS SD NAND贴片式TF卡

一、前言 在现代科技飞速发展的背景下&#xff0c;存储解决方案的创新与进步成为了推动各行各业发展的重要力量。这篇文章讲解雷龙公司出品的CS SD NAND贴片式TF卡的深度测评。这款产品不仅以其小巧精致的设计脱颖而出&#xff0c;更凭借其卓越的性能和可靠性&#xff0c;在众…

Hadoop一 HDFS分布式文件系统

一 分布式文件存储 了解为什么海量数据需要使用分布式存储技术 100T数据太大&#xff0c;单台服务器无法承担。于是&#xff1a; 分布式服务器集群 靠数量取胜&#xff0c;多台服务器组合&#xff0c;才能Hold住&#xff0c;如下 分布式不仅仅是解决了能存的问题&#xff…

windows下docker使用笔记

目录 镜像的配置 镜像的拉取 推荐镜像源列表&#xff08;截至2025年2月测试有效&#xff09; 配置方法 修改容器名字 如何使用卷 创建不同的容器&#xff0c;每个容器中有不同的mysql和java版本&#xff08;不推荐&#xff09; 1. 安装 Docker Desktop&#xff08;Win…

1005 K 次取反后最大化的数组和(贪心)

文章目录 题目[](https://leetcode.cn/problems/maximize-sum-of-array-after-k-negations/)算法原理源码总结 题目 如上图&#xff0c;k是取反的次数&#xff0c;在数组【4&#xff0c;-1,3】中&#xff0c;当k 1&#xff0c;把-2取反为2&#xff0c;和为9&#xff1b;在数组…