Download and install Django model acquaintance of Contents Introduction

Django

A, web application

What web application

Web applications-applications that can be accessed through the Web, the biggest benefit of the program is that users can easily access the application, users only need to have a browser, do not need to install additional software

Application has two modes C / S, B / S. C / S is a client / server applications, which means that such procedures are generally run independently. And B / S is the browser client / server applications, such applications typically means IE and other browsers to run. WEB application generally B / S model. Web application first is the "application", and using standard programming languages, such as writing out of the C, C ++ and other procedures did not differ essentially what. However, the Web application has its own unique place, is that it is Web-based, rather than using the traditional method of operation. In other words, it is the product of a typical browser / server architecture.

Advantages of web applications

  • Web application does not require any complex "expand" process, all you need is a suitable browser;
  • Network applications often takes little space in the user's hard drive, or that is not consumed;
  • They need not be updated, as new features are all executed on the server, to automatically communicated to the client;
  • Web applications and server networking products are easy to combine functions such as email and search functions;
  • Because they run in a web browser window, so in most cases they are cross-platform use (such as Windows, Mac, Linux, etc.)

Disadvantage of Web applications

  • Web applications emphasize the applicability of the browser. If the browser provides no specific function, or abandon a particular platform or operating system version (lead NA), it will affect a large number of users;
  • Network applications rely on Internet remote application file server. Thus, when the connection problem, the application may not function properly.
  • Many web applications are not open source, and can only rely on services provided by third parties and therefore can not be customized for the user, personalized, and in most cases users can not be used offline, and therefore lost a lot of flexibility;
  • They rely solely on application service provider availability. If the company goes bankrupt, stop using the server, the user can not be traced previous data. Compare and see, even if the software manufacturer went out of business, traditional software installation can continue to run, although no longer updated or other user services;
  • Similarly, the software provider company and its functions have greater control. If they would be able to add new features to the software, even if the user want to wait for bugs to be solved before updating. Skip poor software version is also impossible. The company can impose undesirable characteristics to the user, but also free to reduce the bandwidth to cut spending.
  • The company is theoretically possible to retrieve any user behavior. This may cause privacy issues.

B / S architecture advantages

Browser / server architecture (Browser / Server, referred to as B / S) can be well applications over the WAN, become more and more enterprises. Browser / Server architecture with respect to several other application architecture, the following three advantageous aspects:

  • This architecture uses the Internet standard communication protocols (usually TCP / IP protocol) protocol as a client with the server communication. This allows people anywhere in the Internet can access the server properly. For servers, the data can be processed by the appropriate Web service and database services. External standard communication protocol, to share data.
  • The results of the data is processed on the server, it is processed to generate web pages to facilitate client direct download.
  • Processing of the data is further simplified on the client, a browser client application to effect display of data. No longer need to write separate client and install other types of applications. In this way, the client only needs to install an operating system built-in browser, direct the installation of a browser, you can enable access to data on the server. The browser is the standard of computer equipment

To sum up, in essence: Browser is a socket client and server is a server socket

Socket-based hand line and a simple web application

import socket

def server_run():
    server = socket.socket()  # 创建socket对象
    server.bind(('127.0.0.1',8003))  # 绑定ip和端口号
    server.listen(5)  # 设置半连接池
    while True:
        # 1.直接在send内写回复发送给客户端
        #conn,addr=server.accept()
        #recv_data = conn.recv(1024)
        #print(recv_data)
        # 2. 打开一个html文件,发送给客户端
        #with open('test.html','r',encoding='utf-8') as f:
           # data = f.read()
           # conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
        # 3. 动态网页渲染
        import time
        now=time.strftime("%Y-%m-%d %X")
        print(now)
        with open('test.html','r',encoding='utf-8') as f:
            data=f.read()
        data=data.replace('@@@',now)
        conn.send(('HTTP/1.1 200 OK\r\n\r\n%s'%data).encode('utf-8'))
        conn.close()
 if __name__ == '__main__':
    server_run()

HTTP protocol (memorize)

HTTP protocol is the Hyper Text Transfer abbreviation Protocol (Hypertext Transfer Protocol) is used for the World Wide Web (WWW: World Wide Web) transmission hypertext transfer protocol between the server and local browser.

