from flask import Flask, jsonify, send_from_directory app = Flask(__name__, static_folder="public", static_url_path="") # 根路径返回 index.html @app.route("/") def serve_index(): return send_from_directory(app.static_folder, "index.html") # API 子路径,提供 Python 知识点数据 @app.route("/api/python-tips") def python_tips(): tips = { "message": "欢迎来到 Python 知识点", "tips": [ { "title": "变量和数据类型", "description": "Python 是一种动态类型语言,变量不需要显式声明类型。常见的数据类型有整数(int)、浮点数(float)、字符串(str)、列表(list)、字典(dict)等。", "example": "name = 'Kimi'\nage = 25\nis_student = True" }, { "title": "条件语句", "description": "使用 `if`、`elif` 和 `else` 来实现条件判断。", "example": "if age >= 18:\n print('成年人')\nelse:\n print('未成年人')" }, { "title": "循环语句", "description": "Python 提供 `for` 和 `while` 循环,用于重复执行代码块。", "example": "for i in range(5):\n print(i)\n\ni = 0\nwhile i < 5:\n print(i)\n i += 1" }, { "title": "函数定义", "description": "使用 `def` 关键字定义函数,可以有参数和返回值。", "example": "def greet(name):\n return f'Hello, {name}!'\n\nprint(greet('Kimi'))" }, { "title": "列表操作", "description": "列表是 Python 中常用的数据结构,支持添加、删除、排序等操作。", "example": "fruits = ['apple', 'banana', 'cherry']\nfruits.append('orange')\nprint(fruits)\nfruits.pop()\nprint(fruits)" }, { "title": "字典操作", "description": "字典是一种键值对的数据结构,通过键访问值。", "example": "person = {'name': 'Kimi', 'age': 25}\nprint(person['name'])\nperson['age'] = 26\nprint(person)" }, { "title": "异常处理", "description": "使用 `try` 和 `except` 来捕获和处理异常。", "example": "try:\n result = 10 / 0\nexcept ZeroDivisionError:\n print('除数不能为零')" }, { "title": "模块和包", "description": "Python 的模块是包含函数和变量的文件,包是模块的集合。使用 `import` 导入模块。", "example": "import math\nprint(math.sqrt(16))" }, { "title": "文件操作", "description": "使用 `open()` 函数打开文件,支持读写操作。", "example": "with open('example.txt', 'w') as file:\n file.write('Hello, world!')\n\nwith open('example.txt', 'r') as file:\n content = file.read()\n print(content)" } ] } return jsonify(tips) if __name__ == "__main__": app.run(debug=True,host="0.0.0.0", port=80)