Django framework Introduction (1)

Handwriting web framework

# coding:utf8

import socket

server = socket.socket()
server.bind(('127.0.0.1', 8080))
server.listen(5)

# data 中的信息
"""
请求首行,表明请求方式以及遵循的http协议版本
b'GET / HTTP/1.1\r\n
请求头
Host: 127.0.0.1:8080\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 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36\r\n
Sec-Fetch-User: ?1\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\r\n
Sec-Fetch-Site: none\r\n
Sec-Fetch-Mode: navigate\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=aOZSalMQkKGbzstfjcw3O9sDoegdywL8AD7PzhidAyx3tXShN7oQtxN1MMnS6GVX\r\n
\r\n(******)
请求体

'
"""
while True:
    conn, addr = server.accept()  # 阻塞态
    data = conn.recv(1024)
    # print(data)
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    data_str = data.decode('utf-8')
    current_path = data_str.split('\r\n')[0].split(' ')[1]
    print(current_path)
    if current_path == '/index':
        # conn.send(b'index')
        with open(r'01 纯手撸的前端页面.html','rb') as f: # 基于网络传输,所以用'rb'
            conn.send(f.read())
    elif current_path == '/login':
        conn.send(b'login')
    else:
        conn.send(b'404 error')
    conn.close()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
    <h1>你好呀,大兄弟!</h1>
        <img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2973069531,657782944&fm=26&gp=0.jpg" alt="图片不存在!">

</body>
</html>

Write web server module framework based wsgiref

Write web-based third-party modules:
views.py put inside the pipe is a function of these functions we call the view function view layer
urls.py put inside routing (suffix) and the correspondence between the routing layer view function
templates folder inside put all html files

# 服务端web框架文件

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

def run(env,response):
    """
    :param env: 请求相关的所有数据 将http数据全部提前处理成了字典的形式 供调用者使用
    :param response: 响应相关的所有数据
    :return: 给前端真正的数据
    """
    # print(env)
    response('200 OK',[('xxx','liu'),])
    current_path = env.get('PATH_INFO')
    # print(current_path)
    # if current_path == '/index':
    #     return [b'index']
    # elif current_path == '/login':
    #     return [b'login']
    # 定义一个存储函数名的标志位
    func = None
    for url in urls:  # url =  ('/login',login)  ('/index',index)
        if current_path == url[0]:  # 用户敲的后缀名 你后端有对应的处理业务
            func = url[1]  # 将匹配上的函数名赋值给func变量
            break  # 一旦用户匹配上了对应的业务接口 立刻结束匹配
    # 判断func是否被赋值
    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()  # 启动服务端
<!--templates文件夹中的html文件-->
# xxx.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<h1>我是xxx页面</h1>
</body>
</html>

# get_time.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
sadadadasdsadsad
</body>
</html>
# get_user.html文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<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>
</body>
</html>

# get_data.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h2 class="text-center">数据展示</h2>
            <table class="table table-striped table-bordered table-hover">
                <thead>
                    <tr>
                        <th>idd</th>
                        <th>name</th>
                        <th>sex</th>
                        <th>age</th>
                        <th>hire_date</th>
                        <th>post</th>
                        <th>post_comment</th>
                        <th>salary</th>
                        <th>office</th>
                        <th>depart_id</th>
                    </tr>
                </thead>
                <tbody>
                    {% for user_dic in user_list %}
                        <tr>
                            <td>{{ user_dic.idd }}</td>
                            <td>{{ user_dic.name }}</td>
                            <td>{{ user_dic.sex }}</td>
                            <td>{{ user_dic.age }}</td>
                            <td>{{ user_dic.hire_date}}</td>
                            <td>{{ user_dic.post }}</td>
                            <td>{{ user_dic.post_comment }}</td>
                            <td>{{ user_dic.salary }}</td>
                            <td>{{ user_dic.office }}</td>
                            <td>{{ user_dic.depart_id }}</td>
                        </tr>
                    {% endfor %}
                </tbody>

            </table>
        </div>
    </div>
</div>
</body>
</html>
# view.py 文件

def login(env):
    return 'login'

def index(env):
    return 'index'

def reg(env):
    return 'reg'

def xxx(env):
    # return 'xxx'
    with open(r'G:\Python代码日常\day051 django\templates/xxl.html','r',encoding='utf-8') as f:
        return f.read()

