zoukankan      html  css  js  c++  java
  • 七、模板层(一)

    一、序列化和反序列化

    ```
    #coding=utf-8
    from django.http import HttpResponse
    from django.views import View
    import jsonpickle
    class User(object):
        def __init__(self,uname,pwd):
            self.uname = uname
            self.pwd = pwd
     
    class IndexView(View):
        def get(self,request,*args,**kwargs):
            uname = request.GET.get('uname','')
            pwd = request.GET.get('pwd','')
            if uname=='zhangsan' and pwd=='123':
                user = User(uname,pwd)
                #{"py/object": "demo5.views.User", "uname": "zhangsan", "pwd": "123"}
                # ustr = jsonpickle.encode(user)
                # {"py/object": "demo5.views.User", "uname": "zhangsan", "pwd": "123"}
                ustr =jsonpickle.dumps(user)
                print ustr
                request.session['user'] = ustr
            return HttpResponse('Get请求')
     
     
    class GetSession(View):
        def get(self,request,*args,**kwargs):
            user = request.session.get('user','')
            # <demo5.views.User object at 0x0000000003D48588>
            # uuser = jsonpickle.decode(user)
            # <demo5.views.User object at 0x0000000003D1A0F0>
            uuser = jsonpickle.loads(user)
            print uuser
            return HttpResponse('User:%s'%uuser.uname)

    ```
     
    #### 序列化部分字段
    ```
    class User(object):
        def __init__(self,uname,pwd):
            self.uname = uname
            self.pwd = pwd
        def __getstate__(self):
            data = self.__dict__.copy()
            del data['pwd']
            return data

    u = User('zhangsan','123')      
    s = jsonpickle.encode(u,unpicklable=False)
    # jsonpickle.dumps(u,unpicklable=False)
    print s
    #{"uname": "zhangsan"}
    在调用pickle.dump时,默认是对象的__dict__属性被存储,如果你要修改这种行为,可以在__getstate__方法中返回一个state。state将在调用pickle.load时传值给__setstate__
    __setstate__(self, state)
    一般来说,定义了__getstate__,就需要相应地定义__setstate__来对__getstate__返回的state进行处理。
    ```
    二、通用视图
     

    #### 使用方法

    #### 配置URL
    ```
    from django.conf.urls import url
    from django.contrib import admin
    import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', views.IndexView.as_view()),
    ]

    ```

    #### 创建视图
    ```
    #coding=utf-8
    from django.http import HttpResponse
    from django.views import View
    class IndexView(View):
        def get(self,request,*args,**kwargs):
            return HttpResponse('Get请求')

        def post(self,request,*args,**kwargs):
            return HttpResponse('Post请求')
     

    ```
     
     三、页面读取静态文件

    #### Django读取静态文件方式
    - settings.py文件中设置
    ```
    STATIC_URL = '/static/'
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR,'static/imgs'),
        os.path.join(BASE_DIR,'static/css'),
        os.path.join(BASE_DIR,'static/js'),
    ]
    ```
     
    #### 配置URL
    ```
    from django.conf.urls import url
    from django.contrib import admin
    import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index.html$',views.index_view)
    ]
    ```
    #### 创建视图
    ```
    def index_view(request):
        return render(request,'index.html')
    ```

    #### 创建模板
    ```
    {% load staticfiles %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <img src="{% static '1.png' %}"/>
    </body>
    </html>
    ```
     四、模板标签渲染原理
    #### 配置URL
    1. 项目包/urls.py
    ```
    from django.conf.urls import url, include
    from django.contrib import admin
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^student/', include('student.urls')),
    ]
    ```
    2. 应用包/urls.py
    ```
    #coding=utf-8
    from django.conf.urls import url
    import views
    urlpatterns=[
        url(r'^query1/$',views.query_view1)
    ]
     

    ```

    #### 创建视图
    - 方式1:
    ```
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.http import HttpResponse
    from django.shortcuts import render
    from django.template import Template,Context
    # Create your views here.
    def query_view1(request):
        t = Template('hello:{{name}}')
        c = Context({'name':'zhangsan'})
        renderStr = t.render(c)

        return HttpResponse(renderStr)
    ```
    - 方式2:
    ```
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.http import HttpResponse
    from django.shortcuts import render
    from django.template import Template,Context
    # Create your views here.
    def query_view1(request):
        with open('templates/index.html','rb') as fr:
            content = fr.read()
        t = Template(content)
        c = Context({'name':'lisi'})
        renderStr = t.render(c)

        return HttpResponse(renderStr)
    ```

    #### 创建模板
    ```
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        hello:{{ name }}
    </body>
    </html>
    ```
    - 方式3:
    #### 创建视图
    ```
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.http import HttpResponse
    from django.shortcuts import render
    from django.template import Template,Context
    from django.shortcuts import loader
    # Create your views here.
    def query_view1(request):
        t = loader.get_template('index.html')
        renderStr = t.render({'name':'wangwu'})
        return HttpResponse(renderStr)
    ```

    - 方式4:
    #### 配置视图
    ```
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.http import HttpResponse
    from django.shortcuts import render

    # Create your views here.
    def query_view1(request):
        return render(request,'index.html',{'name':'zhaoliu'})

    ```
     
     五、自定义过滤器

    #### 配置URL
    ```
    from django.conf.urls import url, include
    from django.contrib import admin
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^student/', include('student.urls')),
    ]

    #coding=utf-8

    from django.conf.urls import url
    import views

    urlpatterns=[
        url(r'^$',views.index_view)
    ]
    ```

    #### 创建视图
    ```
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals
    from django.shortcuts import render
    # Create your views here.
    def index_view(request):
        content = '''####过滤器'''
        return render(request,'index.html',{'content':content})
    ```

    #### 创建模板
    ```
    {% load filter_mark %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        {{ content|md|safe }}
    </body>
    </html>
    ```

    #### 创建自定义过滤器
    1. 在应用包下创建一个名为"templatetags"的python package
    2. 在包中创建一个自定义的py文件

    pip install markdown
    ```
    #coding=utf-8
    from django.template import Library
    #实例名必须是register
    register = Library()
    @register.filter
    def md(value):
        import markdown
        return markdown.markdown(value)
     
     
     
    ```
     
    #### 截取字符串功能
    ```
    #coding=utf-8
    from django.template import Library
    register = Library()
    @register.filter
    def splitstr(value,args):
        start,end = args.split(',')
        content = value.encode('utf-8').decode('utf-8')
        return content[int(start):int(end)]
    ```
    - index.html页面
    ```
    {% load filter_mark %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
     
        {{ content|splitstr:'1,20' }}
    </body>
    </html>
    ```
     
  • 相关阅读:
    裸二分图匹配poj1469
    洛谷——P2038 无线网络发射器选址
    洛谷—— P1041 传染病控制
    洛谷—— P1784 数独
    Vijos——T 1092 全排列
    Vijos—— T 1359 Superprime
    高并发解决方案--负载均衡
    request 发送多层字典
    June 11th 2017 Week 24th Sunday
    June 10th 2017 Week 23rd Saturday
  • 原文地址:https://www.cnblogs.com/dangjingwei/p/12945996.html
Copyright © 2011-2022 走看看