1121 Class Summary

Static and dynamic pages

  • Static pages

    Static pages are simply using HTML or XML to write, modify data are artificial.

  • dynamic webpages

    Dynamic pages are combined with other languages, such as: HTML + ASP or HTML + ASP.NET or HTML + PHP or HTML + JSP, etc.

    Data are acquired or dynamically retrieved from a database.

Three major Python Web framework

All web applications is essentially a socket server, while the user's browser is a client socket.

They can achieve a simple web framework, receives the HTTP request, response HTTP request, but it may be easier to use web framework.

python web frameworks in the mainstream, there are three:

django

Large frame, built-in components and functions very much

Deficiencies to the powerful features: relatively heavy

  • socket portion with a third-party server module wsgiref
  • Routing layer to achieve their own
  • Template syntax to achieve their own

flask

Dapper, comes with very few components

Substantially all depends on third-party components, subject to third-party components

If the flask all third-party modules together, overshadowed django

  • Third-party server module werkzeug socket portion with
  • Routing layer to achieve their own
  • Template syntax use third-party modules Jinja2

tornado

A non-blocking asynchronous framework that can be used to develop the game server, the efficiency is very high.

  • socket server to achieve their own
  • Routing layer to achieve their own
  • Template syntax to achieve their own

wsgiref module

web application process, if implemented by our own complex, receives an HTTP request, parse the HTTP request, response HTTP request and so on. Often these operations are controlled by WSGI server to complete, WSGI (Web Server Gateway Interface) defines the interface WSGI server performs, we only need to write service WSGI interface specification, and then executed by WSGI server on it.

from wsgiref.simple_server import make_server
from urls import urls
from views import *

def run(env,response):
    """
    :param env: 请求相关的所有数据 将http数据全部提前处理成了字典的形式 供调用者使用
    :param response: 响应相关的所有数据
    :return: 给前端真正的数据
    """
    response('200 OK',[('xxx','jason'),])
    current_path = env.get('PATH_INFO')
  
    func = None
    for url in urls: 
        if current_path == url[0]:  # 用户敲的后缀名 你后端有对应的处理业务
            func = url[1]  # 将匹配上的函数名赋值给func变量
            break  # 一旦用户匹配上了对应的业务接口 立刻结束匹配

    if func:
        res = func(env)
    else:
        res = error(env)
    return [res.encode('utf-8'),]


if __name__ == '__main__':
    server = make_server('127.0.0.1',8080,run)  # 实时监听本机8080端口
    # 一旦有请求来了 会统一交给run函数处理(调用run函数并传参run(env,response))
    server.serve_forever()  # 启动服务端

jinja2 module

Jinja2 is designed to handle interaction with back-end data html page. jinja2 template syntax, grammar extremely close to the python backend, allowing users on the html page, can also be used to operate the rear end of the rear end of python syntax to pass over data

Note: render template is to pass to the back-end data html file, in the back-end deal, the process of generating a complete html file, which is done in the backend, nothing to do with the front end

# jinja2的字典取值方式
<p>{{ userDic }}</p>
<p>{{ userDic.username }}</p>
<p>{{ userDic['age'] }}</p>
<p>{{ userDic.get('hobby') }}</p>
<p>{{ userDic.get('hobby').0 }}</p>
<p>{{ userDic.get('hobby').1 }}</p>
<p>{{ userDic.get('hobby').2 }}</p>


# jinja2的for循环
{% for user_dic in user_list %}
    <tr>
    <td>{{ user_dic.id }}</td>
    <td>{{ user_dic.username }}</td>
    <td>{{ user_dic.password }}</td>
    </tr>
{% endfor %}

Django

Create a Django project

Note Before you install Django:

  1. The computer name can not have Chinese
  2. Do not use the python interpreter version 3.7 is recommended to use version 3.4 to 3.6
  3. A pycharm window can only run a project
  4. Try to install the stable version, this tutorial will be mainly 1.11.11.

Command line to create

  1. Install Django
    pip3 install django

  2. Switch to the right path, create a django project
    django-admin startproject 项目名(例如mysite)

  3. Switch to the project folder, start django project
    python3 manage.py runserveror
    python3 manage.py runserver 127.0.0.1:8080

  4. Create an application (django support multi-app development)
    python3 manage.py startapp app名(例如app01)

    Create a project with the command line Note:

    1. It will not automatically help you create templates folder
    2. Configuration file does not automatically help you write templates file path

Creating pycharm

  1. Install Django

    Settings-project interpreter directly install Django

    Or statementpip install django

  2. New Project

setting configuration file:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',       # 如果新建的app没有,这里要加上
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,"templates")],   # 如果这里的路径是空的,要手动加
        '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',
            ],
        },
    },
]

Django Contents Introduction

mysite/
├── manage.py  # 管理文件
└── mysite  # 项目目录
    ├── __init__.py
    ├── settings.py  # 配置
    ├── urls.py  # 路由 --> URL和函数的对应关系
    └── wsgi.py  # runserver命令就使用wsgiref模块做简单的web server
└── app01  # 应用目录
    ├── __init__.py
    ├── admin.py   # django admin后台管理
    ├── apps.py    # 放所有app的逻辑函数
    ├── models.py  # 放所有数据库相关的模型类
    ├── tests.py   # 存放测试文件
    └── views.py   # 处理业务逻辑的视图函数
  

Run Django project

python manage.py runserver 127.0.0.1:8000

Django basis of three tricks

from django.shortcuts import HttpResponse,render,redirect

HttpResponse

Internal parameters passed in a string will be returned to the browser

E.g:

def index(request):
    # 业务逻辑代码
    return HttpResponse("正常访问了")

render

Receiving a plurality of parameters can be

The first parameter receiving a request

The second parameter to be rendered to fill in a template file (html file)

The third parameter write a save specific data dictionary

Meaning that the data filled in the template file, and finally return the result to the browser, similar to Jinja2 template, note template syntax reder here used in html file using dictionary syntax value python, the python is the back-end processing after completing and then sent to html, and finally return the result to the browser.

E.g:

def index(request):
    # 业务逻辑代码
    return render(request,"index,html",{"name":"qinyj","hobby":["run","jump"]})

redirect

Receiving a URL parameter, meaning that can be redirected to the specified URL address

E.g:

def index(request):
    # 业务逻辑代码
    return redirect("https://www.baidu.com")

Guess you like

Origin www.cnblogs.com/faye12/p/11907806.html