python使用Flask框架创建一个简单的动态日历效果

 更新时间:2024年12月21日 11:19:55   作者:镜花照无眠  
这篇文章主要介绍了python使用Flask框架创建一个简单的动态日历,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧

0. 运行效果

运行代码,然后在浏览器中访问 http://127.0.0.1:5000/,将看到一个动态日历,能够通过点击按钮切换月份。

1. 安装 Flask

首先,确保你已经安装了Flask。如果没有,可以使用以下命令安装:

pip install Flask

测试:

from flask import Flask
#from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
#@app.route('/', methods=['GET', 'POST'])
def hello_world():
    return 'Hello, World!'
    #return render_template('calendar.html')
# 仅在开发环境中使用
if __name__ == '__main__':
    app.run(debug=True)  # 仅用于开发环境

打开 http://127.0.0.1:5000 ,可看到helloworld

2. 项目结构

/项目目录
├── app.py
├── static
│   └── bg.jpg  # 确保你将背景图放在这里
└── templates
    └── calendar.html

3. 创建 Flask 应用

接下来,创建一个名为 app.py 的文件。
导入必要的库:

from flask import Flask, render_template, request
import calendar
from datetime import datetime

其中,render_template: 用于渲染 HTML 模板。request: 用于处理 HTTP 请求数据。calendar: Python 的日历模块,用于生成日历。datetime: 用于获取当前日期和时间。

创建 Flask 应用,__name__ 表示当前模块的名称。

app = Flask(__name__)

定义路由

@app.route('/', methods=['GET', 'POST'])

使用 datetime.now() 获取当前时间,并提取出当前的年月份。

now = datetime.now()  # Get current date and time
year = now.year
month = now.month

表单提交,如果请求是 POST 方法(通常是表单提交),则从表单中获取用户选择的月份和年份。根据用户的操作(前一个月或下一个月),更新 month 和 year 变量。

if request.method == 'POST':
    month = int(request.form.get('month'))
    year = int(request.form.get('year'))
    if request.form.get('action') == 'prev':
        if month == 1:
            month = 12
            year -= 1
        else:
            month -= 1
    elif request.form.get('action') == 'next':
        if month == 12:
            month = 1
            year += 1
        else:
            month += 1

生成日历,渲染html模板

cal = calendar.monthcalendar(year, month)
month_year = f"{year}年{month}月"
return render_template('calendar.html', calendar=cal, month_year=month_year, year=year, month=month, now=now)

代码如下:

from flask import Flask, render_template, request
import calendar
from datetime import datetime
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
    now = datetime.now()  # Get current date and time
    year = now.year
    month = now.month
    if request.method == 'POST':
        month = int(request.form.get('month'))
        year = int(request.form.get('year'))
        if request.form.get('action') == 'prev':
            if month == 1:
                month = 12
                year -= 1
            else:
                month -= 1
        elif request.form.get('action') == 'next':
            if month == 12:
                month = 1
                year += 1
            else:
                month += 1
    # Generate calendar
    cal = calendar.monthcalendar(year, month)
    month_year = f"{year}年{month}月"
    return render_template('calendar.html', calendar=cal, month_year=month_year, year=year, month=month, now=now)
if __name__ == '__main__':
    app.run(debug=True)

4. 创建 HTML 模板

