jdango the basis of a framework

table of Contents

jdango framework

Software development architecture:

c / s architecture

b / s architecture (in essence, is c / s)

web backend

Demand
1. according to user input different suffixes to return different content
to obtain input from the user suffix data in line with the http protocol format
deficiencies
1.socket write our own code of
2.http also our own data processing
HTTP protocol

1. The four characteristics:

- based on a request response

- TCP / IP based protocol applied to the top of the application layer

- Stateless

This Agreement will be cleared as long as the end of the visit, next time, or access or the new state

- No connection

2. Data Format

Request format:

The first line of the request (request method, protocol version)
request headers (kv bunch of key-value pairs)

Intermediate blank line '

Request body

3. Response Status Code

With figures to show a bunch of suggestive information

Each company can define their own response status code

1XX: the server has successfully received the client's data is being processed, you can continue to submit

2XX: 200 requests the server has successfully returned data you want

3XX: Redirection (originally wanted to visit but inside A will automatically give you go above B)

4XX: 404 requested resource does not exist, you do not have the conditions 403 request the resource

5XX: 500 internal server error

Demand
1. Depending on the user input suffix return different content
acquisition suffix data conforms to the user input from the http protocol format

Inadequate

1.socket write our own code of
2.http also our own data processing

import socket


server = socket.socket()
server.bind(('127.0.0.1',8080))
server.listen(5)
"""
请求首行
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/75.0.3770.80 Safari/537.36\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
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
\r\n
请求体
'

"""

while True:
    conn, addr = server.accept()
    data = conn.recv(1024)
    conn.send(b'HTTP/1.1 200 OK\r\n\r\n')
    # print(data)
    data = data.decode('utf-8')  # bytes变成一串字符串
    target_url = data.split('\r\n')[0].split(' ')[1]
    # 判断url返回响应的内容即可
    if target_url == '/index':
        # conn.send(b'index')
        with open(r'D:\上海校区python13期视频\day49\01 demo.html','rb') as f:
            conn.send(f.read())
    elif target_url == '/login':
        conn.send(b'login')
    else:
        conn.send(b'404 error')
    conn.close()

3. Based on wsgiref module line and
according to different functions split into different files
the user in a browser window, enter the url been able to get to the appropriate resource
is already open because the back-end of the corresponding resource interface

基于wsgiref模块以及文件拆分的特点
    只要你想要开设新的资源
        1.先在urls文件中写url与函数的对应关系
        2.再去views文件中写对应的函数

urls.py:路由与视图函数的对应关系
views.py:里面就是放的一堆视图函数(视图函数可以是函数也可以是类)
templates文件夹:里面放的就是一堆html文件(模板文件夹)

Dynamic and static pages
static pages
of data are written in the same years dead
dynamic web
data is obtained dynamically
EG:
1. Get the current time
2. Get the data from the database

Demand
1. You give me time to write a correspondence between access immediately once the show is currently visiting

2.后端有一个用户字典 你需要将该字典传递给html页面 并且在该页面上还可以将传递过来的数据当成字典数据进行获取值的操作

jinja2 module
provides a code that can be written on the back end like python html page to manipulate data (template syntax)
PIP3 install jinja2
flask frame template syntax is jinja2 module, so you just the flask under the framework will automatically download jinja2

模板语法(jinja2模板语法非常贴近python语法 但是并不是所有的框架使用的都是jinja模板语法)
{{ xxx }}
<p>{{xxx.username}}</p>
<p>{{xxx['password']}}</p>
<p>{{xxx.get('hobby')}}</p>
<p>{{xxx.get('hobby')[0]}}</p>
<p>{{xxx.get('hobby').1}}</p>


​ {%for user_dict in xxx %}

​ {{ user_dict.id }}
​ {{ user_dict.name }}
​ {{ user_dict.hobby }}

​ {% endfor %}

Acquiring data in the database to display the front page

Based wsgiref module

from wsgiref.simple_server import make_server
from views import *  #*代表的是导入所有的信息
from urls import urls


