Flask
文章导读:本文主要是利用socket来编写一个简单的服务器,通过在网页地址栏输入的请求来调用与之对应的函数来解析对应的网页文档。
# 主函数
def main():
"""
主函数
:return:
"""
# 配置信息
config = dict(
host='',
port=3000,
)
run(**config)
主函数, 在这里进行主机host和端口port的设定,如果将来要改对应的端口或主机名只需在这里改动即可。
# 启动服务器
def run(host='', port=3000):
"""
启动服务器
:param host:
:param port:
:return:
"""
with socket.socket() as s:
# 端口绑定
s.bind((host, port))
while True:
# 监听请求
s.listen(5)
connection, address = s.accept()
# 这里为了简单,我只接受1024字节的信息,
# 接收到的信息类型为byte类型
request = connection.recv(1024)
request = request.decode('utf-8')
log('ip: {}\nrequest: {}'.format(address[0], request))
try:
# GET / HTTP/1.1 GET后有个空格
path = request.split()[1]
log('path: ', path)
response = response_by_socket(path)
connection.sendall(response)
except Exception as e:
log('error: ', e)
finally:
connection.close()
# 根据对应path调用相应函数
def response_by_socket(path):
"""
根据路径调用相应的函数
:param path:
:return response:
"""
r = {
'/': route_index,
'/doge.gif': route_image,
'/msg': route_msg,
}
# 根据相应的path调用相应的函数
response = r.get(path, error)
return response()
response = r.get(path, error)
这句的意思是如果能够字典r中找到对应的path,则返回path所对应的函数,否则返回error函数。
整体代码如下:
import socket
# 读取html
def page(name):
"""
读取html
:param name:
:return:
"""
with open(name, encoding='utf-8') as f:
return f.read()
# 对print函数进行封装
def log(*args, **kwargs):
"""
对print函数进行封装
:param args:
:param kwargs:
:return:
"""
print('log: ', args, kwargs)
# 主页
def route_index():
"""
主页显示
:return r:
"""
header = 'HTTP/1.1 GET 200 OK\r\nContent-Type=text/html\r\n'
body = '<h1>Hello Kevin</h1><img src="/doge.gif">'
r = header + '\r\n' + body
return r.encode(encoding='utf-8')
# 图片
def route_image():
"""
图片
:return img:
"""
with open('/home/kevin/programe/python/flask_xiao/day2/doge.gif', 'rb') as f:
# 因为图片的存储是一二进制的形式,所以这里的类型为byte
header = b'HTTP/1.1 GET 200 OK\r\nContent-Type=image/gif\r\n'
img = header + b'\r\n' + f.read()
return img
# 信息
def route_msg():
"""
读取一个html格式的文档
:return:
"""
header = 'HTTP/1.1 GET 200 OK\r\nContent-Type=text/html\r\n'
body = page('/home/kevin/programe/python/flask_xiao/day2/index.html')
r = header + '\r\n' + body
return r.encode(encoding='utf-8')
# 错误页面显示
def error(code=404):
"""
错误页面显示
:param code:
:return e:
"""
e = {
404: 'HTTP/1.1 GET 404 NOT FOUND\r\n\r\n<h1>Not Found...</h1>',
}
return e.get(code, b'')
# 根据对应path调用相应函数
def response_by_socket(path):
"""
根据路径调用相应的函数
:param path:
:return response:
"""
r = {
'/': route_index,
'/doge.gif': route_image,
'/msg': route_msg,
}
# 根据相应的path调用相应的函数
response = r.get(path, error)
return response()
# 启动服务器
def run(host='', port=3000):
"""
启动服务器
:param host:
:param port:
:return:
"""
with socket.socket() as s:
# 端口绑定
s.bind((host, port))
while True:
# 监听请求
s.listen(5)
connection, address = s.accept()
# 这里为了简单,我只接受1024字节的信息,
# 接收到的信息类型为byte类型
request = connection.recv(1024)
request = request.decode('utf-8')
log('ip: {}\nrequest: {}'.format(address[0], request))
try:
# GET / HTTP/1.1 GET后有个空格
path = request.split()[1]
log('path: ', path)
response = response_by_socket(path)
connection.sendall(response)
except Exception as e:
log('error: ', e)
finally:
connection.close()
# 主函数
def main():
"""
主函数
:return:
"""
# 配置信息
config = dict(
host='',
port=3000,
)
run(**config)
if __name__ == '__main__':
main()
这是我写的一个简单的html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welocome</title>
</head>
<body>
<div class="center">
<h2>Hello Kevin</h2>
<form name="form1">
<input type="text" name="text" placeholder="User name"><br>
<input type="password" name="password" placeholder="Password"><br>
<input type="submit" value="Submit">
</form>
<form name="form2">
<input type="text" name="text" placeholder="">
</form>
</div>
</body>
</html>
运行效果: