Http code changes the world

http protocol

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

HTTP is used to transfer a data (HTML files, image files, query results, etc.) based on TCP / IP communication protocol.

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. Currently used in the WWW is the sixth version of the HTTP / 1.0, the standardization work underway in HTTP / 1.1, and HTTP-NG (Next Generation of HTTP) recommendations have been proposed.

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.

HTTP Features

1, simple and fast: a customer service request to the server, instead of sending the request method and path. Request method commonly used GET, HEAD, POST. Each method provides a different type of client contacts the server. Due to the simple HTTP protocol, HTTP server makes the program a small scale, so the communication is very fast.

2, flexible: HTTP allows the transmission of any type of data object. It is the type of transmission being marked by Content-Type.

3. No connection: Meaning No connection is to limit the processing only one request per connection. After the server processes client requests and receives the customer's response, i.e., disconnected. In this way it can save transmission time.

4. stateless: HTTP protocol is stateless protocol. No state is no protocol for transaction processing and memory. If the lack of state means that the subsequent processing required in front of the information, it must be retransmitted, which may result in the amount of data transmitted for each connection is increased. On the other hand, when it does not require previous information in response to a faster server.

 

HTTP Request Protocol

Request Protocol in accordance with the following format:

The first line of the request; // request method and request path protocol version, for example: GET /index.html HTTP / 1.1 
request headers; // request header name: request header content, is the key: value format, for example: Host: localhost 
empty row; // request body and spaced apart for 
the request body. // GET request no body, there is only the POST request body.

Content browser sends to the server on this format, if this format is not the server will not read! In the HTTP protocol, there are many requests request method, the most commonly used is the GET and POST .

get request

HTTP default request method is GET
     * no request body
     * the amount of data is limited!
     * GET request data will be exposed in the browser's address bar

GET requests common operations:
       1. given URL directly in the address bar of your browser, then it must be a GET request
       hyperlink 2. Click on the page must be the GET request
       3. When the form is submitted, the form used by default GET request but it can be set to POST

Request header:

1, Host 

requested web server domain address
2, Content-Type 

show this HTTP request submitted content type. Generally only need to set the post when submitted property 

Content-Type attribute value relating There are two types of encoding: 

(. 1) "file application / X-WWW-form-urlencoded": encoding type when the form data is used by the server, the default default value is "application / x-www-form -urlencoded". 
However, in a lot of text sent to the server, which is very low coding efficiency when text or binary data contains non-ASCII characters. (2) "multipart / form- data": when the file upload, type of encoding used should be "multipart / form-data", it can either send the text data, binary data are also supported on the carrier. When the form data is submitted, you can use "application / x-www-form -urlencoded"; when the file is submitted, it is necessary to use "multipart / form-data" encoding type. 3, Keep-Alive expressed the need for persistent connections. If the web server to see here is "Keep-Alive", or see the request using HTTP 1.1 (HTTP 1.1 persistent connections default), you can take advantage of persistent connections


post request

POST / HTTP1.1
Host:www.wrox.com
User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)
Content-Type:application/x-www-form-urlencoded
Content-Length:40
Connection: Keep-Alive

name=Professional%20Ajax&publisher=Wiley

Part I: request lines, the first line is clear post request, and http1.1 version.
Part II: request header, the second to sixth rows.
Part III: blank lines, blank lines seventh row.
Part IV: request data, the eighth line.

 

HTTP response protocol

 Response format

In general, the server receives and processes requests sent, the client returns a response message of HTTP.

HTTP response also consists of four parts, namely: a status line, message header, and response body blank line.

 

Part I: status line, by the HTTP protocol version, status code, a status message of three parts.

A first status line behavior, (HTTP / 1.1) shows that HTTP version 1.1 version, status code 200, status message (ok)

Part II: message header, used to illustrate some additional information to be used by the client

The second and third behaviors message header,
a Date: the date and time response; Content-Type: Specifies the MIME type of HTML (text / html), encoding type is UTF-8

Part III: blank line, blank line after the message header is required
Part IV: response body, the server returns the text information to the client.

html part blank line after the response body.

 

The response status code

Status code has three numbers, the first number of defined categories of response, is divided into five categories: 
1xx: indication information - indicates a request has been received, processing continues 
2xx: Success - indicates that the request has been successfully received, understood, accepted 
3xx: redirection - to fulfill the request must go a step further 
4xx: client error - the request has a syntax error or a request can not be achieved 
5xx: server-side error - server failed to achieve a legitimate request 

