使用 Python 的 flask 架构搭建一个简单web网站
1.flask最简单框架,返回hello world:
from flask import *
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__=="__main__":
app.run(host='0.0.0.0',port=8080) # 0.0.0.0地址可给本机所有的IP地址访问
- 我们可以在app路由处的hello_world函数修改返回的‘hello world!’来改变返回的信息,再者我们在最后一行的代码0.0.0.0的作用是可以允许其他连接本机IP地址都可以来访问到服务,如可以在浏览器输入地址:127.0.0.1:8080即可访问。
2.让flask可以给浏览器返回一个简单的网页,即添加视图函数,让网页变得丰富点:
- 在同一工程文件目录下创建一个templates的文件夹,在该目录下创建一个 html 文件,同时命名为index.html。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wow</title>
</head>
<body>
<h1>我超级帅喔!</h1>
</body>
</html>
- 这时候我们需要在后端 flask 框架中的路由分发中添加这个 html 文件的分发规则与任务,使得浏览器可以通过一定得地址可以访问到该网页。
- 我们把步骤一的 flask 后端的增添一个路由分发任务,更新为如下:
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/index')
def index():
return render_template('index.html') #会自动找templates文件夹里面的index.html,并不需要一个绝对路径。
if __name__=="__main__":
app.run(host='0.0.0.0',port=8080) # 0.0.0.0地址可给本机所有的IP地址访问
3.同理我们可以让 flask 添加更加多我们需要的web网页:
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/index')
def index():
return render_template('index.html') #会自动找templates文件夹里面的index.html,并不需要一个绝对路径。
@app.route('/login')
def index():
return render_template('login.html')
@app.route('/content')
def index():
return render_template('content.html')
if __name__=="__main__":
app.run(host='0.0.0.0',port=8080)
- 2.前端新增,在 templates 目录下添加 login.html、content.html 两个html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/login_finsh" method="POST">
用户名 <input type="text" name="username" id="">
密码 <input type="text" name="password" id="">
<input type="submit" value="登录">
</br>
<input type="button" value="open1">
</br>
<button type="button" onclick="open_function()"> open1</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>这是内容页!</p>
</body>
</html>
- 3.只有我们在浏览器地址栏打上对应的地址即可以浏览到这些网页。