Python制作网页版漂流瓶(本地版见主页)

本文介绍了一个使用PythonFlask框架创建的简单漂流瓶网站,包括前端HTML模板和后端处理逻辑,用户可以输入消息并保存到文件,随机展示一条漂流瓶内容。
摘要由CSDN通过智能技术生成

本文使用创作助手。

下面是一个用Python制作的简单的漂流瓶网站的示例代码。网站使用了Flask框架和HTML模板来创建一个具有输入和随机选择功能的简单网页。你可以根据自己的需要进行修改和扩展。

from flask import Flask, render_template, request
import random

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        message = request.form['message']
        with open('bottles.txt', 'a') as f:
            f.write(message + '\n')
    
    bottles = []
    with open('bottles.txt', 'r') as f:
        bottles = f.read().splitlines()
    
    random_bottle = random.choice(bottles) if bottles else None
    
    return render_template('index.html', random_bottle=random_bottle)

if __name__ == '__main__':
    app.run()

然后在项目目录下创建一个名为templates的文件夹,并在该文件夹中创建一个名为index.html的文件,内容如下:

 

<!DOCTYPE html>
<html>
<head>
    <title>Drift Bottle</title>
    <style>
        body {
            background-color: #f8f8f8;
        }
        
        .container {
            width: 600px;
            margin: 0 auto;
            margin-top: 50px;
            border: 1px solid #ccc;
            padding: 20px;
            background-color: #fff;
        }
        
        textarea {
            width: 100%;
            height: 200px;
            margin-bottom: 10px;
        }
        
        .button {
            display: inline-block;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            text-align: center;
            text-decoration: none;
            cursor: pointer;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Drift Bottle</h1>
        
        {% if random_bottle %}
            <h2>{{ random_bottle }}</h2>
        {% else %}
            <h2>No bottles available</h2>
        {% endif %}
        
        <form action="/" method="POST">
            <textarea name="message" placeholder="Enter your message(s)"></textarea>
            <br>
            <input class="button" type="submit" value="Throw Bottle">
        </form>
    </div>
</body>
</html>

运行代码后,在浏览器中访问http://localhost:5000即可打开漂流瓶网站。你可以在文本框中输入漂流瓶数据,每次按下“Throw Bottle”按钮时,输入的数据将会保存到bottles.txt文件中。网站还会随机选择文件中的信息,并显示在网页上。如果没有漂流瓶数据可用,则会显示“No bottles available”消息。

请注意,这只是一个简单示例,没有进行表单验证和数据持久化等处理。你可以根据实际需求进行修改和扩展。

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值