Web Framework Nature:
The Web application is essentially the socket server. And the user's browser is a scoket client
Import Socketsk = Socket.socket () sk.bind (("127.0.0.1", "a") Sk.listen () while True: conn, addr = sk.accept () data = Conn.recv (8096) conn.send (b ' OK ') conn.close ()
It can be said that the Web service is essentially the extension of several lines of code, and this code is their ancestor
The user then enters the URL in the browser, the browser will send the data like the server, what data will the browser send?
Specify the HTTP protocol, after which the browser sends the request information, the server responds, all follow this rule.
The HTTP protocol mainly specifies the communication format between the client and the server, how does the HTTP protocol specify the message format?
Import socket SK = Socket.socket () sk.bind (("127.0.0.1", 8000)) Sk.listen () while True: conn, addr = Sk.recv (8096 data = CONN.RECV (8096) print (data) conn.send (b ' OK ') conn.close ()
Output:
B ' get/http/1.1\r\nhost:127.0.0.1:8080\r\nconnection:keep-alive\r\ncache-control:max-age=0\r\ nupgrade-insecure-requests:1\r\nuser-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/66.0.3355.4 safari/537.36\r\naccept:text/html,application/xhtml +xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\naccept-encoding:gzip, deflate, br\r\ naccept-language:zh-cn,zh;q=0.9\r\ncookie:csrftoken= Cthepyarjoknx5onvwxiteojxpnyj29l4bw4506yovqfaiffahm0ewdzqkmw6jm8\r\n\r\n '
Replace \ r \ n with line break;
get/http/1.1 host:127.0.0.1:8080 connection:keep-alive cache-control:max-age=0 Upgrade-insecure-requests:1 user-agent:mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/66.0.3355.4 safari/537.36 accept:text/html,application/ xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 accept-encoding:gzip, deflate, BR accept-language:zh-cn,zh;q=0.9 cookie:csrftoken= Cthepyarjoknx5onvwxiteojxpnyj29l4bw4506yovqfaiffahm0ewdzqkmw6jm8
The format requirements of the HTTP protocol for manipulation messages
Each HTTP request and response should follow the same format, with an HTTP header and Boby two parts, where boby are optional.
The header of the HTTP response has a Content-type table name in response to the content format, and his value is Text/html;charset=utf-8
text/html represents a Web page, CHARSET-UTF-8 is encoded as Utf-8
The format of the HTTP GET request;
The format of the HTTP response;
Customizing the web Framework
Import Socketsk = Socket.socket () sk.bind (("127.0.0.1", 8000)) Sk.listen () while True: conn, addr = sk.accept () data = Conn.recv (8096) # Adds response status line conn.send (b ' http/1.1 ok\r\n\r\n ') to the reply message conn.send (b ' OK ') Conn.close ()
The above code allows the page to be displayed dynamically
Import Socketsk = Socket.socket () sk.bind (("127.0.0.1", 8080)) Sk.listen () # return different content parts encapsulated into different functions def timer (): Import Time date = Time.strftime ("%y-%m-%d%h:%m:%s") with open ("time.html", ' R ', encoding= ' utf-8 ') as f: ret = F.read () ret = ret.replace (' time ', date) return Ret.encode ("Utf-8") # defines the correspondence between a URL and the actual function to be performed list1 = [ ("/ time/", timer)]while True: # waits for connection conn, addr = sk.accept () data = CONN.RECV (8000) URL = Data.decode (" Utf-8 "). Split () [1] # to get the path conn.send (b ' http/1.1 ok\r\n\r\n ') by Space split # Send the status code of the HTTP protocol and reply followed Func = None for i in List1: if i[0] = = URL: # Address taken out by the browser/admin/ func = i[1] Break if Fu NC: response = func () else: response = B ' 404 Not Found ' # Send the returned value of the corresponding function conn.send (response) Conn.close ()
Servers and Applications
For the Python Web: It is divided into two parts: servers and applications.
The server sees the program is responsible for the socket service side encapsulation, and when the request arrives, the request of the various data to organize
Application of the program is responsible for the logical processing, in order to facilitate the development of the application, there will be a lot of lweb framework, such as django,flask,web.py, etc., different frameworks have different development methods, but in any case, the application can be issued with the server program, To provide services to users
In this way, the server program needs different frameworks to provide different support, so the chaotic situation for the server or the framework is not good, for the service area, need to support a variety of frameworks, for the framework, only support his server guess can be opened out of the application to use.
At this time, standardization is particularly important, we can set up a standard, as long as the squeeze process to support this standard, the framework also supports this standard, then they can be used, once the standard is determined, both sides to implement. This allows the server to support a framework that supports multiple standards. Framework a server that can use more support standards
WSGI (Web server Gateway interfase) is a specification that defines the amount of interface format between a Web application and a Web server program written in Python, enabling decoupling between Web applications and Web server programs
The common WSGI server is Uwsgi, Gunicorn. Two The standalone WSGI service provided by the Python standard library is called the Wsgiref,diando development environment with the server that this module is made of
Wsgiref
We use the Wsgiref module to replace the socket.server part of the web framework we wrote ourselves
"' returns different content based on different paths in the URL--function Advanced return HTML page to make the page Dynamic Wsgiref module version ' from Wsgiref.simple_server import make_server# Encapsulates the different contents of the returned part into a function def index (URL): # reads the contents of the Index.html page with open (' index.html ', ' R ', encoding= ' Utf-8 ') as F:s = F.read () # returns byte data return bytes (s, encoding= ' Utf-8 ') def Home (URL): With open (' home.html ', ' R ', encoding= ' utf-8 ') a s f:s = f.read () return bytes (s, encoding= ' Utf-8 ') def timer (URL): Import time with open (' time.html ', ' R ', encoding= ' Utf-8 ') as F:s = F.read () s = s.replace ("Time", Time.strftime ("%y-%m-%d%h:%m:%s")) return by TES (S, encoding= ' Utf-8 ') # defines the correspondence between a URL and the actual function to be performed list1 = [('/index/', Index), (' home/', Home), ('/time/', timer)]d EF run_server (environ, start_response): Start_response (' OK ', [(' Content-type ', ' text/html; Charset=utf-8 '),] # Set HTTP response status and header information URL = environ[' path_info ' # gets the URL of the user input func = None for i in list1:if i[0] = = URL: Func = i[1] if Func:response = Func (URL) else:response = B ' 404 Not Found ' return [response,]if __name__ = = ' __main__ ': httpd = Make_se RVer (' 127.0.0.1 ', 8090, run_server) print ("8090 ...") Httpd.serve_forever ()
Django
Install django=== (Install django1.11.15)
PIP3 Install django==1.11.15
Create a Django project:
Django-admin Startproject ProjectName
mysite/├──manage.py # Manage files └──mysite # project directory ├──__init__.py ├──settings.py # configuration ├──urls.py< c8/># route--url and function correspondence └──wsgi.py # runserver command makes simple Web server using WSGIREF module
Run a Django Project
Python manage.py runserver 127.0.0.1:8000
Template file Configuration
TEMPLATES = [ { ' backend ': ' django.template.backends.django.DjangoTemplates ', ' DIRS ': [Os.path.join ( Base_dir, "template")], # Template folder location ' app_dirs ': True, ' OPTIONS ': { ' context_processors ': [ ' Django.template.context_processors.debug ', ' django.template.context_processors.request ', ' Django.contrib.auth.context_processors.auth ', ' django.contrib.messages.context_processors.messages ', ], }, },]
Static file configuration:
Static_url = '/static/' # The static file prefix used in HTML staticfiles_dirs = [Os.path.join (barse_dir, ' static '), # static file storage location c17/>]
Just start learning. You can disable the CSRF middleware in the configuration file to facilitate form submission testing
middleware = [ ' Django.middleware.security.SecurityMiddleware ', ' Django.contrib.sessions.middleware.SessionMiddleware ', ' Django.middleware.common.CommonMiddleware ', # ' Django.middleware.csrf.CsrfViewMiddleware ', ' Django.contrib.auth.middleware.AuthenticationMiddleware ', ' django.contrib.messages.middleware.MessageMiddleware ', ' Django.middleware.clickjacking.XFrameOptionsMiddleware ',]
Django Essentials three-piece set:
From django.shortcuts import HttpResponse, Render, redirect
HttpResponse
Internally, a string parameter is passed back to the browser.
For example:
def index (Request): # Business logic Code return HttpResponse ("OK")
Render
In addition to the request parameter, it accepts a template file to be rendered and a dictionary parameter that holds the specific data.
Populate the template file with the data, and finally return the structure to the browser. (Similar to the jinja2 we used above)
For example:
def index (Request): # Business logic Code return render (Request, "index.html", {"name": "Alex", "hobby": ["Perm", "Bubble Bar"]})
redirect
Accepts a URL parameter that represents a jump to the specified URL
For example:
def index (Request): # Business logic Code return Redirect ("/home/")
How is redirection going?
Redirection (Redirect) is a way to redirect various network requests in different directions to another location
1, website adjustment
2, the webpage is moved to a new address
3, the Web extension changes (if the application needs to change. php to. html or. shtml)
In this case, if you do not redirect, the user's favorites or the old address in the search database can only access a 404 error message, the traffic is lost.
Start Django Error
Django startup times Wrong unicodeencodeerror ...
This error is usually reported because the computer name is Chinese, and the computer name changed to English will restart the computer.
Web Framework Principles