python day18

Posted A+

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python day18相关的知识,希望对你有一定的参考价值。

 

Web框架
    请求周期
    处理用户请求       放置html模版        操作数据库
    Controllers         Views               Modals
   
      Views             Template            Modals
   
    MVC/MTV
   
   
    Django => MTV   
   
Django       
    1.安装
        pip3 install Django==1.10    或  pip3 install Django
       
    2.创建project
        django-admin.py startproject mysite
        目录结构
            mysite  
                mysite   
                    - settings.py    # 配置文件
                    - urls.py          # 路由系统(调度)
                    - wsgi.py         # WSGI
                managel.py              # django程序启动文件
       
    3.创建APP
        所有APP共享project
            cd mysite
            python3 manage.py startapp cmdb
       
        cmdb
            __init__.py
            admin.py            # WEB后台管理
            apps.py                # 当前app配置文件
            models.py            # 数据库管理,自动创建数据结构
            tests.py            # 单元测试,测试你的某个功能
            views.py            # 业务请求处理
           
       
       
   
    4.编写代码
        urls.py
        views.py
            (1) 配置路由关系  urls.py
            urls.py       
                from cmdb import views                                 #导入views模块
                urlpatterns = [
                    # url(r\'^admin/\', admin.site.urls),   
                    url(r\'^index/\', views.index),                      # 配置映射关系,逗号前是url,逗号后为交给某一函数(view模块的index函数)
                ]
           
            (2) 配置业务请求处理 views.py
            views.py  创建对应自己的函数
                cmdb  的 views 处理用户请求,必须为函数
                    from django.shortcuts import HttpResponse          # 导入处理模块
                    # Create your views here.
                    # 处理用户请求
                    def index(request):                                   # 处理函数,用户请求放入request中
                        return HttpResponse(\'123\')                  # 处理字符串,必须放在HttpResponse才能识别
       
    5.启动Django程序
        python3 manage.py runserver 8000
        python manage.py runserver  #测试  启动web服务器,只允许本地访问
        python manage.py runserver 0.0.0.0:8080  #允许所有
       
       
       
    6.访问
        http://127.0.0.1:8000/index/
       
       
       
    7.使用模板
        settings配置
            指定Template目录,告诉django配置文件在那里
        render传递数据给html (request,\'路径\')
       
        (1)    Template                    # 放置HTML模版,可新建
                index.html                # 手动创建
                    <!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <title>Title</title>
                    </head>
                    <body>
                        <h1 style="color: red">123</h1>
                    </body>
                    </html>
           
        (2)    views           #配置业务请求处理,指定html文件,在cmdb目录下
                from django.shortcuts import render
                def index(request):
                # return HttpResponse(\'123\')
                return render(request,\'index.html\')       #使用render方法指定html
           
       
        (3) 启动并访问
            python manage.py runserver 0.0.0.0:8080
            http://127.0.0.1:8000/index/
   
   
    8. 静态文件配置
        (1) statics             # 手动创建,在mysite主目录创建
            jquery-1.8.2.min.js     # 存入jquery文件
       
        (2) index.html 指定statics
            <script src="/statics/jquery-1.8.2.min.js"></script>
       
        (3) settings 指定statics,在文件最后添加
            (1) 指定静态文件目录
                STATICFILES_DIRS = (
                    os.path.join(BASE_DIR,\'statics\'),
                )
                       
            (2)    指定HTML引用静态文件的前缀,可选项,非必选
                STATIC_URL = \'/fff/\'        #指定前缀为fff

        (4) index.html 引用前缀
            <script src="/fff/jquery-1.8.2.min.js"></script>
           
        (5) 访问
            F12 --- Elements----/fff/jquery-1.1.8.2.min.js----右键---open link in new tab打开成功即可
           

                   
    9.表单操作及页面展示(内存版)
        (1)表单页面
            <body>
                <h1>用户输入:</h1>
                {#以POST方式提交#}
                <form action="/index/" method="POST">
                    <input type="text" name="user"/>
                    <input type="test" name="email"/>
                    <input type="submit" value="提交"/>
                </form>
            </body>
       
       
        (2)views处理
            # 判断用户是否是POST请求
            from django.shortcuts import render
            from django.shortcuts import HttpResponse
            # Create your views here.

            def index(request):
                # return HttpResponse(\'123\')
                # 判断
                if (request.method == \'POST\'):
                    user = request.POST.get(\'user\', None)
                    email = request.POST.get(\'email\', None)
                    print(user, email)
                return render(request,\'index.html\')
           
            直接访问会提交会报错,是DJANGO提供的跨站请求伪造,可以通过settings修改处理
                Forbidden (403)
                CSRF verification failed. Request aborted.
           
           
           
        (3)settings修改
            MIDDLEWARE 或 MIDDLEWARE-CLASSES 列表注释掉 django.middleware.csrf.CsrfViewMiddleware 这一行
                MIDDLEWARE = [
                    \'django.middleware.security.SecurityMiddleware\',
                    \'django.contrib.sessions.middleware.SessionMiddleware\',
                    \'django.middleware.common.CommonMiddleware\',
                    # \'django.middleware.csrf.CsrfViewMiddleware\',           
                    \'django.contrib.auth.middleware.AuthenticationMiddleware\',
                    \'django.contrib.messages.middleware.MessageMiddleware\',
                    \'django.middleware.clickjacking.XFrameOptionsMiddleware\',
                ]
                               
        (4)页面提交
            提交内容为   123 123
            后台接收到数据
                123 123
                [31/Aug/2016 23:13:28] "POST /index/ HTTP/1.1" 200 339
           
           
           
        (5)数据展示
            (1)views 处理数据   
                from django.shortcuts import render
                from django.shortcuts import HttpResponse
                # 1. 处理用户请求   u1和e1为两列,u1和u2为两行
                USER_INPUT = [
                    {\'user\':\'u1\', \'email\': \'e1\'},
                    {\'user\':\'u2\', \'email\': \'e2\'},
                ]


                def index(request):
                    # ...
                    # 判断用户是否是POST请求
                    if(request.method == \'POST\'):
                        user = request.POST.get(\'user\',None)
                        email = request.POST.get(\'email\',None)
                        temp = {\'user\': user, \'email\': email}
                        USER_INPUT.append(temp)             # 2. 追加到列表
                        # request.POST.get(\'pwd\',None)

                    # return HttpResponse(\'123\')
                    # 模版引擎
                    # 获取index.html模版 + {\'data\': USER_INPUT } ==》 渲染
                    # 字符串

                    #传递给HTML
                    return render(request, \'index.html\', {\'data\': USER_INPUT })       # 3. 传递给HTML使用data指定USER_INPUT列表
                           
           
           
            (2)HTML 编写代码,按django方式对数据进行for循环生成列表(取的是views里的data和USER_INPUT数据)
                django的for循环必须有开始有结束{% for item in data %}, {% endfor %}
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Title</title>
                </head>
                <body>
                    <h1>用户输入:</h1>
                    {#以POST方式提交#}
                    <form action="/index/" method="POST">
                        <input type="text" name="user"/>
                        <input type="test" name="email"/>
                        <input type="submit" value="提交"/>
                    </form>

                    <h1>数据展示:</h1>
                   
                    <table border="1">
                        {% for item in data %}
                        {# tr为行,td为列#}
                            <tr>
                                <td>{{ item.user }}</td>
                                <td>{{ item.email }}</td>
                            </tr>
                        {% endfor %}
                    </table>
                   
                    <script src="/fff/jquery-1.8.2.min.js"></script>
                   
                </body>
                </html>
           
               
                页面初始列表样式
                    ----
                   |u1|e1|
                   |---|
                   |u2|e2|
                    ----   
               
           
            (3)提交数据到内存,输入内容后提交后在表格显示
                http://127.0.0.1:8000/index/
           
           
    10.连接数据库
        默认使用sqlite数据库
        ORM  数据结构管理  models.py
        settings
       
       
        (1)models.py       #配置数据库,创建类,生成数据库UserInfo表,指定字符长度
            class UserInfo(models.Model):
                user = models.CharField(max_length=32)
                email = models.CharField(max_length=32)
               
        (2)注册app:
            settings.py    # 指定APP名字
                INSTALLED_APPS = [
                    \'django.contrib.admin\',
                    \'django.contrib.auth\',
                    \'django.contrib.contenttypes\',
                    \'django.contrib.sessions\',
                    \'django.contrib.messages\',
                    \'django.contrib.staticfiles\',
                    \'cmdb\',                          
                ]
       
        (3)执行命令,创建库和表
            python3 manage.py makemigrations
            python3 manage.py migrate
            两条命令完自动创建UserInfo表
           
            返回结果:
                makemigrations返回结果
                    Migrations for \'cmdb\':
                    cmdb\\migrations\\0001_initial.py:
                    - Create model UserInfo
                migrate返回结果
                    Applying cmdb.0001_initial... OK
                    Applying sessions.0001_initial... OK
                   
                   
    11.操作数据库   
        创建:
            models.类.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
            models.UserInfo.objects.create(user=u,email=e)
        获取:
            models.类.objects.all()
            models.UserInfo.objects.all()
   
   
   
        (1)views 处理
            from django.shortcuts import render
            from django.shortcuts import HttpResponse
            from django.shortcuts import redirect
            from cmdb import models                                                  # 1.导入models数据库模块
            # 处理用户请求

            def index(request):
                # ...
                # 判断用户是否是POST请求
                # return redirect(\'http://baidu.com\')
                # return redirect(\'\')
                if(request.method == \'POST\'):
                    u = request.POST.get(\'user\',None)
                    e = request.POST.get(\'email\',None)
                    models.UserInfo.objects.create(user=u,email=e)                   # 2. Post提交数据,使数据库出现内容
                    # request.POST.get(\'pwd\',None)

                # return HttpResponse(\'123\')
                # 模版引擎
                # 获取index.html模版 + {\'data\': USER_INPUT } ==》 渲染
                # 字符串

                data_list = models.UserInfo.objects.all()                            # 3. 取UserInfo表数据,get取数据,对于ORM每一行数据都是它的对像
                # [UserInfo对象,UserInfo对象,。。。]   每一行数据里都是一个对像
                # for item in data_list:
                #     print(item.user,item.email)
                #传递给HTML
                return render(request, \'index.html\', {\'data\': data_list })           # 4. 传递给HTML使用data_list指定USER_INPUT列表

       
        (2)HTML文件
            index.html  循环data_list,取每一行对像数据
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title></title>
                </head>
                <body>
                    <h1>用户输入:</h1>
                    <form action="/index/" method="POST">
                        <input type="text" name="user" />
                        <input type="text" name="email" />
                        <input type="submit" value="提交" />
                    </form>

                    <h1>数据展示:</h1>

                    <table border="1">
                        <tr>
                            <th>用户名</th>
                            <th>邮箱</th>
                        </tr>
                        {% for line in data %}
                            <tr>
                                <td>{{ line.user }}</td>
                                <td>{{ line.email }}</td>
                            </tr>
                        {% endfor %}
                    </table>


                    <script src="/fff/jquery-1.8.2.min.js"></script>
                </body>
                </html>
           
       
        (3)访问提交数据到库
            http://127.0.0.1:8000/index/
       
       
       
       
       
       
       
django-admin.py startproject mysite


python3 manage.py startapp app1

一、路由系统     
二级页面      对应urls函数
urls.py       views.py    

from app1  import views


1.  配置路由系统urls.py

from app1  import views

urlpatterns = [
    # url(r\'^admin/\', admin.site.urls),
    url(r\'^index/\', views.f1),
    url(r\'^login/\', views.login),
    url(r\'^detail/(\\d+)/\', views.detail),
    url(r\'^detail2/(\\d+)/(\\d+)/\', views.detail2),
    url(r\'^detail2/(?P<p1>\\d+)/(?P<x2>\\d+)/\', views.detail3),
]

 

2. 业务处理 views.py


from django.shortcuts import HttpResponse

def f1(request):
    return HttpResponse(\'OK\')

def login(request):
    return HttpResponse(\'OK\')


def detail(request,nid):
    print(nid)
    return HttpResponse(\'OK\')


# detail2(1,2)
def detail2(request,xid,nnid):
    print(xid,nnid)
    return HttpResponse(\'OK\')

# detail3(x2=234,p1=123)
def detail3(request,p1,x2):
    print(p1,x2)
    return HttpResponse(\'OK\')

 

3.页面访问

http://127.0.0.1:8000/login/
http://127.0.0.1:8000/detail/123/
http://127.0.0.1:8000/detail2/123/12313/

 

 

 

 

 

分页查看,资源信息管理


   
1.路由系统
   
--------urls.py

from app1  import views

urlpatterns = [
    # url(r\'^admin/\', admin.site.urls),
    # url(r\'^index/\', views.f1),
    # url(r\'^login/\', views.login),
    # url(r\'^detail/(\\d+)/\', views.detail),
    # url(r\'^detail2/(\\d+)/(\\d+)/\', views.detail2),
    # url(r\'^detail3/(?P<p1>\\d+)/(?P<x2>\\d+)/\', views.detail3),
    url(r\'^index/(\\d+)/\', views.index),
    url(r\'^detail/(\\d+)/\', views.detail),
]

 


2.业务函数处理

-------views.py  

USER_LIST = []
for item in range(94):
    temp = {"id":item,\'username\':\'alex\'+str(item),\'email\':\'email\'+str(item)}
    USER_LIST.append(temp)

def index(request,page):
    print(page)
     # 1,0-9
     # 2,10-19
     # 3,20-29
    page = int(page)
    start = (page-1) * 10
    end = page * 10
    user_list = USER_LIST[start:end]
    # return HttpResponse(\'OK\')
    return render(request,\'index.html\',{\'user_list\':user_list})


def detail(request,nid):
    nid = int(nid)
    current_detail_dict = USER_LIST[nid]
    return render(request,\'detail.html\',{\'current_detail_dict\':current_detail_dict})

 

 

 

 


3.两个html

--------index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <table>
        <tr>
            <td>ID</td>
            <td>用户名</td>
            <td>详细</td>
        </tr>
        {% for item in user_list %}
            <tr>
                <td>{{ item.id }}</td>
                <td>{{ item.username }}</td>
                <td><a href="/detail/{{ item.id }}/">查看详细</a></td>
            </tr>
        {% endfor %}
    </table>
</body>
</html>

 

 

 


--------detail.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <ul>
        <li>
            {{ current_detail_dict.id }}
        </li>
        <li>
            {{ current_detail_dict.username }}
        </li>
         <li>
            {{ current_detail_dict.email }}
        </li>
    </ul>
</body>
</html>

 

 

 

 

4. 页面访问

http://127.0.0.1:8000/index/1/   或 http://127.0.0.1:8000/index/22/


ID    用户名    详细
0    alex0    查看详细
1    alex1    查看详细
2    alex2    查看详细
3    alex3    查看详细
4    alex4    查看详细
5    alex5    查看详细
6    alex6    查看详细
7    alex7    查看详细
8    alex8    查看详细
9    alex9    查看详细

点击“详细信息”

http://127.0.0.1:8000/detail/0/

0
alex0
email0

 

 


自定义方法
    filter                  # 过滤
    simple_tag                # 帮助标签
   

   
    1.创建指定文件,名称不能改 templatetags
    2.创建任意.py 文件,如:xx.py
        from django import template
        from django.utils.safestring import mark_safe
        # from django.template.base import resolve_variable,Node,TemplateSyntaxError
        # from django.template.base import Node,TemplateSyntaxError
       
        # 必须不变
        register = template.Library()

        # 创建函数
        @register.filter
        def f1(value,arg):
            return value + "666" + arg


        @register.simple_tag
        def f2(s1,s2,s3,s4):
            return s1 + s2 + s3 + s4


        @register.filter
        def f3(value):
            if value == \'VVV\':
                return True
            return False

    3.在html模板头部执行
        加入此内容   {% load xx %}
    mysite/template.html
        {% load xx %}
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
            {{ k1 }}
            {{ k2.1 }}

            {% for item in k2 %}
                <p>{{ item }},{{ forloop.counter }},{{ forloop.counter0 }},{{ forloop.first }},{{ forloop.last }},{{ forloop.revcounter }}</p>
            {% endfor %}

            {% if k1 == \'v1\' %}
                <h1>V1</h1>
            {% elif k1 == \'v2\' %}
                <h1>V2</h1>
            {% else %}
                <h1>7777</h1>
            {% endif %}
            {{ k1 }}
            {{ k1|lower }}
            {{ k1|f1:"alex" }}
            {%  if k1|f3 %}
                <h1>True</h1>
            {% else %}
                <h1>False</h1>
            {% endif %}
        </body>
        </html>

    4. setting.py 中注册app
        INSTALLED_APPS = [
            \'django.contrib.admin\',
            \'django.contrib.auth\',
            \'django.contrib.contenttypes\',
            \'django.contrib.sessions\',
            \'django.contrib.messages\',
            \'django.contrib.staticfiles\',
            \'app1\'
        ]


    5. views.py
        from django import template
        from django.utils.safestring import mark_safe
        # from django.template.base import resolve_variable,Node,TemplateSyntaxError
        from django.template.base import Node,TemplateSyntaxError

        register = template.Library()

        @register.filter
        def f1(value, arg):
            return value + "666" + arg

        @register.simple_tag
        def f2(s1,s2,s3, s4):
            return s1 + s2 + s3 + s4

        @register.filter
        def f3(value):
            if value == \'VVV\':
                return True
            return False

        @register.simple_tag
        def f4(value):
            if value == \'VVV\':
                return True
            return False

 


    6.app1创建urls.py
        from django.conf.urls import url
        from django.contrib import admin

        #路由系统
        from app1 import views

        urlpatterns = [
            # url(r\'^index/(\\d+)/\', views.index),
            # url(r\'^detail/(\\d+)/\', views.detail),
            url(r\'^template/\', views.template),
        ]

       
    7.myste的urls.py
        from django.conf.urls import url,include       #想自定义必须使用include

        urlpatterns = [
            # url(r\'^admin/\', admin.site.urls),
            # url(r\'^index/\', views.f1),
            # url(r\'^login/\', views.login),
            # url(r\'^detail/(\\d+)/\', views.detail),
            # url(r\'^detail2/(\\d+)/(\\d+)/\', views.detail2),
            # url(r\'^detail3/(?P<p1>\\d+)/(?P<x2>\\d+)/\', views.detail3),
            # url(r\'^index/(\\d+)/\', views.index),
            # url(r\'^detail/(\\d+)/\', views.detail),
            url(r\'^web/\', include(\'app1.urls\')),
        ]
       
    8. mysite的apps.py
        from django.apps import AppConfig
        class App1Config(AppConfig):
            name = \'app1\'

       

    9.页面访问
    http://127.0.0.1:8000/web/template/
        VVVV 22
        11,1,0,True,False,3

        22,2,1,False,False,2

        33,3,2,False,True,1

        7777

        VVVV vvvv VVVV666alex
        False

 

 

 

 


后台管理系统,block模板使用
    views.py
        def assets(request):
            assets_list = []
            for i in range(10):
          &

以上是关于python day18的主要内容,如果未能解决你的问题,请参考以下文章

python学习day18

python学习day——18

2018-06-19-Python????????????day18-????????????????????????

python18-day5

Python Day18

python18-day7