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服务端的更多相关文章

  1. OpenResty搭建高性能服务端

    OpenResty搭建高性能服务端   Socket编程 Linux Socket编程领域为了处理大量连接请求场景,需要使用非阻塞I/O和复用,select.poll.epoll是Linux API提 ...

  2. So easy Webservice 1.Socket建设web服务

    socket 是用来进行网络通讯的,简单来说,远程机器和本地机器各建一个socket,然后通过该socket进行连接通讯 socket简单模型图: socket的原理图: 代码实现: 1.创建sock ...

  3. 《用OpenResty搭建高性能服务端》笔记

    概要 <用OpenResty搭建高性能服务端>是OpenResty系列课程中的入门课程,主讲人:温铭老师.课程分为10个章节,侧重于OpenResty的基本概念和主要特点的介绍,包括它的指 ...

  4. wsgiref手写一个web服务端

    ''' 通过wsgiref写一个web服务端先讲讲wsgiref吧,基于网络通信其根本就是基于socket,所以wsgiref同样也是通过对socket进行封装,避免写过多的代码,将一系列的操作封装成 ...

  5. 基于Socket创建Web服务

    基于Socket创建Web服务 为什么要使用Socket呢,我们来看下图

  6. 快速搭建Kerberos服务端及入门使用

    快速搭建Kerberos服务端及入门使用 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Kerberos是一种网络身份验证协议.它旨在通过使用秘密密钥加密为客户端/服务器应用程序提 ...

  7. 4、架构--NFS实践、搭建web服务、文件共享

    笔记 1.晨考 1.数据备份的方式有哪些 全量和增量 2.数据备份的命令有哪些,都有哪些优点缺点 cp : 本地,全量复制 scp :远程,全量复制 rsync :远程,增量复制 3.rsync的参数 ...

  8. 关于如何提高Web服务端并发效率的异步编程技术

    最近我研究技术的一个重点是java的多线程开发,在我早期学习java的时候,很多书上把java的多线程开发标榜为简单易用,这个简单易用是以C语言作为参照的,不过我也没有使用过C语言开发过多线程,我只知 ...

  9. winform客户端利用webClient实现与Web服务端的数据传输

    由于项目需要,最近研究了下WebClient的数据传输.关于WebClient介绍网上有很多详细介绍,大概就是利用WebClient可以实现对Internet资源的访问.无外乎客户端发送请求,服务端处 ...

  10. 如何提高Web服务端并发效率的异步编程技术

    作为一名web工程师都希望自己做的web应用能被越来越多的人使用,如果我们所做的web应用随着用户的增多而宕机了,那么越来越多的人就会变得越来越少了,为了让我们的web应用能有更多人使用,我们就得提升 ...

随机推荐

  1. HTML5第五章作业

    5.1.3 html 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" ...

  2. heimaJava17

    java IO流 缓冲流 概念 缓存流也称为高效流.或者高级流.之前学习的字节流也可以称为原始流 作用:缓冲流自带缓冲区.可以提高原始字节流.字符流读写数据的性能 分类 字节缓冲流 字节缓冲输入流:B ...

  3. js数组常用的方法

    var arr=['hello','前端','world']; 1. arr.join(分隔符):将数组中的值拼接成一个字符串,返回这个字符串,默认分隔符"," arr.join( ...

  4. 用反证法说明List<Object>和List<String>不存在子父类关系可行吗?

    看宋红康老师的Java基础视频讲解,视频中用反证法证明List

  5. linux/windows常见文件系统最大支持单个文件大小

    windows常见文件系统:FAT12/FAT16/FAT32/NTFS/NTFS5.0 对应支持大小:      8M/2G/4G/64G/2TB linux常见文件系统:ext2/ext3/ext ...

  6. System.IO.IOException:“找不到资源“views.buttonstylepage.xaml”。”

    初学作为记录(事发场景): WPFDemo的程序集中,定义了一个Views文件夹,该文件夹放一些页面Page.UI层面的东西.用Frame空间做导航的时候,始终报一个错误   //   System. ...

  7. QImageReader(Writer)支持格式变少的解决方法

    首发于我的个人博客:xie-kang.com 博客内有更多文章,欢迎大家访问 原文地址 获取程序支持的图片格式: #include "mainwindow.h" #include ...

  8. Docker下部署LNMP黄金架构

    一.部署lnmp 1.网络规划 172.16.10.0/24nginx:172.16.10.10mysql:172.16.10.20php:172.16.10.30网站访问主目录:/wwwrootng ...

  9. Android笔记--监听短信内容

    监听短信内容 就比如说是在我们用一个软件需要使用"获取验证码"的功能时,能够跟短信的验证码互通,实现较为完整的登录功能: 监听短信内容主要是利用了contentObserver实现 ...

  10. Gym - 101845E (图形转换思维)

    题意:给你个边长为n(1 <= n <= 50)的下图这种三角形,图形所有点构成集合.找多少对a,b满足条件,条件为:ab两点之间还有其他点. 题解:刚开始以为直接找规律就行,wa了两次发 ...