一:登录操作

from django.contrib.auth import authenticate,login,logout  #可以用来做登录验证
from django.contrib.auth.decorators import login_required  #装饰器,用于对用户是否登录进行验证

1.简单使用:

def acc_login(request):
error_msg = ''
if request.method == "POST":
username = request.POST.get("username")
password = request.POST.get("password")
user = authenticate(username=username,password=password) #进行用户验证
if user:
login(request,user) #登录状态,添加入session, request.user = user return redirect(request.GET.get("next","/"))
else:
error_msg = "Wrong Username Or Password" return render(request,"login.html",{"error_msg":error_msg}) def acc_logout(request):
logout(request) #清除session数据
return redirect("/login.html") from django.contrib.auth.decorators import login_required @login_required
def dashboard(request): return render(request,"Sale/dashboard.html")

注意:使用@login_required需要我们配置

LOGIN_URL = "/login.html"  #默认是在accounts/login路由下跳转

2.方法了解

(1)authenticate方法

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)  #根据用户名获取用户对象
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):  #根据密码进行登录验证,以及获取用户的操作权限
return user
UserModel = get_user_model()
def get_user_model():  #返回用户表对象,对象由AUTH_USER_MODEL指定,默认是auth.User默认数据表,我们可以在自己的setting文件中进行覆盖
"""
Returns the User model that is active in this project.
"""
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)

(2)login方法

def login(request, user, backend=None):
def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
user = request.user
if hasattr(user, 'get_session_auth_hash'):
session_auth_hash = user.get_session_auth_hash() if SESSION_KEY in request.session:
if _get_user_session_key(request) != user.pk or (
session_auth_hash and
not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)):
# To avoid reusing another user's session, create a new, empty
# session if the existing session corresponds to a different
# authenticated user.
request.session.flush()
else:
request.session.cycle_key() try:
backend = backend or user.backend
except AttributeError:
backends = _get_backends(return_tuples=True)
if len(backends) == :
_, backend = backends[]
else:
raise ValueError(
'You have multiple authentication backends configured and '
'therefore must provide the `backend` argument or set the '
'`backend` attribute on the user.'
) request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)
request.session[BACKEND_SESSION_KEY] = backend
request.session[HASH_SESSION_KEY] = session_auth_hash
if hasattr(request, 'user'):
request.user = user
rotate_token(request)
user_logged_in.send(sender=user.__class__, request=request, user=user)

设置session,向request中添加user属性,可以直接使用request.user获取User表对象

(3)logout方法

def logout(request):
def logout(request):
"""
Removes the authenticated user's ID from the request and flushes their
session data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if hasattr(user, 'is_authenticated') and not user.is_authenticated:
user = None
user_logged_out.send(sender=user.__class__, request=request, user=user) # remember language choice saved to session
language = request.session.get(LANGUAGE_SESSION_KEY) request.session.flush() if language is not None:
request.session[LANGUAGE_SESSION_KEY] = language if hasattr(request, 'user'):
from django.contrib.auth.models import AnonymousUser
request.user = AnonymousUser()

清空session,删除request.user

(4)login_required方法

def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):#function是我们装饰的函数名,redirect_field_name是跳转时所带的参数,默认next
    """
Decorator for views that checks that the user is logged in, redirecting
to the log-in page if necessary.
"""
actual_decorator = user_passes_test(
lambda u: u.is_authenticated,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator

函数体

def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
""" def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
path = request.build_absolute_uri()
resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
# If the login url is the same scheme and net location then just
# use the path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:]
current_scheme, current_netloc = urlparse(path)[:]
if ((not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)):
path = request.get_full_path()
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(
path, resolved_login_url, redirect_field_name)
return _wrapped_view
return decorator

装饰器方法

二:csrf的多种使用方法

from django.views.decorators.csrf import csrf_exempt

1.需求分析

当我们需要对某一个view方法去掉csrf_token验证时。总不至于去注释掉所有的csrf验证吧
# 'django.middleware.csrf.CsrfViewMiddleware',

那么我们需要去取消某一个方法的csrf验证

2.实现代码

1.FBV:直接使用装饰器方法

@csrf_exempt
def asset(request):
pass

2.CBV:需要再去引入一个模块(其实也可以直接使用)

from django.utils.decorators import method_decorator
class AssetView(View):
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(AssetView, self).dispatch(request, *args, **kwargs)
    def post(self,request,*args,**kwargs):
     pass    def put(self,request,*args,**kwargs):
     pass
其中dispatch()方法:作用是将任务分发到正确的方法上。因为需要过滤掉csrf的方法不止post,还有put等,所以在dispatch中过滤掉csrf,那么在其他的方法上可以不用去管

3.在url中进行过滤

from django.conf.urls import url
from API import views as v1
from django.views.decorators.csrf import csrf_exempt urlpatterns = [
url(r'^asset',csrf_exempt(v1.AssetView.as_view())),
]

三:import导入的多种方法(用于反射)

1.一般导入模块直接使用import

import 模块  #一般我们是直接使用import导入对应模块
from 包 import 模块  #多层导入 

2.需求:现有字符串代表各个模块,如何通过反射获取该模块

(1)使用__import__

__import__("模块")  

