摘要
这篇博客详细介绍了如何使用Flask框架搭建第一个简单的’hello world’应用,包括环境配置、基本代码编写和运行测试,适合Python Web开发新手入门学习。
提示词
采用大模型:通义千问(代码模式)
实现一个"hello world"的Flask项目,包括直接输出、使用模板渲染和处理网页参数三个子功能。
输出
为了实现一个包含直接输出、使用模板渲染和处理网页参数的Flask项目,我们需要创建以下几个文件:
app.py- 主程序文件templates/index.html- 模板文件
下面是完整的代码实现。
目录结构
flask_project/
│
├── app.py
└── templates/
└── index.html
创建主程序文件 app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello_direct():
return 'Hello, World!'
@app.route('/template')
def hello_template():
return render_template('index.html')
@app.route('/greet', methods=['GET'])
def greet():
name = request.args.get('name', 'World')
return f'Hello, {name}!'
if __name__ == '__main__':
app.run(debug=True)
创建模板文件 templates/index.html
在项目的根目录下创建一个名为 templates 的文件夹,并在其中创建 index.html 文件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hello Template</title>
</head>
<body>
<h1>Hello from a template!</h1>
</body>
</html>
运行项目
确保你已经安装了Flask。如果没有安装,可以使用以下命令进行安装:
pip install flask
然后,在终端中导航到项目目录并运行以下命令启动Flask应用:
python app.py
访问以下URL查看不同功能的效果:
- 直接输出:http://127.0.0.1:5000/
- 使用模板渲染:http://127.0.0.1:5000/template
- 处理网页参数(例如,传入名字为Alice):http://127.0.0.1:5000/greet?name=Alice
这样就完成了包含直接输出、使用模板渲染和处理网页参数的Flask项目。
用自然语言唤醒AI的创造力!无需复杂代码,释放你的想象力,让AI成为你的编程搭档。探索大模型提示词技术,快速实现创意,开启智能开发之旅!点击查看更多AI提示词编程案例!

1929

被折叠的 条评论
为什么被折叠?



