django 权限、密码、env管理

1、视图中禁用ajax:

from django.views.decorators.csrf import csrf_exempt
#  在函数中上方加上 @csrf_exempt

2、基于继承class的View视图权限装饰

from django.utils.decorators import method_decorator
# 使用 下方为在post请求禁用csrf  #也可以在函数上面直接使用
@method_decorator(name='post',decorator=csrf_exempt)
class IndexView(View):

  def get(self):
      pass

  def post(self):
      pass

3、登录装饰器

from django.contrib.auth.decorators import login_required,permission_required from django.contrib.auth.mixins import LoginRequiredMixin
#   使用 login_required 要在settings里面配置
LOGIN_URL = '/login/' '/login/' 为登录路径
# 使用LoginRequiredMixin要在视图中配置
login_url = '/login/'

4、登录后跳转原网页

class LoginView(View):
    def get(self, request):
        next_url = request.GET.get('next', '')
        # request.session['next_url'] = next_url
        print(next_url)
        form = LoginForm1()
        return render(request, 'login.html', context={
            'form': form,
            'next_url': next_url
        })
    def post(self, request):
        form = LoginForm1(request.POST)
        print(form.errors)
        if form.is_valid():
            username = request.POST.get('username')
            password = request.POST.get('password')
            user = authenticate(username=username, password=password)
            next_url = request.GET.get('next', '')
            print(next_url)
            if user:
                login(request, user)
                print(request.user.username)
                if next_url:
                    # del request.session['next_url']
                    return redirect(next_url)
                return redirect('/news/')
            else:
                form = LoginForm1(data=request.POST)
                messages.error(request, '用户名或密码错误')
                return render(request, 'login.html', context={
                    'form': form,
                })
        else:
            form = LoginForm1(data=request.POST)
            # messages.error(request, '用户名或密码错误')
            return render(request, 'login.html', context={
                'form': form,

            })

5、登录

from django.contrib.auth import logout, login
from django.contrib.auth import authenticate
# 登录:
	username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    next_url = request.GET.get('next', '')
    print(next_url)
    if user:
        login(request, user)
# 登出
logout(requrst)

6、自定义装饰器

import functools


def perc(func): # 权限控制装饰器
    @functools.wraps(func)
    def inner(request,*args,**kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner
# 使用,在函数上面加上  @perc

7、密码管理

from django.contrib.auth.hashers import make_password
from django.contrib.auth import get_user_model()
User = get_user_model()
user = User.object.all().first()
password = make_password(password)
user.check_password(password)

8、Django 的 ForeignKey 与数据库的 FOREIGN KEY约束

province = models.ForeignKey(Province, null=True, on_delete=models.SET_NULL,
                                 related_name='cities', db_constraint=False)

9、django 配置文件放在.env 配置

pip install django-environ
# settings.py  操作
import environ
import warnings
env = environ.Env()
if DEBUG:
    # warnings.filterwarnings('error')
    pass
else:

    warnings.filterwarnings('ignore')

env.read_env(os.path.join(BASE_DIR, '.env'))
try:
    env.read_env('D://.env')
except:
    pass

print(env.db_url('DATABASE_URL'))
env.db_url_config(os.environ.get('DATABASE_URL'))

django 优化

修改数据库最大连接数

            mysql> show variables like "%max_connection%";
            +-----------------------+-------+
            | Variable_name         | Value |
            +-----------------------+-------+
            | extra_max_connections | 1     |
            | max_connections       | 151   |
            +-----------------------+-------+
            2 rows in set

            mysql> set global  max_connections = 200
                -> ;
            Query OK, 0 rows affected

            mysql> show variables like "%max_connection%";
            +-----------------------+-------+
            | Variable_name         | Value |
            +-----------------------+-------+
            | extra_max_connections | 1     |
            | max_connections       | 200   |
            +-----------------------+-------+
            2 rows in set
            

开启线程数小于最大连接数

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgresql_psycopg2',
        'NAME': '<dbname>',
        'USER': '<dbuser>',
        'PASSWORD': '<dbpassword>',
        'HOST': '/var/run/postgresql',
        'PORT': '',
        'CONN_MAX_AGE': None,  # Set to None for persistent connections
    }
}
posted @ 2020-08-12 08:35  仰望丶那一缕微光  阅读(229)  评论(0编辑  收藏  举报