本文使用创作助手。
下面是一个用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”消息。
请注意,这只是一个简单示例,没有进行表单验证和数据持久化等处理。你可以根据实际需求进行修改和扩展。