def error(env):
    return '404 error'


import time
def get_time(env):
    ctime = time.strftime('%Y-%m-%d %X')
    # 后端数据 如何传递给html页面(利用字符串的替换)
    with open(r'G:\Python代码日常\day051 django\templates/get_time.html','r',encoding='utf-8') as f:
        data = f.read()
    data = data.replace('sadadadasdsadsad',ctime)
    return data


from jinja2 import Template
def get_userdict(env):
    user_dic = {'username':'jason','age':18,'hobby':['read','book','run']}
    with open(r'G:\Python代码日常\day051 django\templates/get_user.html','r',encoding='utf-8') as f:
        data = f.read()
    temp = Template(data)
    res = temp.render(userDic = user_dic)  # 将user_dic传递给html页面 页面上通过userDic就能够拿到后端传递过来的值
    return res

import pymysql
def get_data(env):
    conn = pymysql.connect(
        host = '127.0.0.1',
        port = 3306,
        user = 'root',
        password = '123',
        db = 'db3',
        charset = 'utf8',
        autocommit = True
    )
    cursor = conn.cursor(pymysql.cursors.DictCursor)  # 将查出来的数据组织成一个字典
    sql = "select * from userinfo"  # 关键性的数据 不要自己手动拼接
    affect_rows = cursor.execute(sql)  # sql注入:就是利用MySQL注释语法
    # print(affect_rows)
    user_list = cursor.fetchall()
    # print(user_list)
    # return 'hahahahha'
    with open(r'G:\Python代码日常\day051 django\templates/get_data.html','r',encoding='utf-8') as f:
        data = f.read()
    temp = Template(data)
    res = temp.render(user_list = user_list)
    return res
# urls.py

from views import *
urls = [
    ('/login',login),
    ('/index',index),
    ('/reg',reg),
    ('/xxx',xxx),
    ('/get_time',get_time),
    ('/get_userdict',get_userdict),
    ('/get_data',get_data),
]

Dynamic and static pages
static pages
of data is written to die the same years (even if it is man-made changes in the direct modification)
dynamic web
data is obtained in real time
EG:
1 dynamic back-end code to get the current time
2 data from the database query out

    题目1
        访问页面 页面上展示当前访问的时间
    
    题目2
        访问页面 页面上展示后端用户字典 并且在前端页面上可以
        利用一些简便的方式操作字典取值
        
jinja2模板语法
    专门用来处理后端数据与html页面的交互
    
    模板语法(极其贴近python后端语法)  
        让你能够在html页面上 也能够用后端python语法来操作后端传递过来的数据
    <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>
    
    {% for user_dic in user_list %}
        <tr>
            <td>{{ user_dic.id }}</td>
            <td>{{ user_dic.username }}</td>
            <td>{{ user_dic.password }}</td>
        </tr>
    {% endfor %}
    模板的渲染  将后端传递给html文件的数据  在后端处理好 生成一个完整的html文件的过程
    注意 模板的渲染是在后端完成的 跟前端没有关系

python three major framework

django large and built-in components and functions very, very much similar to the aircraft carrier
shortcomings: write small projects, they might be more cumbersome (overkill)

flask small but dapper own components and is particularly similar Ranger particularly little
substantially all rely on third-party components
deficiencies: limited to third-party modules relatively large impact
if the flask all third-party modules can be combined directly overshadowed django

tornado non-blocking asynchronous framework that can even be used to develop the game server

a: socket part
b: Match route
c: Template grammar

Django:
A use of someone else's wsgiref (django default)
b write their own
c himself wrote
the Flask:
A use of someone else's Werkzeug
b write their own
c with someone else's jinja2
Tornado:
A, b, c are to write their own of

django framework introduced

Precautions

        *1.计算机名称不能有中文
        2.python解释器不要使用3.7版本  推荐使用版本3.4~3.6,对Django兼容性比较好
        3.一个pycharm窗口 只能跑一个项目*

        django版本问题
                django版本以1.11.11为主(1.11.9~1.11.13)          

django download method

Method 1: pycharm settings installed

Second way: cmd installation

pip3 install django==1.11.11

如何检验django是否安装成功:
        命令行敲 django-admin

Django project and create the app

Command line to create project

1. Create a django project

django-admin startproject project name (eg mysite)