common status codes: 
the OK                         // client request succeeds 
Bad request                // client requests a syntax error, can not be understood by the server 
unauthorized               // request is not authorized, the status code must be used with the WWW-Authenticate header field 
Forbidden                  // server receives the request, but refused to provide services 
not Found                  // requested resource does not exist, eg: enter the wrong URL
Server Error Internal      // server error occurred unexpected 
Server Unavailable Papers with         // request that the server can not handle the current client, may return to normal after a period of time

 

The difference between GET and POST requests

1, GET, request the data is then either deposited URL (that is, the data is placed into the HTTP protocol header), to divide the URL and transmit data, a plurality of parameters & connect; for example:? Login.action name = hyddd & password =? idontknow & verify =% E4% BD% A0% E5% A5% BD. If the data is in English letters / numbers, as it is transmitted, if the space is converted to +, if Chinese / other characters, the string directly BASE64 encryption, obtained as:% E4% BD% A0% E5% A5% BD, where XX XX% for the symbols in the ASCII hexadecimal representation.

POST submission: submit the data packet is placed in the body of the HTTP packet. Red lettering is the actual data transmission in the above example

Therefore, the GET data submitted will be displayed in the address bar out, and POST submission, the address bar will not change

2, the size of data transmission: First statement: the HTTP protocol does not limit the size of the transfer data, HTTP protocol specification does not limit the length of the URL.

Exists in the actual development restrictions are:

The GET : has a specific browser and server URL length limit, e.g. IE URL length limit is 2083 bytes (2K + 35). For other browsers, such as Netscape, FireFox, etc., in theory, there is no length limit, that limit depends on operating system support.

So for the time GET submission, data transmission will be restricted URL length.

POST : Because not pass through the URL value, in theory, unlimited data. However, the actual requirements of each WEB server will submit data on post size limit, Apache, IIS6 has its own configuration.

 The difference between GET and POST

    1. Body GET data is placed after the submitted URL to? URL and transmit the divided data, is connected to between & parameter, such as EditPosts.aspx? Name = test1 & id = 123456. POST method is the data submitted in a HTTP packet .

    2. 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.

    3. GET requires the use Request.QueryString to get the value of a variable, while the POST method to get the value of a variable by Request.Form.

    4. Submit a GET data, it will bring security problems, such as a login page when submitting data via GET, the user name and password will appear in the URL, if the page can be cached or others can access this machine, you can from history record obtain the user ID and password.

web and web application framework

web application

For all Web applications, in fact, a socket server, the user's browser is actually a socket client in nature.

import socket

def handle_request(client):

    buf = client.recv(1024)
    client.send("HTTP/1.1 200 OK\r\n\r\n".encode("utf8"))
    client.send("<h1 style='color:red'>Hello, yuan</h1>".encode("utf8"))

def main():

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost',8001))
    sock.listen(5)

    while True:
        connection, address = sock.accept()
        handle_request(connection)
        connection.close()

if __name__ == '__main__':

    main()

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.

      The correct approach is the underlying code is implemented by a dedicated server software, we focus on Python generate an HTML document. Because we do not want access to TCP connections, HTTP request and response format of the original, so the need for a unified interface, allowing us to concentrate on writing Web services using Python.

This interface is WSGI: Web Server Gateway Interface.

wsgiref

from wsgiref.simple_server import make_server


def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'<h1>Hello, web!</h1>']


httpd = make_server('', 8080, application)

print('Serving HTTP on port 8000...')
# 开始监听HTTP请求:
httpd.serve_forever()

 

python mysql connection

pymysql Import 


Import pymysql 
# database connection 
conn = pymysql.connect (Host = '' , Port = 3306 , the User = ' root ' , passwd = '' , db = ' S6 ' ) #DB: library name 
# create a cursor 
CUR = conn .cursor () 

# SQL = '' '
 # Create Table userinfo2 ( 
# a PRIMARY KEY the INT ID, 
# name VARCHAR ( 32 ), 
# password VARCHAR ( 32 ) 
#) 
# 
# ' ''
 # 
# cur.execute (SQL) 
# 
# cur.executemany("insert into userinfo2 values(%s,%s,%s)", [(1,"yuan","123"),
#                                                           (2,"alex","456"),
#                                                           (3,"egon","789")])


cur.execute("select * from userinfo2 WHERE NAME='yuan' AND PASSWORD ='123'"
conn.commit ())
# Submit
# Close pointer object 
cur.close () 
# close the connection object 
conn.Close ()

 

Guess you like

Origin www.cnblogs.com/lida585/p/10990622.html