HTTP is a protocol belonging to the object-oriented application layer, due to its simple, fast way for distributed hypermedia information system. It is proposed in 1990, after several years of use and development, has been continuously improved and expanded. HTTP protocol works on the client - server architecture on. Browser as an HTTP client URL that is WEB server sends all requests to the server via HTTP. Web server according to the received request, transmits the response information to the client.

Features of the HTTP protocol

  • HTTP protocol is based on an application layer protocol using TCP / IP protocol
  • Based on the request - response pattern : HTTP agreement, issuing a request from the client, the server responds to the request and finally returns and, in other words, can set the start is to start establishing a communication of the client, the server does not request is not received prior to It will send a response.
  • Stateless Save : HTTP is a non-save state, i.e., no state (Stateless) protocol. HTTP protocol itself does not request and the communication status between the response stored. This means that HTTP level, a nice protocol for sending requests or responses do not persist in the process. Using the HTTP protocol, whenever a new request is sent, it will produce a corresponding new response. The agreement itself does not keep everything before the request or response information packet. This is to handle a large number of transactions quickly, to ensure that the protocol scalability , and the HTTP protocol specifically designed so simple. However, as the Web continues to develop, because there is no state which led to business processing becomes difficult cases increased. For example, a user logs on to a shopping site, even after he jumps to the other page of the station, but also need to be able to continue to stay logged in. For this example, the site is to be able to grasp who sent the request, the need to preserve the user's status. HTTP / 1.1 is a stateless protocol, although, in order to realize a desired function to maintain state, then the introduction of Cookie technology. With Cookie and then HTTP protocol communication, you can manage the state.
  • No connection : Meaning No connection is to limit each link only one request. After the server processes the client request and response by the customer, i.e., disconnected. In this way it can save transmission time.

HTTP Request Protocol

http protocol comprising protocol data requested by the browser sends a request to the protocol sent by the server to follow the data server to the browser to follow. HTTP is believed to be known as an HTTP packet. Requester (client) HTTP packets do request packet, the responder (server side) made in response message. HTTP word text message itself is composed of multiple rows of data.

Request format:

