通过socket入门html

代码实现:

socket 1

import socket
import re
from threading import Thread

server = socket.socket()
server.bind(('127.0.0.1',8899))
server.listen()

while 1:
    conn,addr = server.accept()

    def home(conn):
        with open('test.html','rb') as f:
            data = f.read()
        conn.send(data)
        conn.close()

    def nofount(conn):
        conn.send(b'not found 404')
        conn.close()

    urlpatterns = [
        ('/',home),
    ]

    b_msg = conn.recv(1024)
    path = b_msg.decode('utf-8').split(' ')[1]
    print(path)
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')

    for url in urlpatterns:
        if path == url[0]:
            t = Thread(target=url[1],args=(conn,))
            t.start()
            break

    else:
        t = Thread(target=nofount, args=(conn,))
        t.start()

socket 2

import socket
from threading import Thread

sk = socket.socket()
sk.bind(('127.0.0.1',8001))
sk.listen()
def func1(conn):
    conn.send(b'HTTP/1.1 200 ok\r\ncontent-type:text/html\r\ncharset:utf-8\r\n\r\n')
    with open('test.html','rb') as f:
        data = f.read()
    conn.send(data)
    conn.close()

def func2(conn):
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    with open('sdf','rb') as f:
        pic_data = f.read()
    conn.send(pic_data)
    conn.close()

def func3(conn):
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    with open('test.css','rb') as f:
        css_data = f.read()
    conn.send(css_data)
    conn.close()

def func5(conn):
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    with open('test.js', 'rb') as f:
        js_data = f.read()
    conn.send(js_data)
    conn.close()

def func4(conn):
    conn.send(b'HTTP/1.1 200 ok\r\n\r\n')
    with open('wechat.ico', 'rb') as f:
        ico_data = f.read()
    conn.send(ico_data)
    conn.close()

l1 = [
    ('/', func1),
    ('/meinv.png',func2),
    ('/test.css',func3),
    ('/wechat.ico',func4),
    ('/test.js',func5),
]

def fun(path, conn):
    for i in l1:
        if i[0] == path:
            t = Thread(target=i[1], args=(conn,))
            t.start()

while 1:
    conn, addr = sk.accept()
    b_msg = conn.recv(1024)
    str_msg = b_msg.decode('utf-8')
    path = str_msg.split('\r\n')[0].split(' ')[1]
    print(path)

    fun(path, conn)

socket 3

import socket
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()

def index(url):
    with open("test.html","r",encoding='utf8') as f:
        s = f.read()
    return bytes(s,encoding='utf8')

def home(url):
    with open('./html/form.html','r',encoding='utf8') as f:
        s = f.read()
    return bytes(s, encoding="utf8")

list1 = [
    ("/index/", index),
    ("/home/", home),
]

while 1:
    conn, add = sk.accept()
    data = conn.recv(8096)
    data = str(data, encoding="utf8")
    data1 = data.split('\r\n')[0]
    url = data1.split()[1]
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    func = None
    for i in list1:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b'404 not found'

    conn.send(response)
    conn.close()

socket 4

import socket
import time

sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listen()

def index(url):
    with open('test.html','r',encoding='utf8') as f:
        s = f.read()
        now = str(time.time())
        s = s.replace("{{x}}",now)
    return bytes(s, encoding='utf8')

def home(url):
    with open("./html/test.html",'r',encoding='utf8') as f:
        s = f.read()
    return bytes(s, encoding='utf8')

list1 = [
    ("/index/",index),
    ("/home/", home),
]

while 1:
    conn, add = sk.accept()
    data = conn.recv(8096)

    data = str(data, encoding='utf8')
    data1 = data.split("\r\n")[0]
    url = data1.split(' ')[1]
    conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
    func = None
    for i in list1:
        if i[0] == url:
            func = i[1]
            break
    if func:
        response = func(url)
    else:
        response = b'404 not found!'

    conn.send(response)
    conn.close()

通过wsgiref实现网络访问

from wsgiref.simple_server import make_server

def application(environ, start_response):
    """

    :param environ:
    :param start_response:
    :return:
    """
    start_response('200 OK', [('Content-Type', 'text/html'),('k1','v1')])
    print(environ['PATH_INFO'])
    return [b'<h1>Hello, web!</h1>']

httpd = make_server('127.0.0.1',8080,application)

httpd.serve_forever()

通过jinja2模块渲染页面

from wsgiref.simple_server import make_server
from jinja2 import Template

def index():
    with open('test.html','r',encoding='utf-8') as f:
        data = f.read()
    template = Template(data)
    ret = template.render({"name":'alex','hobby':'eat'})
    return [bytes(ret, encoding='utf8')]

URL_LIST = [
    ('/index/', index)
]

def run_server(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html'),('k1','v1')])
    url = environ['PATH_INFO']
    func = None
    for i in URL_LIST:
        if i[0] == url:
            func = i[1]
            break
    if func:
        return func()
    else:
        return [bytes('404没有该页面',encoding='utf8')]

if __name__ == '__main__':
    httpd = make_server('',8000,run_server)
    httpd.serve_forever()
02-10 05:20