def run(env,response):
    """
    :param env: 请求相关的所有数据
    :param response: 响应相关的所有数据
    :return: 浏览器能够接受的内容
    """
    response('200 OK',[])
    # print(env)  # 大字典  里面的PATH_INFO参数就是用户输入的后缀
    target_url = env.get('PATH_INFO')
    # if target_url == '/index':
    #     # 一堆逻辑判断
    #     return [b'index']
    # elif target_url == '/login':
    #     return [b'login']
    # 先定义一个变量 用来存储可能匹配到的函数名
    func = None
    # 1 for循环获取一个个的url与函数对应关系的元组
    for url in urls:  # url = (),(),()
        # 2 判断当前用户访问的url与元组第一个元素是否一致
        if target_url == url[0]:
            # 3 如果相等 说明有对应的后端逻辑代码 将匹配到的函数名赋值给func
            func = url[1]
            # 4 一旦用户匹配上了响应的url 应该立刻结束当前for循环了 因为没有意义
            break
    # 针对func是否有值 还需要判断
    if func:
        # 匹配上了  加括号直接调用
        res = func(env)
    else:
        # 匹配404逻辑代码
        res = error(env)
    return [res.encode('utf-8')]  # 这个里面的res是view里面返回的,返回函数的返回值给浏览器 并且编码成bytes


if __name__ == '__main__':
    server = make_server('127.0.0.1',8080,run)
    # 监听127.0.0.1:8080 一旦有客户端来访问 会立刻将make_server第三个参数加括号调用执行
    server.serve_forever()  # 启动服务端

urls

from views import *

urls = [
    ('/index',index),
    ('/login',login),
    ('/xxx',xxx),
    ('/get_time',get_time),
    ('/get_user',get_user),
    ('/get_info',get_info)
]

views

def index(env):
    return 'index'

def login(env):
    return 'login'

def error(env):
    return '404 error'


def xxx(env):
    return 'xxx'

import time
def get_time(env):
    # 该函数需要返回一个html页面
    current_time = time.strftime('%Y-%m-%d %X')
    # 文件操作 读取html文件
    with open(r'D:\上海校区python13期视频\day49\templates\02 get_time.html','r',encoding='utf-8') as f:
        data = f.read()  # html文件内容  字符串
    data = data.replace('gfdgsfdgfdsgsfdgsfdgsfdgsdg',current_time)  # 利用字符串的替换
    return data

from jinja2 import Template
def get_user(env):
    user_dict = {'username':'jason','password':123,'hobby':['read','study','run']}
    with open(r'D:\上海校区python13期视频\day49\templates\03 get_user.html','r',encoding='utf-8') as f:
        data = f.read()
    temp = Template(data)
    res = temp.render(xxx=user_dict)  # 将user_dict传递给html页面 在页面上通过变量名xxx就能够获取到user_dict
    return res


import pymysql
def get_info(env):
    conn= pymysql.connect(
        host= '127.0.0.1',
        port= 3306,
        user= 'root',
        password= '123',
        database= 'mydjango',
        charset= 'utf8',
        autocommit = True #自动提交给mysql确认

    )
    cursor= conn.cursor(cursor=pymysql.cursors.DictCursor)#产生一个游标对象
    #cursor= pymsql.cursors.DictCursor 将查询的结果 做一个字典的形式返回
    sql= 'select * from user_info'
    cursor.execute(sql)#执行sql语句
    data = cursor.fetchall()  #获取查询结果的所有数据
    ##结果是是[{} ,{},{}]
    #讲列表套字典的结果数据,直接传递给html的页面上
    with open(r'','r', encoding='utf-8') as f:
        res = f.read()
    #利用jinja2模块
    tmp= Template(res)
    #利用对象render的方法,将数据直接传递给html页面
    res= tmp.render(xxx=data)
    return res

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 href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
{{ xxx }}
<p>{{xxx.username}}</p>
<p>{{xxx['password']}}</p>
<p>{{xxx.get('hobby')}}</p>
<p>{{xxx.get('hobby')[0]}}</p>
<p>{{xxx.get('hobby').1}}</p>
</body>
</html>

get_info.hrml

<!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 href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h2 class="text-center">数据展示</h2>
        <div class="col-md-8 col-md-offset-2">
            <table class="table-hover table table-striped">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>username</th>
                        <th>hobby</th>
                    </tr>
                </thead>
                <tbody>
<!--                    xxx = [{},{},{},{}]-->
                {%for user_dict in xxx %}
                    <tr>
                        <td>{{ user_dict.id }}</td>
                        <td>{{ user_dict.name }}</td>
                        <td>{{ user_dict.hobby }}</td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