__import__("层一.层二.层三.模块",fromlist=True) #对于多层,我们使用.连接。注意:fromlist需要添加为True,不然只会导入层一,调用的使用我们还要一级一级向下找,不方便
def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty.
package:test3    --->   包下面有t2.py文件,定义test2方法
无fromlist:
md = __import__("test3.t2")
md.t2.test2() #test2 有fromlist
md = __import__("test3.t2",fromlist=True)
md.test2()

演示结果

(2)使用importlib.import_module

def import_module(name, package=None):
#如果是相对导入的话,第二个参数是需要的 The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
md = importlib.import_module("test3.t2")
md.test2()  #test2
md = importlib.import_module(".t2","test3")  #.t2代表时相对于test3下的相对路径,就是相当于将前后连接test3.t2
md.test2()
md = importlib.import_module("test3.t1.t11")
md.test11() md = importlib.import_module(".t1.t11","test3")
md.test11() #test11
#test11

再多一级

python---django的模块简便使用的更多相关文章

  1. Python Django 功能模块

    Python Django模块 Django模块,是针对有django基础,对django功能进行模块化,方便下次使用. 一.注册模块 该注册采用邮箱验证,注册成功后会发送激活链接到邮箱. 邮箱验证参 ...

  2. Python - Django - auth 模块

    生成数据库 查看 auth_user 数据库 给 auth_user 表创建一个超级用户 邮箱地址可以不写 再看一下 auth_user 表 密码被加密了 login.html: <!DOCTY ...

  3. python安装外部模块Django

    Windows安装Django模块: 由于本人安装的Python版本是Python3.7,所以安装命令为:pip3 install django /pip3 install django安装过程中出现 ...

  4. python——django使用mysql数据库(二)

    上一篇中,我们已经讲述了如何初始化一个django数据库,这一章就来讲讲在实际的项目中如何使用我们初始化的数据库呢? 如还未进行初始化数据库操作,请参考python——django使用mysql数据库 ...

  5. python Django教程 之 安装、基本命令、视图与网站

    python  Django教程  之 安装.基本命令.视图与网站 一.简介 Django 中提供了开发网站经常用到的模块,常见的代码都为你写好了,通过减少重复的代码,Django 使你能够专注于 w ...

  6. python django 模板

    1 用两个大括号括起来的文字{{person_name}} 称为变量 2 被 大括号和面分号包围的文件({% if ordered_warranty %})是模板标签 3 过滤器是用管道符(|) 和U ...

  7. Python+Django+Eclipse 在Windows下快速开发自己的网站

    一.配置开发环境 我的开发环境是:Python3.3.2 + Django1.5.2 + Eclipse 1.安装Python 下载地址:http://www.python.org/getit/ 安装 ...

  8. python Django 学习笔记(一)—— Django安装

    注:本人python版本2.7.5 ,win7系统 安装Django https://www.djangoproject.com/download/ 官方下载Django-1.5.5.tar.gz 1 ...

  9. Python+Django+SAE系列教程17-----authauth (认证与授权)系统1

    通过session,我们能够在多次浏览器请求中保持数据,接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们须要认证. 当然了,Django 也提供了 ...

  10. 使用python+django+twistd 开发自己的操作和维护系统的一个

    许多开源操作系统和维护系统,例nagios.zabbix.cati等等,但是,当他们得到的时间自己的个性化操作和维护需求,始终无力! 最近的一项研究python.因此,我们认为python+djang ...

随机推荐

  1. 寒假作业第二篇随笔(A+B)

    Github链接:https://github.com/heihuifei/object-oriented A+B Format (20) Calculate a + b and output the ...

  2. fcn模型训练及测试

    1.模型下载 1)下载新版caffe: https://github.com/BVLC/caffe 2)下载fcn代码: https://github.com/shelhamer/fcn.berkel ...

  3. mysql group by分组查询错误修改

    select @@global.sql_mode;set @@sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR ...

  4. LeetCode题解:(19) Remove Nth Node From End of List

    题目说明 Given a linked list, remove the nth node from the end of list and return its head. For example, ...

  5. 第二次结对作业-WordCount进阶需求

    原博客 队友博客 github项目地址 目录 具体分工 需求分析 PSP表格 解题思路描述与设计实现说明 爬虫使用 代码组织与内部实现设计(类图) 算法的关键与关键实现部分流程图 附加题设计与展示 设 ...

  6. docker weave安装

    1.升级内核到3.10.0以上,安装iproute22.安装 0.80版本:#wget -O /usr/local/bin/weave https://raw.githubusercontent.co ...

  7. Tomcat 启动流程

  8. 03.基于IDEA+Spring+Maven搭建测试项目--常用dependency

    <!--常用的依赖配置--> <!--未展示完整的pom.xml文件内容--> <properties> <java.version>1.8</j ...

  9. [BZOJ2244][SDOI2011]拦截导弹 CDQ分治

    2244: [SDOI2011]拦截导弹 Time Limit: 30 Sec  Memory Limit: 512 MB  Special Judge Description 某国为了防御敌国的导弹 ...

  10. Android热修复原理(一)热修复框架对比和代码修复

    在Android应用开发中,热修复技术被越来越多的开发者所使用,也出现了很多热修复框架,比如:AndFix.Tinker.Dexposed和Nuwa等等.如果只是会这些热修复框架的使用那意义并不大,我 ...