day 60 Django's first day

1. The essence of web framework

We can understand it this way: all web applications are essentially a socket server, and the user's browser is a socket client. This way we can implement the web framework ourselves.

 

Make a simple web framework first

 

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

while True:
    conn,addr =sk.accept()
    data =conn.recv(8096)
    print(data)
    conn.send(b'ok')
    conn.close()

Enter the url 127.0.0.1 in the browser and the result returned by the server

b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8080\r\n
Connection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch, br\r\n
Accept-Language: zh-CN,zh;q=0.8\r\n\r\n
'

 

Introduction to the HTTP protocol:

 

Format requirements of HTTP protocol for sending and receiving messages

 

Each HTTP request and response follows the same format. An HTTP contains two parts, Header and Body, where Body is optional. There is a header in the HTTP response  that indicates the content format of the response. Such as  representing HTML pages.Content-Typetext/html

 

The format of the HTTP GET request: (the request message sent by the browser)

 

The format of the HTTP response: (the server sends a message to the browser)

 

 

 

Virgin Edition Custom Web Framework

 

import socket

sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 8000))
sock.listen()

while True:
    conn, addr = sock.accept()
    data = conn.recv(8096)
    # Add a response status line to the reply message
    conn.send(b"HTTP/1.1 200 OK\r\n\r\n")
    conn.send(b"OK")
    conn.close()  

output result 

 

"""
Imperfect web server example
"""

import socket

# Generate socket instance object
sk = socket.socket()
# Bind IP and port
sk.bind(("127.0.0.1", 8001))
# monitor
sk.listen()

# Write an infinite loop, waiting for the client to connect to me
while 1:
    # Get the connection to the client
    conn, _ = sk.accept()
    # Receive messages from the client
    data = conn.recv(8096)
    print(data)
    # Reply message to client
    conn.send(b'http/1.1 200 OK\r\ncontent-type:text/html; charset=utf-8\r\n\r\n')
    # Want the content displayed by the browser on the page to be the response body
    conn.send(b'<h1>hello s10!</h1>')
    # closure
    conn.close()
    sk.close()

  

 

 Return different content according to different paths

 

 

import socket 
sk = socket.socket()
sk.bind(("127.0.0.1", 8080)) # bind IP and port
sk.listen() # listen

while 1:
# wait for connection
conn, add = sk.accept( )
data = conn.recv(8096) # Receive the message from the client # Get
the path from data
data = str(data, encoding="utf8") # Convert the received byte type data into a string
# Split by \r\n
print(data)
print("**"*20)###
data1 = data.split("\r\n")[0] # Get the first line of data
print(data1)
print ("**"*20)
url = data1.split()[1] # Separate it by spaces, url is the access path we separated from the message sent by the browser
print(url)
print( "**"*20)
conn.send(b'HTTP/1.1 200 OK\r\n\r\n') # Because it must follow the HTTP protocol, the reply message should also add a status line
# Return different content according to different paths
if url == "/index/":
response = b"index"
elif url == "/home/":
response = b"home"
else:
response = b"404 not found!"

conn.send(response)
conn.close()

  output result

 

C:\Python36\python3.exe D:/PycharmProjects/delete.py
GET /index/ 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 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: zh-CN,zh;q=0.8
Cookie: __guid=96992031.2553796166569308000.1524818350890.1082; monitor_count=9


****************************************
GET /index/ HTTP/1.1
****************************************
/index/
****************************************

  

 

 

 

二、Django

2.1 Install the latest lts version

pip3 install Django==1.11.11 (command under cmd)

Create a django project

django-admin startproject mysite# Create a django project named mysite

  

 Check 

 

 

Catalog introduction

 

 

 

 

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',
            ],
        },
    },
]
copy code

  

 

Static file configuration:

 
STATIC_URL = '/static/' # static folder prefix used in HTML
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"), # Static file storage location
]

 

 

When you first start learning, you can temporarily disable the csrf middleware in the configuration file to facilitate the form submission test.

 
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',
]
copy code

 

Django's basic three-piece set:

 

from django.shortcuts import HttpResponse, render, redirect

 

 

 

 