Request method: get and post requests

  • Body GET request submitted data is placed after the URL to '?' Split URL and transmit data to & linked between parameters such as EditBook? Name = test1 & id = 123456. POST method is the data submitted in a HTTP packet in.
  • GET submitted the data size is limited (because the browser restrictions on the length of the URL), and the data submitted by the POST method is not limited.
  • GET and POST requests the server request data acquired in different ways.
 GET请求
    # 请求首行
    GET / HTTP/1.1\r\n
    # get请求后面的参数
    GET /?name=lqz&age=18 HTTP/1.1\r\n
    # 请求头
    Host: 127.0.0.1:8008\r\n
    Connection: keep-alive\r\n
    Cache-Control: max-age=0\r\n
    Upgrade-Insecure-Requests: 1\r\n
    User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\r\n
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, br\r\n
    Accept-Language: zh-CN,zh;q=0.9\r\n
    Cookie: csrftoken=7xx6BxQDJ6KB0PM7qS8uTA892ACtooNbnnF4LDwlYk1Y7S7nTS81FBqwruizHsxF\r\n\r\n'
    # 请求体(get请求,请求体为空)    
    '''
    '''
    POST请求
    # 请求首行
    POST /?name=qzk&age=18 HTTP/1.1\r\n
    # 请求头
    Host: 127.0.0.1:8008\r\nConnection: keep-alive\r\nContent-Length: 21\r\nCache-Control: max-age=0\r\nOrigin: http://127.0.0.1:8008\r\nUpgrade-Insecure-Requests: 1\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\nReferer: http://127.0.0.1:8008/?name=lqz&age=18\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: zh-CN,zh;q=0.9\r\nCookie: csrftoken=7xx6BxQDJ6KB0PM7qS8uTA892ACtooNbnnF4LDwlYk1Y7S7nTS81FBqwruizHsxF\r\n\r\n
    # 请求体
    name=qzk&password=123'
    
    '''

Response protocol

Response format

The response status code

Duty status code is the result when the client requests the server would like to send the request to return. By means of a status code, the user can know the state of the server process requests the information server.

web framework

Web framework (Web framework) is a development framework to support the development of dynamic web sites, web applications and network services. Most of these web frameworks provide a way to develop and deploy a website, but also provides a common approach to web behavior. web framework has achieved a lot of features, developers use the framework provided and complete their own business logic, you can quickly develop a web application. The browser and the server is based on HTTP protocol to communicate. It can be said web framework is extended out more than a dozen lines of code base sheets, there are a lot of simple and convenient method of use, greatly improving the efficiency of development.

wsgiref module

The simplest Web application is the first HTML file is saved with the good, with an existing HTTP server software, the user receives the request, reads from the HTML file and returns.

If you want to dynamically generate HTML, you need to put these steps to achieve their own. However, acceptance of the HTTP request, parse HTTP request, the HTTP response is sent coolies live, if we ourselves write these underlying code, it has not yet begun to write dynamic HTML, you have to spend a month to read the HTTP specification.

​ 正确的做法是底层代码由专门的服务器软件实现,我们用Python专注于生成HTML文档。因为我们不希望接触到TCP连接、HTTP原始请求和响应格式,所以,需要一个统一的接口协议来实现这样的服务器软件,让我们专心用Python编写Web业务。这个接口就是WSGI:Web Server Gateway Interface。而wsgiref模块就是python基于wsgi协议开发的服务模块

from wsgiref.simple_server import make_server

def mya(environ, start_response):
    print(environ)
    start_response('200 OK', [('Content-Type', 'text/html')])
    if environ.get('PATH_INFO') == '/index':
        with open('index.html','rb') as f:
            data=f.read()

    elif environ.get('PATH_INFO') == '/login':
        with open('login.html', 'rb') as f:
            data = f.read()
    else:
        data=b'<h1>Hello, web!</h1>'
    return [data]

if __name__ == '__main__':
    myserver = make_server('', 8011, mya)
    print('监听8010')
    myserver.serve_forever()

Django简介之MVC与MTV

MVC

web服务器开发领域里最著名的是MVC模式,所谓MVC就是把web应用分为模型(Models)、控制器(control)和视图(views)三层,他们之间已一种插件式的、松耦合式的连接在一起,模型负责业务对象与数据库的映射(ORM),视图负责与用户的交互(页面),控制器接受用户的输入调用模型和视图,完成用户的请求。其示意图如下:

MTV

Django的MTV模式本质上和MVC是一样的,也是为了各组件间保持松耦合关系,只是定义上有些不同。

Django的MTV分别是指:

  • M 代表模型(Model):负责业务对象和数据库的关系映射(ORM)。
  • T 代表模板(Template):负责如何把页面展示给用户(HTML)
  • V 代表视图(View):负责业务逻辑,并在适当时间调用Model 和Template

除了以上三层之外,还需要一个URL分发器,它的作用是将一个个URL的页面请求分发给不同的View处理,View 再调用相应的Model 和Template,MTV的相应模式如下

一般是用户通过浏览器向我们的服务器发起一个请求(request),这个请求回去访问视图函数,(如果不涉及到数据调用,那么这个时候视图函数返回一个模板也就是一个网页给用户),视图函数调用模型,模型去数据库查找数据,然后逐级返回,视图函数把返回的数据填充到模板中空格中,最后返回网页给用户。

下载Django

方式一、在命令行输入:pip3 install django==1.11.9 (后面可以不用写==1.11.9就是下载最新版本,it行业一般不会轻易去使用最新版本,因此建议下载1.11版本)

方式二、用pycharm安装

方式三、用pycharm的Terminal 的命令安装。

创建一个Django project

django-admin.py startproject mysite

当前目录下回生成mysite的工程。目录结构如下:

注:

  • manage.py-----Django项目里面的工具,通过它可以调用django shell 和数据库等
  • settings.py-----包含了项目的默认设置,包括数据库信息,调试标志以及其他一些工作的变量
  • urls.py--------负责把URL模式映射到应用程序

在mysite目录下创建应用

python manage.py startapp blog

启动django项目

python manage.py runserver

注意事项

开启Django 需要注意一下几点坑:

  1. 计算机名称不能有中文
  2. 一个pycharm 窗口就是一个项目,不要讲多个项目放在一个窗口里面
  3. 项目名称不能写中文
  4. 网页中 需要右击检查,进入设置,将 浏览器设置为不记住缓存(如果后期不这么操作,会导致网页上不显示您希望的效果)

Guess you like

Origin www.cnblogs.com/qianzhengkai/p/10980705.html