socket搭建web服务端
import socket
from threading import Thread
import time def html(conn):
time_tag = str(time.time())
print(time_tag)
with open('test1.html', 'r', encoding='utf-8') as f:
content = f.read()
content = content.replace('#zzxx#', time_tag)
content = content.encode('utf-8')
conn.send(content)
conn.close()
def css(conn):
with open('test.css', 'rb') as f:
content = f.read()
conn.send(content)
conn.close()
def js(conn):
with open('test.js', 'rb') as f:
content = f.read()
conn.send(content)
conn.close()
def jpg(conn):
with open('934905.jpg', 'rb') as f:
content = f.read()
conn.send(content)
conn.close()
def icon(conn):
with open('bilibili.ico', 'rb') as f:
content = f.read()
conn.send(content)
conn.close()
sk = socket.socket()
sk.bind(("127.0.0.1", 8080))
sk.listen() urlpath = [
('/', html),
('/test.css', css),
('/test.js', js),
('/934905.jpg', jpg),
('/bilibili.ico', icon),
] while True:
conn, addr = sk.accept()
msg = conn.recv(1024)
# print(msg.decode("utf-8"))
request_str = msg.decode("utf-8")
path = request_str.split('\r\n')[0].split(' ')[1]
print(path)
conn.send(b"HTTP/1.1 200 ok\r\n\r\n")
# conn.send(b"hello")
for i in urlpath:
if path == i[0]:
# i[1](conn)
t = Thread(target=i[1], args=(conn, ))
t.start()
wsgiref Web框架
from wsgiref.simple_server import make_server
import time
from showdata import showdata
from jinja2 import Template def html():
# time_tag = str(time.time())
# print(time_tag)
user_info = showdata()
# with open('test1.html', 'r', encoding='utf-8') as f:
with open('jinja2test.html', 'r', encoding='utf-8') as f:
content = f.read() tem = Template(content)
content = tem.render({"userinfo": user_info}) content = content.replace('#zzxx#', user_info['name'])
content = content.encode('utf-8')
return content
def css():
with open('test.css', 'rb') as f:
content = f.read()
return content
def js():
with open('test.js', 'rb') as f:
content = f.read()
return content
def jpg():
with open('934905.jpg', 'rb') as f:
content = f.read()
return content
def icon():
with open('bilibili.ico', 'rb') as f:
content = f.read()
return content
urlpath = [
('/', html),
('/test.css', css),
('/test.js', js),
('/934905.jpg', jpg),
('/bilibili.ico', icon),
]
def application(environ, start_response):
print(environ)
start_response('200 OK', [('k1', 'v1'), ('k2', 'v2')]) path = environ['PATH_INFO']
for i in urlpath:
if path == i[0]:
ret = i[1]()
break
else:
ret = b'404' # return [b'<h1>Hello World!<h1>']
return [ret] httpd = make_server('127.0.0.1', 8080, application)
print('Seeving HTTP on port 8080')
httpd.serve_forever()
showdata文件
import pymysql
def showdata():
conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123456',
database='web_test',
charset='utf8'
) cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = 'select * from userinfo;'
cursor.execute(sql)
data = cursor.fetchone()
print(data)
conn.commit()
cursor.close()
conn.close()
return data
下面是将服务打包起来,更易于管理

