模板

前言

要说到应用程序,就不得不提的就是cs架构和BS架构

所谓的cs架构就是client端和server端,就像我们的电脑上的qq,微信等应用程序

bs架构就是浏览器端和server端,我们不需要写客户端了,直接用浏览器接收来自server端的数据,进行解析

手写简易的server端

import socket
soc=socket.socket() #实例化socket
soc.bind(('127.0.0.1',8001)) #绑定ip地址和端口
soc.listen(5)#监听

while True:
sock,addr=soc.accept()#等待客户端连接
sock.send(b'HTTP/1.1 200 OK\r\nContent-Type:Text/html\r\n\r\n')#发送请求头和请求报文

data=str(sock.recv(1024),encoding='utf-8')#将请求过来的数据解析成字符串
print(data)
data=data.split('\r\n')[0].split(' ')#将请求中的第一行提取出来
if '/index' in data:
with open('index.html','rb') as f:
ff=f.read()

print(ff)
sock.send(ff)#响应请求内容
else:
sock.send(b'')
sock.close()

使用wsgiref手撸web框架

web框架运行文件wsgirefserver.py

# 这是一个web框架的测试模板wsgiref
from wsgiref.simple_server import make_server

from urlss import *


def run(env, response):
print(env)
print(response)
response('200 OK', [('Content-type', 'text/html')]) # 请求报文
position = env['PATH_INFO'] # 拿到请求体中的路由
func = None
for url in urls:
if url[0] == position:
func = url[1]
break
if func:
response = func()
else:
response = error()

return [response.encode('utf-8'), ]


if __name__ == '__main__':
ser = make_server('127.0.0.1', 8001, run)
ser.serve_forever()

视图views.py

#!/user/bin/env python3
# -*- coding: utf-8 -*-
import time
import datetime
from jinja2 import Template
import sys
import pymysql


def index():
with open('templates/index.html', 'r') as f:
data = f.read()
return data


def test():
with open('templates/test.html', 'r') as f:
data = f.read()
tem = Template(data)
response = tem.render(user={'name': 'andy', 'age': 18})

return response


def timer():
ctime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print(ctime)
with open('templates/time.html', 'r') as f:
data = f.read()
data = data.replace('@@time@@', ctime)
return data


def error():
return ''


def user():
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='admin', db='web')
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute('select * from userinfo')
user_list = cur.fetchall()
print(user_list)

with open('templates/user.html', 'r') as f:
data = f.read()
tem = Template(data)
response = tem.render(user_list=user_list)
return response


if __name__ == '__main__':
user()

路由urlss.py

#!/user/bin/env python3
# -*- coding: utf-8 -*-
from views import *
urls = [
('/index', index),
('/timer', timer),
('/test', test),
('/user', user),

]

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>index</h3>
<h2 style="color: red;">this is red wrod</h2>
<img src="http://106.14.187.174/static/blog/img/rest_framework.jpg" alt="">
</body>
</html>

templates/test.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>{{user.name}}
{{user.age}}</h1>

</body>
</html>

templates/time.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
@@time@@
</body>
</html>

templates/user.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<h1>hello</h1>
<h2>andy table</h2>
<table border="2">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>password</th>
</tr>
</thead>
<tbody>
{% for user in user_list %}
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.password}}</td>
</tr>
{%endfor%}
</tbody>
</table>
</body>
</html>