</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 href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
gfdgsfdgfdsgsfdgsfdgsfdgsdg
</body>
</html>

4. Display data in the database to obtain the front page

1. Routing and view function correspondence relationship
2. The view function
3. template folder
4. template syntax (is not recognized at the front end of the rear end of the implement)

web framework

python three mainstream web frameworks
django
large and carry their own special components and functions similar to a particularly large aircraft carrier
shortcomings: cumbersome
when you need to use a lot of features few other features
flask (more than 600 lines of source application context request context )
small but carry their own special special components and functions similar to the Rangers on less
though their third-party support but less functional module of the framework especially particularly
if you overlay all third-party modules flask up even more than django
deficiencies Department: limited to third-party modules

tornado
    异步非阻塞
    天然支持高并发 甚至可以用它来开发游戏服务器

django framework 1. Notes 1. The computer name can not have Chinese 2. project file name do not use Chinese 3. pycharm a separate window is a complete project 2. Version problem 1.X 2.X is recommended that you use version 1.X inside 1.11.09 - 1.11.13 If you've followed over the need to manually uninstall the previous version will be automatically re-install uninstall and then install 3. install pip3 install == 1.11.11 Django 4. test is installed successfully command line django-admin

















如何创建django项目
    1.命令行
        1.创建django项目
            django-admin startproject mysite(项目名)
            效果:创建一个mysite的文件夹
                mysite
                    -mysite
                        --__init__.py
                        --settings.py
                        --urls.py
                        --wsgi.py
                    -manage.py
        2.启动django项目(先切换到项目目录下)
            python3 manage.py runserver # django默认的端口号是8000
        
        3.创建具有独立功能的app  通常情况下应该做到建明制衣 
            python manage.py startapp app01
                app01
                    --migrations文件夹
                    --__init__.py
                    --admin.py
                    --apps.py
                    --models.py
                    --tests.py
                    --views.py


"" "
1. Use the command line to create a django project is not automatically created templates folder touch version you can manually create your own
2. command line django project not only failed to create templates folder configuration file does not fill in the path
and pycharm created automatically added
"" "

    2.pycharm快捷创建
        
app的概念
    application 应用
    django其实是一个专注于开发app的web框架
    一个空的django项目就类似于是一所大学
    app就类似于大学里面的各个学院
    每个app其实就类似于不同的功能模块
        购物网站
            用户相关 user
                用户相关的app
            订单相关 order
                订单相关的app
            投诉相关 tousu
                投诉相关的app
    不同的功能模块推荐使用不同的app去开发
    django支持多app


Do not use the python interpreter version 3.7
is recommended that you use 3.4 to 3.6

The main function django file
mysite
-mysite
- the init .py
--settings.py project profiles
--urls.py routing function correspondence between the view of the total project route
--wsgi.py
-manage.py
app01
--migrations folder database change record
---- the init .py
- the init .py
--admin.py Django Admin
--apps.py registered app related
--models.py model class (ORM)
--tests.py test file
--views .py view function (******)
app02
--migrations folder database change record
---- the init .py
- the init .py
--admin.py Django Admin
--apps.py registered app related
- -models.py model class (ORM)
--tests.py test file
--views.py view function (******)
db.sqlite3 Django comes with a small local database for test (data date format is not very sensitive)

Easy mistake
1. Code has not modified the effect
1. same port from a number of services have been running that service is the beginning of the
2. browser cache problem

************* After creating the app must be sure to register go to setting file **********
Django can automatically restart but its restart mechanism
whenever it detects your code there is a change in a certain time interval will automatically restart
it sometimes may appear that you have not written the code has been automatically restart

will be white django three axes
HttpResponse
return string
render
returned html pages and the data can be transmitted to the html page
rendering template (position data corresponding to a rear end placed in a template html syntax)

redirect
    重定向

def index(request):
    return HttpResponse('你好啊 小妹妹')


def login(request):
    return render(request,'login.html',{'user_dict':{'username':'jason','password':123},'userxxx':'hello world'})


def home(request):
    # return redirect('https://www.mzitu.com')
    return redirect('/index')

login.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 href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.js"></script>
</head>
<body>
<p>我的脑力正在不断的提高 非常棒的一件事情</p>
{{ user_dict }}
{{ user_dict.name }}


</body>
</html>

Guess you like

Origin www.cnblogs.com/bs2019/p/12153883.html