2. Start django project

Switch to the project folder
python3 manage.py the runserver
python3 manage.py the runserver 127.0.0.1:8080

3. Create application (django support multi-app development)

​ python3 manage.py startapp app01

Note:
1. does not automatically help you create templates folder
2. configuration file does not automatically help you write templates file path

pycharm create project

Method One: FILE >>> new project select the second Django, named after the project name when the name can not be a Chinese
creation app, add the name of the application in the Application, the direct creation projects and applications; can not be added manually created late application.

Method Two: Open the menu bar Tools >>> run manage task function bar to create projects and applications

Creating good app requires registration to take effect in django profile

He stressed:
1. Django must ensure that only a running state
2. debug Django project, must remember to clear your browser's cache (if the page does not achieve the desired effect debugging of code changed)
browser page right: Check the "network" Settings "Preferences" Network "Disable cache ( while DevTools is open) check mark;

3. If you think about using Django's default port can make changes to the method as shown below:

app concept

django is a main function to develop app for the web framework
app is the application application means
a django project is a university (empty shelves does not have any function), while the app is similar to the inside of each University;
an empty django does not have any environmental effect is merely to improve pre-configured for the app

You can develop according to different functions of multiple app
a app corresponds to a specific function module
user related functions associated with the user app
order-related order-related function app
commodity-related functions related merchandise app
each app has its own independent Features





The main document describes Django

Applications folder (App)
Migrations database records related to migrate data
adnin.py django backend management-related
models.py model table associated
views.py view related functions

Project name
settings.py profile
urls.py routing and mapping between the view function
all html files used in the project templates folder
manage.py django file entrance Django base will be three functions from django .shortcuts import HttpResponse, render, redirect


HttpResponse
inside pass a string parameter and returns to the browser.

# views.py
def index(request):
    # 业务逻辑代码
    return HttpResponse("你好,世界!")
# urls.py

from firstapp import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),  # 添加对应的功能函数
]
# 启动服务端:Starting development server at http://127.0.0.1:9999/
# 在浏览器页面用 http://127.0.0.1:9999/index/连接服务端,将index函数内部字符串渲染到浏览器页面上。

render
addition to also accept a request parameter to be rendered template file and save a data dictionary specific parameters.
The data filled in the template file, and finally return the result to the browser. (Similar to what we used above jinja2)

# views.py
def reg(request):
     user_dic = {'username':'zhang','password':123}
    #  下面两种方法都可以
    return render(request,'reg.html',local())  # 拿到reg函数内部所有的局部变量,在html文件内部可以根据模板语法选择你要渲染到前端页面上的变量。
    # return render(request,'reg.html',{'user_dic':user_dic})
# urls.py
from firstapp import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^reg/', views.reg),
]
# templates 文件夹建立 reg.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
<form action="" class="form-control">
    <label for="">username:<input type="text"></label>
    <label for="">password<input type="text"></label>
    <input type="submit" class="提交">
    {{ user_dic }}
    <div>{{user_dic.username }}</div>
    <div>{{ user_dic.password }}</div>  # 只支持点的方式,不支持字典的取值方式
</body>
</form>
</body>
</html>
# 启动服务端:Starting development server at http://127.0.0.1:9999/# 在浏览器页面用 http://127.0.0.1:9999/reg/连接服务端,将reg函数内部reg.html 文件渲染到浏览器页面上。

redirect (redirect)
accepts a URL parameter that indicates a jump to the specified URL (current page jumps).

1) can be written path suffix of this site;

2) can also write the full path, namely: Any web page address.

# views.py
def login(request):
    # return redirect('http://www.baidu.com') # 访问login后缀名,重定向到百度网址
    return redirect('/reg') # 本网站的后缀名


# urls.py
from firstapp import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^reg/', views.reg),
    url(r'^login/', views.login),
]
# 启动服务端:Starting development server at http://127.0.0.1:9999/# 在浏览器页面用 http://127.0.0.1:9999/login/连接服务端,按照login函数内部redirect指定的网址跳转,或者路径=后缀。

Note: Django can automatically identify changes to your code, there is no need to restart the server, but sometimes identify relatively slow, it is best to manually re-start, you can refresh a few times the browser page

Guess you like

Origin www.cnblogs.com/zhangchaocoming/p/11909399.html