Django WEB框架
1 基本WEB框架
import socket
server = socket.socket()
ip_port = ('127.0.0.1',8000)
server.bind(ip_port)
server.listen()
while True:
conn,addr = server.accept()
recv_msg = conn.recv(1024)
print(recv_msg)
conn.send(b'My First WEB Server')
conn.close()
在浏览器的URL输入框中输入:http://127.0.0.1:8000/
,浏览器返回My First WEB Server
。
服务器端窗口输出:
GET / HTTP/1.1
Host: 127.0.0.1:8000
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4385.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
2 WSGI
如何才能让服务器能够执行动态的内容?一般会分为两部分:服务器程序和应用程序。
-
应用程序则负责具体的逻辑处理。一般是通过
Python
或者PHP
来处理,之后再把处理完的结果在提交到HTTP 服务器程序
。 -
HTTP服务器程序负责对socket服务器进行封装:将 HTTP 请求响应给客户端。
WSGI(Web Server Gateway Interface)
就是一种规范,它定义了使用 Python
编写的 web 应用程序
与 web服务器程序
之间的接口格式,实现 web 应用程序
与 web服务器程序
间的解耦。wsgi
类似是 Python
到 HTTP
的一条通道。类似还有 CGI、FastCGI
等。Apache、Nginx
等 HTTP服务器软件都是只负责处理 HTTP 的请求和响应,然后 Python、PHP
再通过类似 wsgi
这样的接口与之融合。
Python标准库
提供的独立WSGI服务器叫 wsgiref
,Django开发环境用的就是这个模块来做服务器。
2.1 HTML文档模板
此模板试用于第二章所有实例。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Title</title>
</head>
<body>
<h1>header1</h1>
<p>this is paragraph.</p>
<h1>{
{ userinfo }}</h1>
<ul>
{% for k,v in userinfo.items() %}
<li>{
{ k }}--{
{ v }}</li>
{% endfor %}
</ul>
</body>
</html>
2.2 WSGI-基本配置
from wsgiref.simple_server import make_server
def application(environ, start_response):
"""
application 由wsgi服务器调用、函数对http请求与响应的封装
:param environ: 返回浏览器http请求信息 (dist)
:param start_response: WEB服务器响应客户端 (function)
传给HTTP服务器程序时,格式应为byte类型,并加上"[]"
:return:
"""
print(environ)
# 响应浏览器请求
start_response('200 ok', [('Content-Type', 'text/html'), ('k1', 'v1'), ('k2', 'v2')]