DJango 学习(3)—— django引入:动静态网页
动静态网页区别
静态网页
网页上的数据是直接写死的 万年不变
动态网页
数据是实时获取的
eg. 后端获取当前时间展示到前端html页面上
后端数据从数据库获取展示到 html 页面上
借助于 wsgiref 模块实现动态网页
文件夹目录
main.py
import urls
from views import *
from wsgiref.simple_server import make_server
def run(env, response):
"""
:param env: 请求相关的所有数据
:param response: 响应相关的所有数据
:return: 返回给浏览器的数据
"""
response("200 OK", [])
current_path = env.get("PATH_INFO")
func = None
for url in urls.urls:
if url[0] == current_path:
func = url[1]
break
if func:
res = func(env)
else:
res = error(env)
return [res.encode("utf-8")]
if __name__ == "__main__":
server = make_server("127.0.0.1", 8080, run)
server.serve_forever()
urls.py
from views import *
urls = [
("/index", index),
("/login", login),
("/time", get_time),
('/dic', get_dict)
]
views.py
def index(env):
return "index"
def login(env):
return "login"
def error(env):
return "404 error"
import time
def get_time(env):
now = time.localtime()
now_time = time.strftime("%Y-%m-%d %X", now)
with open(r"templates/01-get_time.html", "r", encoding="utf-8") as f:
data = f.read()
data = data.replace("time", now_time)
return data
from jinja2 import Template
def get_dict(env):
user_dic = {"username": "aoteman", "age": 18}
with open(r"templates/01-get_dict.html", "r", encoding="utf-8") as f:
data = f.read()
tep = Template(data)
res = tep.render(user=user_dic)
return res
01-get_time.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="JQuery3.6.0.js"></script>
<link rel="stylesheet" href="bootstrap-3.4.1-dist/css/bootstrap.min.css">
<script src="bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<h1>HTML</h1>
time
</body>
</html>
01-get_dict.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>我是一个页面</h1>
{{ user }}
{{ user.get("username") }}
{{ user.age }}
</body>
</html>
模板语法之 jinja 2 模块
{{ user }}
{{ user.get("username") }}
{{ user.age }}
{% for user_dic in user_list %}
<tr>
<td>{{ user_dic.id }}</td>
<td>{{ user_dic.name }}</td>
<td>{{ user_dic.sex }}</td>
<td>{{ user_dic.age }}</td>
</tr>
{% endfor %}
运行结果