HttpResponse

Internally, a string parameter is passed in and returned to the browser.

E.g:

def index(request):
    # business logic code
    return HttpResponse("OK")

render

In addition to the request parameter, it also accepts a template file to be rendered and a dictionary parameter that holds specific data.

Fill the data into the template file, and finally return the result to the browser. (similar to the jinja2 we used above)

E.g:

def index(request):
    # business logic code
    return render(request, "index.html", {"name": "alex", "hobby": ["烫头", "泡吧"]})

redirect

Accepts a URL parameter, which means to jump to the specified URL.

E.g:

def index(request):
    # business logic code
    return redirect("/home/")

 

 

What's up with the redirect?

 

 

 

 

Homework:

Django version login

Start Django and report an error:

Django starts with an error UnicodeEncodeError...

This error is usually reported because the computer name is Chinese. Change the computer name to English and restart the computer.

 

 

  1. The essence of WEB framework

    socket server side and browser side

 

  2. Socket server and function division

    a. Responsible for sending and receiving messages with the browser ----------------> wsgiref/ uWsgi/gunicorn

    b. Execute different functions according to different paths accessed by customers

    c. Read the content from html, and complete the replacement of the string. --- ---jinja2

  3. Classification of web frameworks in python:

    According to the above functions:

    1. The framework comes with a,b,c ---> tornado

    2. The framework comes with b and c, using a ---> Django of third-party modules 

    3. The framework comes with b, using third-party a and c ----> Flash 

    Divide by another dimension

    1. Django--->big and comprehensive (you can use it when you make a website)

    

 

 

wsgiref version web framework

 

 

 

Make a Django framework

 

1. The location of the webpage

1. Put the html under the templates

 

2 Put bootstrap jquery in the static directory

 

 

 2. In the setting, set the path for the webpage to obtain files such as css js images

 

 

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

##Static file save directory alias
STATIC_URL = '/static/'

##All static files (css /jss/ images) are prevented from the folder we configure below
STATICFILES_DIRS =[
    os.path.join(BASE_DIR,'static')
]

 

 

 

 

 

2. Set in the url directory

 
 
from django.shortcuts import HttpResponse,render 
def yimi(request):
#request parameter saves all data related to the user's browser request
# return b'hello yimni!'
return HttpResponse('hello yimi!!') #httpresponse put http The protocol messages have been encapsulated.

def xiaohei(request):
return HttpResponse('hello xiaohei')

def index(request):
return render(request,'index.html')

urlpatterns=[
url(r'^yimi/' ,yimi),
url(r'^xiaohei/',xiaohei),
url(r'^index/',index)
]
 

 

 

 2. View the settings in the settings

 

 

 

import them

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))   Get the path of the root directory

  

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        ##Tell Django that you can find all the html files we use here
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,

  

 

 4. Run

1. Method 1

 


2PyCharm start
Click the green triangle to start the Django project directly (provided that the left side of the small triangle is your Django project name)

 

 

2. Method 2:

 

In the root directory of the project (that is, the directory with manage.py), run:
python3 manage.py runserver IP: port --> start
python3 manage.py runserver port at the specified IP and port --> at the specified port The port starts
python3 manage.py runserver --> default starts on port 8000 of the local machine

 

 

 

day61 2018-04-28

1. Content Review

1. Format of HTTP protocol message:
1. Request (request)
request method path HTTP/1.1\r\n
k1:v1\r\n
...\r\n
\r\nRequest
body<-- Yes,

2. Response
HTTP/1.1 Status Code Status Descriptor\r\n k1
:v1\r\n
Content-Type: text/html; charset=utf8\r\n
\r\nResponse
Body<- - HTML content

2. The essence of the Python web framework:
a. Send and receive socket messages --> Parse messages according to the HTTP protocol message format

b. Correspondence between paths and functions to be executed --> Main business logic

c. String replacement --> Template (special symbols --> data)

