Django lore
Django origin
Django is an open source Web application framework written in Python. MVC framework pattern is adopted, that is, model M, view V and controller C. It was originally developed as CMS (Content Management System) software to manage some of Lawrence publishing group’s news-focused websites. It was released under the BSD license in July 2005. The frame is named after Belgian gypsy jazz guitarist Django Reinhardt. Django wasn’t written by a single person, it was written by a Team (click on Django Team to learn about Team members), and we all know that Django was named after one person, the man below. Let’s call him Johnny the Three Fingers
Django design ideas
The main goal of Django is to make it easy to develop complex, database-driven web sites. Django focuses on component reuse and pluggability, agile development, and DRY (Don’t Repeat Yourself). Python is widely used in Django, including configuration files and data models.
Django uses the MTV development model
Django is a framework based on MVC constructs. But with Django, the controller accepts user input and the framework handles it itself, so Django focuses more on models, templates, and Views, called MTV patterns. Under this model, we can feel its decoupling most directly. The front and back ends are completely separated. Their respective responsibilities are as follows:
- The Model, or data access layer, handles all transactions related to data: how it is accessed, validated, what behaviors are involved, and the relationships between data.
- The View, or presentation layer, handles presentation-related decisions: how to display on a page or other type of document.
- Templates are the logic that the business logic layer uses to access the model and retrieve the appropriate Template. Bridge between model and template.
Django project overview
Django Installation and Configuration
Django is installed on the terminal
# pip3 install django = = 1.11.11Copy the code
Django is installed on Pycharm
Using Mac OS as the demo standard, if Windows or Linux users read this article and cannot install it, please leave a comment below
Enter Pycharm and select the Pycharm –Preferences–Project–Project Interpreter–(+)– to search for Django, as shown below
Special reminder for Django installation
Django comes in a number of versions, so you are advised to install Django 1.11.** instead of installing the latest version. Do not install the latest version, do not upgrade! Do not install the latest version, do not upgrade!
Django 1.6.x supports Python 2.6.5 Python 2.7, Python 3.2, and 3.3. Django 1.6.x supports Python 2.6. x, 2.7. x, X and 3.3.X Django 1.7. X supports Python 2.7, 3.2, 3.3, and 3.4 (Note: Django 1.9.x supports Python 2.7, 3.2, 3.3, 3.4, and 3.5. (LTS) Django 1.9.x supports Python 2.7, 3.4 and 3.5. Django 1.11.x supports Python 2.7, 3.4, and 3.5. Django 1.11.x supports Python3.4, 3.5, and 3.6 (LTS). Will be released in 2019, more detailed information can go to https://www.djangoproject.com/download/, please find itself. Different versions of Django create the same project with different Settings, different modules, and more or less directives. Therefore, do not install different versions of Django in the same environment. It is best to use the same Django version for projects created under one version to avoid conflicts.Copy the code
Djangos implementation Principles
Django is essentially a Web framework
We can think of it this way: all Web applications are essentially a socket server, and the user’s browser is a socket client. So we can implement the Web framework ourselves.
Import socket sk = socket.socket() sk.bind(("127.0.0.1", 80)) sk.listen() while True: conn, addr = sk.accept() data = conn.recv(8096) conn.send(b"OK") conn.close()Copy the code
You can say that Web services are essentially extensions based on those dozen lines of code. This code is their ancestor.
When a user’s browser enters a url, it sends data to the server. What data does the browser send? How to send? Who decides that? You this website is this regulation, he that website according to his that regulation, this Internet can play?
Therefore, there must be a unified rule, so that people send and receive messages with a format, not random writing.
This rule is HTTP protocol, whether the browser sends a request message, the server responds to the message, should follow this rule.
The HTTP protocol mainly defines the communication format between the client and the server. How does the HTTP protocol specify the message format?
Let’s first print out what message we received on the server.
Import socket sk = socket.socket() sk.bind(("127.0.0.1", 80)) sk.listen() while True: Conn, addr = sk.accept() data = conn.recv(8096) print(data)Copy the code
B 'get/HTTP/1.1\r\nHost: 127.0.0.1:8080\r\nConnection: keep-alive\r\ upups-insecure -Requests: 1\r\ nuser-agent: Mozilla / 5.0 (Windows NT 10.0; Win64; X64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp image/apng, * / *; Q =0.8\r\nDNT: 1\r\ naccept-Encoding: gzip, deflate, br\r\ nAccept-language: zh-cn,zh; Q = 0.9 \ r \ nCookie: csrftoken = RKBXh1d3M97iz03Rpbojx1bR6mhHudhyX5PszUxxG3bOEwh1lxFpGOgWN93ZH3zv \ r \ n \ r \ n 'Copy the code
Then let’s take a look at what the browser responds to when we visit the blogosphere website.
The response information can be seen in the Network TAB of the browser debug window.
Click on view Source and the following image will appear:
We found that the sent and received messages need to follow a certain format, here we need to understand the HTTP protocol.
Please click on this article for an in-depth understanding of the HTTP protocol in the introductory front-end tutorial (I)
After the above supplementary learning, we know that in order to make our own Web server properly, we must let our Web server in the response to the client in accordance with the RULES of THE HTTP protocol to add the response status line, so we have realized a serious Web framework.
Import socket sock = socket.socket(socket.af_inet, socket.sock_stream) socket.bind (('127.0.0.1', 8000)) sock.listen() while True: conn, Conn. send(b"HTTP/1.1 200 OK\r\n\r\n") conn.send(b"OK") conn.close()Copy the code
You can write it as a function, you can write it as a dynamic, but I’m afraid the way to write a frame is as old as the journey to the West, so let’s stop there
Server programs and applications
For a python Web program in real development, there are typically two parts: the server program and the application. The server program is responsible for the socket server encapsulation, and when the request arrives, the request for various data collation. The application is responsible for the specific logical processing. In order to facilitate application development, there are many Web frameworks, such as Django, Flask, web.py, etc. Different frameworks develop in different ways, but in any case, the application must work with the server application to serve the user. Thus, the server program needs to provide different support for different frameworks. This mess is bad for both the server and the framework. The server needs to support a variety of frameworks, and for frameworks, only servers that support it can be used by developed applications. This is where standardization becomes particularly important. We can set a standard, and as long as the server application supports it and the framework supports it, they can work with it. Once the standard is determined, both sides implement it separately. In this way, the server can support more standards-compliant frameworks, and the framework can use more standards-compliant servers.
WSGI (Web Server Gateway Interface) is a specification that defines the Interface format between Web applications written in Python and Web Server programs to decouple Web applications from Web Server programs.
Common WSGI servers are UWSGi and Gunicorn. The Python standard library provides a standalone WSGI server called WSGIref, which the Django development environment uses as its server.
Continuing with the Web framework above…
Wsgiref module edition """ import time from wsgiref.simple_server import make_server Def index(url): with open("index.html", "r", encoding="utf8") as f: def index(url): with open("index.html", "r", encoding="utf8") as f: s = f.read() now = str(time.time()) s = s.replace("@@oo@@", now) return bytes(s, encoding="utf8") def home(url): with open("home.html", "r", encoding="utf8") as f: List1 = [("/index/", index), ("/home/", home), return bytes(s, encoding="utf8") ] def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html; Charset =utf8'),]) # environ['PATH_INFO'] # environ['PATH_INFO'] if i[0] == url: func = i[1] break if func: response = func(url) else: response = b"404 not found!" Return [response,] if __name__ == '__main__': HTTPD = make_server('127.0.0.1', 8090, run_server) print(" ) httpd.serve_forever()Copy the code
The above code implements a simple dynamic where I can query the data from the database, replace the corresponding content in my HTML, and then send it to the browser for rendering. This process is the equivalent of an HTML template rendering data. Essentially, HTML content uses special symbols to replace the data to be displayed. The special symbols I use here are my own, but there is a tool available for template rendering: Jinja2
Jinja2: pip3 install jinja2
<! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> title </title> </head> <body> <h1> {{name}} < / h1 > < h1 > hobbies: < / h1 > < ul > {% for hobby in hobby_list %} < li > {{hobby}} < / li > {% endfor %} < / ul > < / body > < / HTML >Copy the code
from wsgiref.simple_server import make_server from jinja2 import Template def index(): With open("index2.html", "r") as f: data = f.read() template = template (data) # generate template file ret = template.render({"name": Return [bytes(ret, encoding="utf8"),] def home(): return [bytes(ret, encoding="utf8"),] def home(): with open("home.html", "rb") as f: URL_LIST = [("/index/", index), ("/home/", home), ] def run_server(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html; Url = environ['PATH_INFO'] # func = None # for I in URL_LIST: If I [0] == url: func = I [1] # break if func: # return func() # return func() # else: Return [bytes (" 404 without the page ", encoding = "utf8"),] if __name__ = = "__main__ ': httpd = make_server('', 8000, run_server) print("Serving HTTP on port 8000..." ) httpd.serve_forever()Copy the code
Now the data is handwritten by ourselves, so can we query the data from the database to fill the page?
Connect to database with Pymysql:
Conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", passwd=" XXX ", db=" XXX ", charset="utf8") cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute("select name, age, department_id from userinfo") user_list = cursor.fetchall() cursor.close() conn.close()Copy the code
Create a test user table:
CREATE TABLE user(
id int auto_increment PRIMARY KEY,
name CHAR(10) NOT NULL,
hobby CHAR(20) NOT NULL
)engine=innodb DEFAULT charset=UTF8;Copy the code
The principle of template is string replacement. As long as we write in the HTML page following the syntax rules of Jinja2, it will be replaced in accordance with the specified syntax, so as to achieve dynamic return of content.
Error when starting Django
Django starts with “UnicodeEncodeError…”
This error is usually reported because the computer name is Chinese, change the English computer name to restart the computer can be.
Django startup error “SyntaxError: Generator expression must be parenthesized”
This error is most likely due to Python3.7.0 being used, and currently Python3.7.0 has some compatibility issues with Django.
Start writing projects using Django
It doesn’t matter if you don’t understand the previous implementation principles, since you’re still a long way from being an architect, so you don’t need that much knowledge right now, but here are some real Django basics
I’m sure you’ve been holding on for a long time, so let’s write a small project and relax
Write Hello World using Django
All of the following demonstrations are run on a terminal, although some parts can also be run on Pycharm
Python3 manage.py startApp test_app # Create a test project under the project tree # List the files and folders under the project in a tree formCopy the code
The results are as follows
. ├ ─ ─ the manage. Py ├ ─ ─ test_app │ ├ ─ ─ just set py │ ├ ─ ─ admin. Py │ ├ ─ ─ apps. Py │ ├ ─ ─ migrations │ │ └ ─ ─ just set py │ ├ ─ ─ Models. Py │ ├ ─ ─ tests. Py │ └ ─ ─ views. Py └ ─ ─ test_site ├ ─ ─ just set py ├ ─ ─ __pycache__ │ ├ ─ ─ just set retaining - 36. Pyc │ └ ─ ─ Settings. Retaining - 36. Pyc ├ ─ ─ Settings. Py ├ ─ ─ urls. Py └ ─ ─ wsgi. PyCopy the code
Continue to run the command on the terminal
python3 manage.py migrate
python3 manage.py runserverCopy the code
Then open any browser and type http://127.0.0.1:8000/
Youll see Django working. Next, write Hello World. Just change two of the files
Create a views.py file under test_site — test_site
from django.shortcuts import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")Copy the code
Modify the urls.py file
from django.conf.urls import url
from django.contrib import admin
from test_site import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello),
]Copy the code
(Creative Commons 4.0 License)