在与 app.py 相同的目录下,创建一个名为 templates 的文件夹,并在其中创建一个名为 calendar.html 的文件,添加代码:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>动态日历</title>
    <style>
        body {
            background: url('/static/bg.jpg') no-repeat center center fixed;
            background-size: cover;
            margin: 0;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        .calendar-container {
            position: absolute;
            top: 50px;
            left: 50px;
            width: 300px;
            border: 2px solid white;
            border-radius: 10px;
            background: rgba(255, 255, 255, 0.9);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            padding: 10px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            text-align: center;
            padding: 10px;
            border: 1px solid #ddd;
        }
        .today {
            background-color: red;
            color: white;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .button {
            cursor: pointer;
            font-size: 1.2em;
            padding: 5px 10px;
            background: lightgray;
            border: none;
            border-radius: 5px;
        }
    </style>
</head>
<body>
<div class="calendar-container">
    <div class="header">
        <form method="post" style="display: inline;">
            <input type="hidden" name="month" value="{{ month }}">
            <input type="hidden" name="year" value="{{ year }}">
            <button class="button" name="action" value="prev">&#9664;</button>
        </form>
        <span>{{ month_year }}</span>
        <form method="post" style="display: inline;">
            <input type="hidden" name="month" value="{{ month }}">
            <input type="hidden" name="year" value="{{ year }}">
            <button class="button" name="action" value="next">&#9654;</button>
        </form>
    </div>
    <table>
    <tr>
        <th>日</th>
        <th>一</th>
        <th>二</th>
        <th>三</th>
        <th>四</th>
        <th>五</th>
        <th>六</th>
    </tr>
    {% for week in calendar %}
    <tr>
        {% for day in week %}
        {% if day == 0 %}
        <td></td>
        {% else %}
        <td {% if day == now.day and year == now.year and month == now.month %}class="today"{% endif %}>{{ day }}</td>
        {% endif %}
        {% endfor %}
    </tr>
    {% endfor %}
</table>
</div>
</body>
</html>

背景图路径设置,Flask 会自动为 static 目录中的文件处理 URL,因此可以这样引用它:

background: url('/static/bg.jpg');

到此这篇关于python使用Flask框架创建一个简单的动态日历效果的文章就介绍到这了,更多相关python Flask动态日历内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python实现接口自动化封装导出excel和读写excel数据

    Python实现接口自动化封装导出excel和读写excel数据

    这篇文章主要为大家详细介绍了Python如何实现接口自动化封装导出excel和读写excel数据,文中的示例代码简洁易懂,希望对大家有所帮助
    2023-07-07
  • python使用期物处理并发教程

    python使用期物处理并发教程

    这篇文章主要为大家介绍了python使用期物处理并发教程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • 解析Python编程中的包结构

    解析Python编程中的包结构

    这篇文章主要介绍了解析Python编程中的包结构,包括对一些包管理工具的介绍,需要的朋友可以参考下
    2015-10-10
  • Django中celery的使用项目实例

    Django中celery的使用项目实例

    Celery是⼀个 基于python开发的分布式异步消息任务队列,通过它可以轻松的实现任务的异步处理,下面这篇文章主要给大家介绍了关于Django中celery使用的相关资料,需要的朋友可以参考下
    2022-07-07
  • pyqt qlistwidget改变item颜色的操作

    pyqt qlistwidget改变item颜色的操作

    这篇文章主要介绍了pyqt qlistwidget改变item颜色的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03
  • 浅析Python中的随机采样和概率分布

    浅析Python中的随机采样和概率分布

    Python中包含了很多概率算法,包括基础的随机采样以及许多经典的概率分布生成。本文主要介绍了我们在机器学习中常用的概率函数。感兴趣的同学可以了解一下
    2021-12-12
  • Python实现四舍五入的两个方法总结

    Python实现四舍五入的两个方法总结

    这篇文章主要介绍了python中实现四舍五入的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • 浅谈python正则的常用方法 覆盖范围70%以上

    浅谈python正则的常用方法 覆盖范围70%以上

    这篇文章主要为大家详细介绍了python正则的常用方法,覆盖范围70%以上,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-03-03
  • Python实现数据结构线性链表(单链表)算法示例

    Python实现数据结构线性链表(单链表)算法示例

    这篇文章主要介绍了Python实现数据结构线性链表(单链表)算法,结合实例形式分析了Python单链表的定义、节点插入、删除、打印等相关操作技巧,需要的朋友可以参考下
    2019-05-05
  • 4种非常实用的python内置数据结构

    4种非常实用的python内置数据结构

    这篇文章主要介绍了4种非常实用的python内置数据结构,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-04-04

最新评论