3. A complete request process:
0. Start the server and wait for the client (user's browser) to connect
1. Enter the URL in the browser address bar to establish a connection with the server, The browser sends a request
2. The server receives the request message, parses the request message, and finds the function to be executed according to the corresponding relationship between the path and the function
3. Execute the function, open the HTML file, perform string replacement, and get a final return HTML content
4. According to the message format requirements of the HTTP protocol, reply the HTML content to the user's browser (send a response)
5. After the browser receives the response message, it renders the page according to the HTML rules.
6. Close the connection


2. Django yesterday Content sorting:
0. Django installation
pip3 install django==1.11.11

pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple/ django==1.11.11 When

installing PyCharm:
be careful not to check that option (you know)

1. Django project startup:
1. Command line startup
In the root directory of the project (that is, the directory with manage.py), run:
python3 manage.py runserver IP: port --> start at the specified IP and port
python3 manage.py runserver port --> start
python3 manage.py runserver at the specified port --> start at port 8000 of the local machine by default

2. PyCharm starts
the small green triangle, which can directly start the Django project (provided that the small triangle On the left is your Django project name)

2. Configure the relevant project name/settings.py file
1. Templates (the configuration for storing HTML files) <-- Tell Django where to find my HTML files

2. Static files (css/js/ image)
# Alias ​​of the directory where static files are saved
STATIC_URL = '/static/'

# All static files (css/js/images) are placed in the folder you configured below me
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
3. Comment out setting.py with csrf The line (about 45~47 lines)


3. Today's content
1. A complete example of login


Review:
What three points need to be paid attention to when submitting data to the back end of the form form: Come back on May 1 and write it by default Everyone eats ice cream
1. The form is not from, all tags that get user input should be placed in the form, and must have a name attribute
2. The action attribute controls where to submit, and the method is generally set to post
3. The submit button must be type =submit, cannot be another type


2. GET request and POST request
GET request:
1. Browser requests a page 2. POST request
when search engine retrieves keywords : 1. Browser submits data to the server, such as login/registration, etc.


3. APP in Django:
What is APP? And why use APP?

project --> Project (Old Boys Education University)

APP --> Application (Linux Institute/Python Institute/Big Data Institute/Java Institute) is

convenient for us In a large Django project, management implements different business functions.

1. Commands to create APP
1. Command line, enter in the root directory of the Django project:
python3 manage.py startapp app name

4. ORM

import pymysql
pymysql.connect(
...
...
)

1. The SQL level written by different programmers is uneven
2. The execution efficiency is also uneven

python syntax -- automatic translation --> SQL statement

jQuery DOM
$("#d1") -- Automatic translation --> document.getElementById("d1")

ORM:
Advantages:
1. Simple, no need to write SQL statements by yourself
2. High development efficiency
Disadvantages:
1. Remember your special grammar
2. Compared with the SQL statements of the gods , There is definitely a gap in the execution efficiency

ORM's corresponding relationship:
class ---> data table
Object ---> Data Row
Properties ---> Field

What ORM can do:
1. Manipulate data tables --> create tables/delete tables/modify tables
Operate the classes in models.py

2. Operate data rows --> Data additions, deletions, changes, and inquiries


cannot create a database, create it yourself Database

Detailed steps for using Django's ORM:
1. Create a database yourself
create database database name;
2. Set the relevant configuration for connecting to the database in the Django project (tell Django which database to connect to)
# Database related configuration
DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql', # The database type to connect to
'HOST': '127.0.0.1', # The address to connect to the database
'PORT': 3306, # The port
'NAME': "day61 ", # database name
'USER': 'root', # user
'PASSWORD': '123456' # password
}
}
3. Tell Django to use pymysql instead of the default MySQLDB to connect to the MySQL database
in the project/__init__.py file, write the following Two sentences:
import pymysql
# Tell Django to use pymysql instead of the default MySQLdb
pymysql.install_as_MySQLdb()
4. Define a class in the models.py file under the app, this class must inherit the models.Model
class class name (models.Model):
...
5. Execute two commands
1. python3 manage. py makemigrations
2. python3 manage.py migrate


Addition and query of ORM single table:
1. Query
models.UserInfo.objects.all()

2. Add
models.UserInfo.objects.create(name="Zhang San")


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325015976&siteId=291194637