"Python Basics" Web Application Programming

  • CS, Client/Server client upgrade is troublesome;
  • BS,Browser/Server;

In addition to heavyweight software such as Office, PSetc., most of the software is Webprovided in the form, such as Sina News, Blog, Weibo, etc.;

Webstages of development

  1. For static web pages, each modification of the page is directly saved by manually modifying the HTML source file, which cannot handle interaction;
  2. CGI, Common Gateway Interface, used to process dynamic data sent by users (written in C/C++);
  3. ASP/JSP/PHP, the scripting language has high development efficiency and is closely integrated with HTML, quickly replacing the low-level language CGI;
  4. MVC, in order to solve the problem of poor maintainability caused by directly using scripting language to check in HTML, the Web application Model-View-Controllerintroduces the mode to simplify Web development;
  5. At present, asynchronous development, MVVM front-end technology emerges in an endless stream;

1. Introduction to HTTP protocol

HTTP/1.1 version allows multiple HTTP requests to multiplex a TCPconnection;

1. HTTP request

Request-response mode, one request only processes one response;

  1. The client must first send a request to the server, and the request includes;
  • Type: GET, POST, DELETE...
  • Path: /full/url/path
  • Domain name: www.sina.com.cn
  • Other Headers
  • If it is POST, the request also includes a Body
  1. The server wants the client to return an HTTP response, the response includes;
  • Response code: 200 success, 3XX redirection, 4XX request error, 5XX server processing request error
  • Response type: specified by Content-Type
  • Other Headers
  • Body: Contains the content of the response, the HTML source code of the web page, etc.
  1. If the returned content also contains other HTTP requests, repeat 1.2;

2. HTTP format

  • For each Headerline, multiple Headerlines are separated by a newline character '\r\n';
  • HeaderSplit with Bodytwo '\r\n';
  • BodyThe data type is determined Content-Typeby the header ;
  • Content-EncodingSpecify the compression method;

2. Introduction to HTML

HTML defines a set of grammatical rules to tell browsers how to display web pages;

The HTML document is composed of a series of Tags, the outermost Tag is <html>, and the specification should include <head>...</head>and <body>...</body>;

HTML is a rich document model, so there are a series of Tags used to represent links, pictures, tables, forms, etc.;

1. CSS

Cascading Style SheetsCascading style sheets, used to control the presentation of all elements in HTML;

2. JavaScript

Added to make HTML interactive, can be embedded in HTML, or externally linked to HTML;

Proficiency in HTML, CSS, JavaScript is a must for a good web developer

3. WSGI interface

Web Server Gateway Interface

A Python standard interface for receiving HTTP requests, parsing HTTP requests, and sending HTTP responses, and is a bridge between the Web server or gateway and the Web business or framework;

No matter how complex the web application is, the entry point is a WSGI processing function. All the input information of the HTTP request is obtained environ, the HTTP response is start_response()output Header, and the function return value is output Body;

1. Implement the WSGI interface

def application(environ, start_response):
    start_response('200 oK', [('Content-Type', 'text/html')])
    body = f"<h1>Hello, {
      
      environ['PATH_INFO'][1:] or 'web'}!</h1>"
    return [body.encode('utf-8')]
  • environA dict object containing all HTTP request information;
  • start_responseA function to send an HTTP response, which can only be sent once, see the above example for the format;
  • returnBody of HTTP response, bytes;

2. Run WSGI

Python has a built-in WSGI server module wsgiref, a reference example written in pure Python, which fully complies with the WSGI standard, regardless of the running effect, and is only used for development and testing;

from wsgiref.simple_server import make_server

# 创建一个服务器,IP地址为空,端口是 8000,处理函数是 application
httpd = make_server('', 8000, application)
print('Serving HTTP on port 8000...')
# 开始监听HTTP 请求
httpd.serve_forever()

4. Using web frameworks

In the face of different requests from the customer service end, if you use WSGI, you need to environmake different processing logics for different information, such codes are difficult to maintain;

The web framework is responsible for URLmapping to functions and parsing the parameters of HTTP requests, so that we can focus on one function to process one URL;

1. Flask

Python's most popular web framework;

Install

pip install flask

example

from flask import Flask
from flask import request

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    return '<h1>Home</h1>'


@app.route('/signin', methods=['GET'])
def signin_form():
    return '''<form action="/signin" method="post">
              <p><input name="username"></p>
              <p><input name="password" type="password"></p>
              <p><button type="submit">Sign In</button></p>
              </form>'''


@app.route('/signin', methods=['POST'])
def signin():
    # 需要从request对象读取表单内容:
    if request.form['username'] == 'admin' and request.form[
            'password'] == 'password':
        return '<h3>Hello, admin!</h3>'
    return '<h3>Bad username or password.</h3>'


if __name__ == "__main__":
    app.run()

URLFlask associates and functions through decorators , and request.form['name']obtains form content;

Flask's own server (for debugging) port is 5000;

2. Other web frameworks

  • DjangoJ
  • web.pysmall
  • BottleSimilar to Flask
  • Tornadoasynchronous

5. Using Templates

Separate the Python code and HTML code, and put all the HTML code in the template;

1. MVC

Model-View-Controller

ControllerFunctions that process URLs, responsible for business logic;

ViewThe .html template page is responsible for the display logic, and finally outputs the HTML seen by the user through simple variable replacement;

ModelVariables used to pass to View for replacement;

2. Jinja2

Install

$ pip install janja2

example

from flask import Flask, request, render_template

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    # 使用模板: ./templates/home.html
    return render_template('home.html')


@app.route('/signin', methods=['GET'])
def signin_form():
    return render_template('form.html')


@app.route('/signin', methods=['POST'])
def signin():
    # 需要从request对象读取表单内容:
    username = request.form['username']
    password = request.form['password']
    if username == 'admin' and password == 'password':
        return render_template('signin-ok.html', username=username)
    return render_template('form.html',
                           message='Bad username or password',
                           username=username)

Flaskrender_templates()Realize the rendering of the template through the function;

{ { name }}Indicates a variable that needs to be replaced;

{% ... %}Indicates instructions such as loops and conditional judgments;

3. Other Templates

  • Mako, <% ... %> and ${xxx}
  • Cheetah, <% ... %> and ${xxx}
  • Django, {% ... %} and { { xxx }}

PS: Welcome friends from all walks of life 阅读, 评论thank you friends 点赞, 关注, 收藏!

Guess you like

Origin blog.csdn.net/ChaoMing_H/article/details/129578284