• drf版本控制 和django缓存,跨域问题,


    drf版本控制

    基于url的get传参方式

    REST_FRAMEWORK={
    # "DEFAULT_AUTHENTICATION_CLASSES":["app01.auth.AuthLogin",],
    # "DEFAULT_PERMISSION_CLASSES":['app01.auth.MyPer'],
    # "DEFAULT_THROTTLE_CLASSES":["app01.auth.VisitThrottle"],
    'DEFAULT_PARSER_CLASSES':['rest_framework.parsers.JSONParser'],
    'DEFAULT_THROTTLE_RATES': {
    'luffy': '3/mmmmmm'
    },

    'DEFAULT_VERSION': 'v1', # 默认版本(从request对象里取不到,显示的默认值)
    'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
    'VERSION_PARAM': 'version' # URL中获取值的key
    }

    基于url的正则方式

     url(r'^(?P<version>[v1|v2]+)/publishs/', views.PublishView.as_view()),

     

     

    django缓存

    CACHES = {
        'default': {
            # 1. MemCache 基于MemCache的缓存
            # 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
            # 'LOCATION': '127.0.0.1:11211',
    
            # 2. DB Cache 基于数据库的缓存
            # 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
            # 'LOCATION': 'my_cache_table',
    
            # 3. Filesystem Cache 基于文件的缓存
            # 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
            # 'LOCATION': '/var/tmp/django_cache',
    
            # 4. Local Mem Cache 基于内存的缓存
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'backend-cache'
        }
    }
    
    
    
    import os
    import time
    import django
    
    from django.core.cache import cache
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
    django.setup()
    
    
    def basic_use():
        s = 'Hello World, Hello Django Cache.'
        cache.set('key', s)
        cache_result = cache.get('key')
        print(cache_result)
    
        s2 = 'Hello World, Hello Django Timeout Cache.'
        cache.set('key2', s2, 5) #5是超时时间
        cache_result = cache.get('key2')
        print(cache_result)
    
        time.sleep(5) #5秒后就查不到了
        cache_result = cache.get('key2')
        print(cache_result)
        pass
    
    
    if __name__ == '__main__':
        basic_use()
    
    
    #实例
    # 星座运势
    def constellation(request):
        data = []
        if already_authorized(request):
            user = get_user(request)
            constellations = json.loads(user.focus_constellations)
        else:
            constellations = all_constellations
        for c in constellations:
            result = cache.get(c)
            if not result:
                result = thirdparty.juhe.constellation(c)
                timeout = timeutil.get_day_left_in_second()
                cache.set(c, result, timeout)
                logger.info("set cache. key=[%s], value=[%s], timeout=[%d]" %(c, result, timeout))
            data.append(result)
    
        response = CommonResponseMixin.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
        return JsonResponse(response, safe=False)
    

      

    settings:

    CACHES = {
    'default': {
    'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', # 指定缓存使用的引擎
    'LOCATION': r'D:lqzvue', # 指定缓存的路径
    'TIMEOUT': 300, # 缓存超时时间(默认为300秒,None表示永不过期)
    'OPTIONS': {
    'MAX_ENTRIES': 300, # 最大缓存记录的数量(默认300)
    'CULL_FREQUENCY': 3, # 缓存到达最大个数之后,剔除缓存个数的比例,即:1/CULL_FREQUENCY(默认3)
    }
    }
    }

    views:

    from django.shortcuts import render,HttpResponse
    
    # Create your views here.
    from django.views.decorators.cache import cache_page
    import time
    # 单页面缓存缓存5秒
    # @cache_page(20)
    def test(request):
        print('我来了')
        ctime=time.time()
    
        return render(request,'test.html',locals())
    

      

    templates:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <script src="/static/jquery-3.3.1.js"></script>
        <title>Title</title>
    </head>
    <body>
    不缓存的
    {{ ctime }}
    <br>
    缓存的的
    {#{% load cache %}#}
    {#第一个参数是超时时间,缓存时间,第二个参数是key值,别名#}
    {#{% cache 10 'test' %}#}
    {#    {{ ctime  }}#}
    {#{% endcache %}#}
    <button id="btn">点我发请求</button>
    </body>
    
    <script>
        $("#btn").click(function () {
            $.ajax({
                url:'http://127.0.0.1:8000/v1/publishs/',
                type:'get',
    {#            type:'delete',#}
    {#            type:'put',#}
    {#            contentType:'application/json',#}
    {#            data:JSON.stringify({'name':'lqz'}),#}
                success:function (data) {
                    console.log(data)
                }
            })
        })
    
    
    </script>
    </html>
    

      跨域问题

    from django.utils.deprecation import MiddlewareMixin
    class CORSMiddle(MiddlewareMixin):
        def process_response(self,request,response):
            response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8001'
            if request.method == 'OPTIONS':
                response['Access-Control-Allow-Methods'] = 'PUT,DELETE'
                response['Access-Control-Allow-Headers']='Content-Type'
            return response
    

     

  • 相关阅读:
    管理 node 版本,选择 nvm 还是 n?
    JDBC性能优化方案
    JDBC基础-setFetchSize方法
    JDBC的fetchsize和maxrows
    正确使用MySQL JDBC setFetchSize()方法解决JDBC处理大结果
    10种简单的Java性能优化
    35+ 个 Java 代码性能优化总结
    一线架构师带你玩性能优化
    诊断Java代码中常见的数据库性能热点问题应该这么做!
    十个 JDBC 的最佳实践
  • 原文地址:https://www.cnblogs.com/du-jun/p/10450567.html
Copyright © 2020-2023  润新知