使用wsgiref手撸web框架的更多相关文章

  1. 纯手撸web框架

    纯手撸web框架 一.Web应用的组成 接下来我们学习的目的是为了开发一个Web应用程序,而Web应用程序是基于B/S架构的,其中B指的是浏览器,负责向S端发送请求信息,而S端会根据接收到的请求信息返 ...

  2. wsgiref模块、web框架、django框架简介

    """web框架:将前端.数据库整合到一起的基于互联网传输的python代码 web框架也可以简单的理解为是软件开发架构里面的'服务端'""" ...

  3. 手撸Spring框架,设计与实现资源加载器,从Spring.xml解析和注册Bean对象

    作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 你写的代码,能接的住产品加需求吗? 接,是能接的,接几次也行,哪怕就一个类一片的 i ...

  4. 写一个Python 1、通过select实现的最简单的web框架2、通过wsgiref实现的web框架

    #!/usr/bin/env python # -*- coding: utf- -*- import socket import select class MyRequest: "&quo ...

  5. 手写web框架之加载Controller,初始化框架

    1,加载Controller     我们需要创建 一个ControllerHelper类,让它来处理下面的逻辑:      通过ClassHelper我们可以获取所有定义了Controller注解的 ...

  6. 手写web框架之实现依赖注入功能

    我们在Controller中定义了Service成员变量,然后在Controller的Action方法中调用Service成员变量的方法,那么如果实现Service的成员变量? 之前定义了@Injec ...

  7. 手写web框架之实现Bean容器

    实现Bean容器    使用ClassHelper可以获取所加载的类,但无法通过类来实例化对象,因此我们需要提供一个反射工具类,让它封装java反射相关的API,对外提供更好用的工具方法.将该类命名为 ...

  8. 手写web框架之加载配置项目

    一  定义框架配置项 在项目的src/main/resources目录下创建一个名为smart.propertiesd的文件,文件的内容如下: smart.framework.jdbc.driver= ...

  9. web框架的本质(使用socket实现的最基础的web框架、使用wsgiref实现的web框架)

    import socket def handle_request(client): data = client.recv(1024) client.send("HTTP/1.1 200 OK ...

随机推荐

  1. 简单的试了试async和await处理异步的方式

    今天无意中就来试了试,感觉这个新的方法还是非常行的通的,接下来我们上代码 这段代码想都不用想输出顺序肯定是//null null 233,当然出现这个问题还是因为它是同步,接下来我们就进行异步方式来处 ...

  2. 02-flink时间语义 与 Window 基础概念与实现原理

    Flink 多种时间语义对比 Flink 在流应用程序中支持不同的 Time 概念,就比如有 Processing Time.Event Time 和 Ingestion Time.下面我们一起来看看 ...

  3. MongoDB3.6版本新增特性

    MongoDB3.6版新特性如下: (1)Default Bind to Localhost 从3.6版本开始,在默认情况下,MongoDB二进制文件mongod和mongos绑定到localhost ...

  4. Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set…

    php打印小票错误提示:Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activate ...

  5. Spring cloud微服务安全实战 最新完整教程

    课程资料获取链接:点击这里 采用流行的微服务架构开发,应用程序访问安全将会面临更多更复杂的挑战,尤其是开发者最关心的三大问题:认证授权.可用性.可视化.本课程从简单的API安全入手,过渡到复杂的微服务 ...

  6. 令人抓狂的redis和rediscluster Python驱动包的安装

    本文环境:centos 7,Python3编译安装成功,包括pip3,然后需要安装redis相关的Python3驱动包,本的redis指redis包而非redis数据库,rediscluster类似. ...

  7. 各大原厂看好MRAM发展

    MRAM是一种以电阻为存储方式结合非易失性及随机访问两种特性,可以兼做内存和硬盘的新型存储介质.写入速度可达NAND闪存的数千倍,此外,其制作工艺要求低,良品率高,可以很好的控制成本.在寿命方面,由于 ...

  8. echarts 【图表的基本使用】

    一.柱状图 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <tit ...

  9. java开发相关工具安装包分享

    链接:https://pan.baidu.com/s/19rSlXhrZ9AtNdai64tErGQ 提取码:04up

  10. 剑指offer-面试题13-机器人的运动范围-递归法

    /* 题目: 地上有一个m行n列的方格.一个机器人从坐标(0,0)的格子开始运动, 每次可向上.下.左.右移动一格,但不能进入行坐标和列坐标之和大于k的格子. 如,当k=18时,机器人能进入(35,3 ...