python利用零宽切片插入元素

常见的python插入元素方式一般是insert或者手动挪动后修改值,然后其实还有种比较少用的通过零宽切片插入元素的方式,比较有意思,随便记录下.

Python 3.8.0 (v3.8.0:fa919fdf25, Oct 14 2019, 10:23:27) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3,4,5]
>>> a[:0] = [0,0,0]
>>> a
[0, 0, 0, 1, 2, 3, 4, 5]
>>> a[4:4] = [8,8,8,8,8,8]
>>> a
[0, 0, 0, 1, 8, 8, 8, 8, 8, 8, 2, 3, 4, 5]
>>> a[4:8] = []
>>> a
[0, 0, 0, 1, 8, 8, 2, 3, 4, 5]

无正文.

django类视图装饰器

一点关于django类视图装饰器的小笔记。

django类视图是很常用的,对于传统的函数视图来说,装饰器可以直接装饰函数,但类视图,装饰器无法直接装饰类方法。

比较了几种常见的解决方法,个人觉得比较优雅的解决方法如下:

from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View

@method_decorator(csrf_exempt, name="dispatch")
class login(View):

    @method_decorator(auth_login)
    def get(self, request, username):
        #....func...
        return render(request, 'login.html', {"displayName":username, "admin_flag":admin_flag})

继续阅读“django类视图装饰器”

django使用middleware实现views的访问限制

需要实现这样的需求,对于以个django app,需要对其中的一些restful api做IP访问限制,这样实现起来最方便的是在middleware中写逻辑。

关于django中间件的说明:
http://usyiyi.cn/translate/Django_111/topics/http/middleware.html
http://python.usyiyi.cn/translate/django_182/topics/http/middleware.html
继续阅读“django使用middleware实现views的访问限制”

《Python进阶》读书笔记(2)

9.装饰器

既将函数传参给装饰器函数,在函数执行的上下文作某些通用操作。

记得要用@wraps复制函数名称(__name__),等等属性

使用举例:

from functools import wraps

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            #若未登录,返回401
            authenticate()
        return f(*args, **kwargs)
    return decorated

继续阅读“《Python进阶》读书笔记(2)”