Python learning-web framework and pythonweb framework
All Web applications are essentially a socket server, and your browser is actually a socket Client.
WSGI (Web Server Gateway Interface) is a specification that defines the Interface formats between web apps and web servers written in python to achieve decoupling between web apps and web servers.
1. The independent WSGI server provided by the python standard library is called wsgiref
1 from wsgiref.simple_server import make_server 2 3 def RunServer(environ, start_response): 4 start_response('200 OK', [('Content-Type', 'text/html')]) 5 return [bytes('
The result is:
Ii. custom web framework
Develop your own Web framework through the wsgiref module provided by the python standard library
1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 4 from wsgiref. simple_server import make_server 5 6 def f1 (): 7 f = open ("index.html") 8 data = f. read () 9 f. close () 10 # Replace the returned information with the database information (dynamic) 11 import time12 db_str = str (time. time () 13 data = data. replace ("(x)", db_str) 14 # The jinja2 template provides you with a more complex replacement 15 return data16 17 def f2 (): 18 f = open ("login.html") 19 data = f. read () 20 f. close () 21 from jinja2 import Template22 template = Template (data) 23 # accept the value and replace it with 24 ret = template. render (name = "koka", user_list = ["asd", "qwe"]) 25 return ret. encode ("UTF-8") 26 27 #1 defines a dictionary. The preceding function defines 28 routers = {29 '/index/': f1, 30'/login/': f2, 31} 32 33 def RunServer (environ, start_response ): 34 # environ encapsulate all user-related information 35 # environ ["PATH_INFO"] reads the url36 start_response ('2017 OK ', [('content-type ', 'text/html')]) 37 # execute different functions based on different URLs, return a different string 38 request_url = environ ['path _ info'] 39 # print environ # Here we can use breakpoints to check what data it encapsulates 40 41 # If the url requested by the user match the url we defined with 42 if request_url in routers. keys (): 43 func_name = routers [request_url] () 44 ret = func_name () 45 return ret46 else: 47 return '000000' 48 49 if _ name _ = '_ main _': 50 httpd = make_server ('', 404, RunServer) 51 print "Serving HTTP on port 8000... "52 httpd. serve_forever ()
Template engine:
1 <!DOCTYPE html> 2
1 <!DOCTYPE html> 2