manage.py
"""
写服务器逻辑
"""
from wsgiref.simple_server import make_server
from urls import urlpath def application(environ, start_response):
# print(environ)
start_response('200 OK', [('k1', 'v1'), ('k2', 'v2')]) path = environ['PATH_INFO']
print(path)
for i in urlpath:
if path == i[0]:
ret = i[1]()
break
else:
ret = b'404' # return [b'<h1>Hello World!<h1>']
return [ret] httpd = make_server('127.0.0.1', 8080, application)
# print('Seeving HTTP on port 8080')
httpd.serve_forever()
views.py
"""
写业务逻辑
""" from showdata import showdata
from jinja2 import Template def html():
# time_tag = str(time.time())
# print(time_tag)
user_info = showdata()
# with open('test1.html', 'r', encoding='utf-8') as f:
with open('templates/jinja2test.html', 'r', encoding='utf-8') as f:
content = f.read() tem = Template(content)
content = tem.render({"userinfo": user_info})
print("主页") content = content.replace('#zzxx#', user_info['name'])
content = content.encode('utf-8')
return content
def css():
with open('static/css/test.css', 'rb') as f:
content = f.read()
print("css文件")
return content
def js():
with open('static/js/test.js', 'rb') as f:
content = f.read()
return content
def jpg():
with open('static/img/934905.jpg', 'rb') as f:
content = f.read()
return content
def icon():
with open('static/img/bilibili.ico', 'rb') as f:
content = f.read()
return content
urls.py
"""
路由逻辑
"""
import views urlpath = [
('/', views.html),
('/static/css/test.css', views.css),
('/static/js/test.js', views.js),
('/static/img/934905.jpg', views.jpg),
('/static/img/bilibili.ico', views.icon)
]
models.py
import pymysql conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='123456',
database='web_test',
charset='utf8'
) cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = 'create table userinfo(id int primary key auto_increment,name char(10), age int' \
' not null);'
cursor.execute(sql) conn.commit()
cursor.close()
conn.close()
socket搭建web服务端的更多相关文章
- OpenResty搭建高性能服务端
OpenResty搭建高性能服务端 Socket编程 Linux Socket编程领域为了处理大量连接请求场景,需要使用非阻塞I/O和复用,select.poll.epoll是Linux API提 ...
- So easy Webservice 1.Socket建设web服务
socket 是用来进行网络通讯的,简单来说,远程机器和本地机器各建一个socket,然后通过该socket进行连接通讯 socket简单模型图: socket的原理图: 代码实现: 1.创建sock ...
- 《用OpenResty搭建高性能服务端》笔记
概要 <用OpenResty搭建高性能服务端>是OpenResty系列课程中的入门课程,主讲人:温铭老师.课程分为10个章节,侧重于OpenResty的基本概念和主要特点的介绍,包括它的指 ...
- wsgiref手写一个web服务端
''' 通过wsgiref写一个web服务端先讲讲wsgiref吧,基于网络通信其根本就是基于socket,所以wsgiref同样也是通过对socket进行封装,避免写过多的代码,将一系列的操作封装成 ...
- 基于Socket创建Web服务
基于Socket创建Web服务 为什么要使用Socket呢,我们来看下图
- 快速搭建Kerberos服务端及入门使用
快速搭建Kerberos服务端及入门使用 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Kerberos是一种网络身份验证协议.它旨在通过使用秘密密钥加密为客户端/服务器应用程序提 ...
- 4、架构--NFS实践、搭建web服务、文件共享
笔记 1.晨考 1.数据备份的方式有哪些 全量和增量 2.数据备份的命令有哪些,都有哪些优点缺点 cp : 本地,全量复制 scp :远程,全量复制 rsync :远程,增量复制 3.rsync的参数 ...
- 关于如何提高Web服务端并发效率的异步编程技术
最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...
- winform客户端利用webClient实现与Web服务端的数据传输
由于项目需要,最近研究了下WebClient的数据传输.关于WebClient介绍网上有很多详细介绍,大概就是利用WebClient可以实现对Internet资源的访问.无外乎客户端发送请求,服务端处 ...
- 如何提高Web服务端并发效率的异步编程技术
作为一名web工程师都希望自己做的web应用能被越来越多的人使用,如果我们所做的web应用随着用户的增多而宕机了,那么越来越多的人就会变得越来越少了,为了让我们的web应用能有更多人使用,我们就得提升 ...
随机推荐
- springboot项目启动报错:找不到或无法加载主类 com....
springboot项目报错 找不到或无法加载主类 com.... 1.如果是导入的别人的项目 首先要配置好JDK 和 MAVEN 然后点击右侧栏的maven图标 --->点击clean(清除掉 ...
- NOIP2008普及组
T2]排座椅 横行相同时列数+1,纵行相同时行数+1. 主要是用桶排序,因为范围太大了,用sort会超时 #include<iostream> #include<cstring> ...
- 用bat文件,自动进入cmd虚拟环境
L:cd L:\myenv\Scriptscmd /K activate.bat 这行,这样写,cmd窗口会继续保留,按任意键也不会关闭. 这个问题网上大部分说法是在批处理里面加上 cmd /k, ...
- Angular Material TreeTable Component 使用教程
一. 安装 npm i ng-material-treetable --save npm i @angular/material @angular/cdk @angular/animations -- ...
- 1.3Dmax界面_试图操作
一.初始界面 1.菜单栏(软件的核心) 2.工具栏 3.石墨工具 4.命令板块 5.场景大纲 tools--> new Scene Explorer 创建的物体信息就会从出现在这里 6.视图窗口 ...
- PyTorch中的矩阵乘法
1. 二维矩阵乘法 , 其中 , , 输出 的维度是.该函数一般只用来计算两个二维矩阵的矩阵乘法,而且不支持broadcast操作. 2. 三维带Batch矩阵乘法 由于神经网络训练一般采用mi ...
- zookeeper异常
1. KeeperErrorCode = Unimplemented for /service 在使用curator时,对zk有版本匹配关系. Curator 2.** <---> ...
- DVWA-Weak Session IDs(弱会话ID) 不安全的会话
在登录服务器之后,服务器会返回给用户一个会话(session),这个会话只会存在一段时间,拥有这个会话下次登录就不用输入密码就可以登录到网站,如果返回的这个会话很弱,容易被猜解到,就很不安全,照成会话 ...
- 学习ASP.NET Core Blazor编程系列二十八——JWT登录(3)
学习ASP.NET Core Blazor编程系列文章之目录 学习ASP.NET Core Blazor编程系列一--综述 学习ASP.NET Core Blazor编程系列二--第一个Blazor应 ...
- 论文解读(ToAlign)《ToAlign: Task-oriented Alignment for Unsupervised Domain Adaptation》
论文信息 论文标题:ToAlign: Task-oriented Alignment for Unsupervised Domain Adaptation论文作者:Guoqiang Wei, Cuil ...