Web框架的本质
包含以下知识点:
- socket
- http协议
- HTML知识
- 数据库(pymysql,SQLAlchemy)
1 网站访问的流程
博客园(socket服务端
1.监听IP和端口,默认80
3.收到用户请求
4.响应用户请求
浏览器(socket客户端)
2.用户访问博客园,即浏览器输入博客园地址www.cnblogs.com,进行DNS解析并与博客园服务器建立连接
5.接收博客园发送的响应信息
6.断开连接
HTTP请求是无状态的
2 Web框架本质
静态网站
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/13
import socket
sock = socket.socket()
sock.bind(('127.0.0.1', 8001))
sock.listen(5)
def index(request):
"""
处理用户请求,并返回响应内容
:param request:
:return:
"""
f = open('index.html', 'rb')
data = f.read()
f.close()
return data
def article(request):
f = open('article.html', 'rb')
data = f.read()
f.close()
return data
routes = [
('/index', index),
('/article', article),
]
def run():
while True:
conn, addr = sock.accept()
data = conn.recv(8096)
data = str(data, encoding='utf8')
headers,bodys = data.split('
')
temp_list = headers.split('
')
method,url,protocal = temp_list[0].split(' ')
func_name = None
for item in routes:
if item[0] == url:
func_name = item[1]
break
if func_name:
response = func_name(data)
else:
response = b'404'
if response == b'404':
conn.send(b'HTTP/1.1 404 NOT FOUND
')
else:
conn.send(b'HTTP/1.1 200 OK
')
conn.send(response)
conn.close()
if __name__ == "__main__":
run()
动态网站
#!/usr/bin/env python
# __Author__: "wanyongzhen"
# Date: 2017/5/13
import socket
import time
import pymysql
sock = socket.socket()
sock.bind(('127.0.0.1', 8001))
sock.listen(5)
def index(request):
"""
处理用户请求,并返回响应内容
:param request:
:return:
"""
f = open('index.html', 'rb')
data = f.read()
f.close()
return data
def article(request):
f = open('article.html', 'r', encoding='utf8')
data = f.read()
f.close()
ctime = time.time()
data = data.replace('@@sw@@', str(ctime))
data = bytes(data, encoding='utf8')
return data
def users(request):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='db02', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute('select id,name,email from users')
user_list = cursor.fetchall()
cursor.close()
conn.close()
print(user_list)
content_list = []
for row in user_list:
tp = '''<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
</tr>'''%(row['id'], row['name'], row['email'])
content_list.append(tp)
content=''.join(content_list)
f = open('users.html', 'r', encoding='utf8')
template = f.read()
f.close()
template = template.replace('@content@', content)
template = bytes(template,encoding='utf8')
return template
routes = [
('/index', index),
('/article', article),
('/users', users)
]
def run():
while True:
conn, addr = sock.accept()
data = conn.recv(8096)
data = str(data, encoding='utf8')
headers,bodys = data.split('
')
temp_list = headers.split('
')
method,url,protocal = temp_list[0].split(' ')
func_name = None
for item in routes:
if item[0] == url:
func_name = item[1]
break
if func_name:
response = func_name(data)
else:
response = b'404'
if response == b'404':
conn.send(b'HTTP/1.1 404 NOT FOUND
')
else:
conn.send(b'HTTP/1.1 200 OK
')
conn.send(response)
conn.close()
if __name__ == "__main__":
run()
总结:
1. HTTP协议,无状态、短连接
2.浏览器(socket客户端)
3.自己写网站
- a socket服务端
- b 根据URL不同返回不同的内容
- 路由系统 URL -> 函数
- c 字符串返回给用户
- 模板引擎的渲染
- HTML充当模板(包含特殊字符)
- 自己创造任意数据
4.Web框架
框架种类:
- a b c Tornado
- b c Django(通过wsgiref完成a功能)
- b flask
另外一种分类:
- Django
- 其他
2 Django框架
安装Django框架
pip3 install django
命令创建并启动
创建Django项目
django-admin startproject mysite
目录结构
mysite
|____manage.py # 对当前Django程序所有操作可以基于 python manage.py runserver
|____mysite
| |______init__.py
| |____settings.py # Django的配置文件
| |____urls.py # 路由系统:url -> 函数
| |____wsgi.py # 用于定义Django用什么实现socket服务端(wsgiref)
启动Django项目
cd mysite
python manage.py runserver 127.0.0.1:8080
PS: pycharm也可以轻松创建
第一个Django请求
mysite/mysite/urls.py 文件
from django.conf.urls import url
from django.contrib import admin
from django.shortcuts import HttpResponse
def login(request):
"""
处理用户请求,并返回内容
:param request: 用户请求相关的所有信息(对象)
:return:
"""
return HttpResponse('login')
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^login/', login),
]
Django程序创建步骤
1.创建Project
2.配置
- 模板路径(默认即可)
- 配置静态文件路径
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
3.额外配置 注释该行
# 'django.middleware.csrf.CsrfViewMiddleware',