一、restful

  1. pip install djangorestframework

  2.settings.py

 INSTALLED_APPS = (
...
'rest_framework',
)
 REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}

  3.urls.py

 from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets # Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
       depth = 2
fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

  4.http://127.0.0.1:8000/users/

  5.自定义views

    根据上面基础,深入自定义views

 urlpatterns = [
url(r'^', include(router.urls)),
url(r'^eventlog_list/$', eventlog_list),
url(r'^eventlog_detail/(\d+)/$', eventlog_detail),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
 @api_view(['GET', 'POST'])  #只允许POST、GET
def eventlog_list(request):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
eventlogs = models.EventLog.objects.all()
serializer = rest_searilizers.EventLogSerializer(eventlogs, many=True)
return Response(serializer.data) elif request.method == 'POST':
print("request", request.data)
serializer =rest_searilizers.EventLogSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET','PUT'])
@csrf_exempt # 放开这个视图的CSRF检查
def eventlog_detail(request, pk):
"""
Retrieve, update or delete a code eventlog.
"""
try:
eventlog_obj = models.EventLog.objects.get(pk=pk)
except models.EventLog.DoesNotExist:
return HttpResponse(status=404) if request.method == 'GET':
serializer = rest_searilizers.EventLogSerializer(eventlog_obj)
return JsonResponse(serializer.data) elif request.method == 'PUT':
print(request)
data = JSONParser().parse(request)
serializer = rest_searilizers.EventLogSerializer(eventlog_obj, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE':
eventlog_obj.delete()
return HttpResponse(status=204)

二、自定义认证

  方式一:继承User表,一对一增加自己想要的字段

from django.contrib.auth.models import User
class UserInfo(models.Model):
username = models.OneToOneField(User)

  方式二:继承abstractbaseuser

  1.settings.py  指定系统认证不再是User表改成UserProfile

AUTH_USER_MODEL = 'crm.UserProfile'

  2.models.py  继承基类新的User表,即UserProfile.  还有一个管理类

 from django.db import models

 # Create your models here.
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
# BaseUserManager email规范设置和密码基本设置规则
# AbstractBaseUser 真正的用户名 密码 验证
) # ################如果用User model
# 1、必须有一个唯一的字段可被用于识别目的
# 2、full 和 short的名字
# 继承AbstractBaseUser 这个是核心
# 有了这个还必须要有一个自定管理器
# 如果和User字段和默认的一致的话,直接使用UserManager就可以了,如果user定义了不同的字段
# 需要自定义一个管理器,它继承BaseUserManager 并提供2个额外的方法: class UserProfileManager(BaseUserManager):
def create_user(self, email, name, password=None):
"""
Creates and saves a User with the given email, name and password.
"""
'''email是唯一标识,没有会报错'''
if not email:
raise ValueError('Users must have an email address') user = self.model(
email=self.normalize_email(email), # 检查email规则
name=name,
)
# AbstractBaseUser set_password == > make_password == > 加盐 hash
user.set_password(password) # 检测密码合理性
user.save(using=self._db) # 保存密码
return user def create_superuser(self, email, name, password):
"""
Creates and saves a superuser with the given email, name and password.
"""
user = self.create_user(email,
password=password,
name=name
)
user.is_admin = True # 比创建用户多的一个字段
user.save(using=self._db)
return user class UserProfile(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=32)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False) objects = UserProfileManager() # 会用到 get_by_natural_key 不然会报 USERNAME_FIELD = 'email' # 默认的用户名,对于自定义的用户模型,用USERNAME_FIELD 标识
REQUIRED_FIELDS = ['name'] # 通过createsuperuser管理命令创建一个用户时,用于提示的一个字段名称列表 def get_full_name(self):
# The user is identified by their email address
return self.email def get_short_name(self):
# The user is identified by their email address
return self.email def __str__(self): # __unicode__ on Python 2
return self.email '''django自带后台权限控制,对哪些表有查看权限等'''
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True '''用户是否有权限看到app'''
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True @property
def is_staff(self): # 用户管理网站权限
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin

  3.admin.py  能过管理管理UserProfile一些配置

 # 如果你想在admin控制台上面看到用户的表,需要在admin.py增加这些
from crm import models
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from crm.models import UserProfile class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta:
model = UserProfile
fields = ('email', 'name') def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2 def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField() class Meta:
model = UserProfile
fields = ('email', 'password', 'name', 'is_active', 'is_admin') def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"] class UserAdmin(BaseUserAdmin):
# 添加和更改用户实例的表单
# 以前是ModelAdmin
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm # The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'name', 'is_admin') # 这个和以前一样,显示一条数据这3个字段
list_filter = ('is_admin',) # 用这个字段过滤
fieldsets = ( # 点击进入,显示详细
('email passwd', {'fields': ('email', 'password')}), # email passwd是蓝色条框
('Personal info', {'fields': ('name',)}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = ( # 增加用户时显示详细
('增加', {
'classes': ('wide',),
'fields': ('email', 'name', 'password1', 'password2')}
),
)
search_fields = ('email',) # 查询字段
ordering = ('email',) # 排序字段
filter_horizontal = () # 水平和垂直 #
admin.site.register(models.UserProfile, UserAdmin)
admin.site.unregister(Group)

  

  项目:https://github.com/willianflasky/growup/tree/master/s16/homework/day24_restful/LuffyCRM

python16_day24【restful、crm表构、认证】的更多相关文章

  1. Yii2 restful api创建,认证授权以及速率控制

    Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...

  2. Form authentication(表单认证)问题

    前言 最近在做ASP.NET MVC中表单认证时出了一些问题,特此记录. 问题 进行表单认证时,在 PostAuthenticateRequest 事件中从Cookie值中解密票据.如下: prote ...

  3. SharePoint 2013 修改表单认证登录页面

    前 言 之前的博客我们介绍了如何为SharePoint配置表单登陆,但是,登陆页面是丑.很丑.非常丑.特别非常丑!我们现在就介绍一下如何定制SharePoint表单登陆页面! SharePoint 表 ...

  4. SharePoint 2013 表单认证使用ASP.Net配置工具添加用户

    前 言 上面一篇博客,我们了解到如何为SharePoint 2013配置表单身份认证,但是添加用户是一个麻烦事儿:其实,我们还可以用Asp.Net的配置工具,为SharePoint 2013添加表单用 ...

  5. php laravel加密 form表单认证 laravel分页

    use Illuminate\Support\Facades\Crypt; echo Crypt::encrypt(123); //加密echo "<br>";//解密 ...

  6. SharePoint 表单认证创建用户

    前言 本文介绍如何在SharePoint表单登陆中添加表单用户,前提是已经配置了表单认证,如果没配置表单登陆,需要先配置表单登陆: 1. 打开Visual Studio,如下图: 2. 新建一个项目 ...

  7. springboot结合jwt实现基于restful接口的身份认证

    基于restful接口的身份认证,可以采用jwt的方式实现,想了解jwt,可以查询相关资料,这里不做介绍~ 下面直接看如何实现 1.首先添加jwt的jar包,pom.xml中添加依赖包: <de ...

  8. spring security 表单认证的流程

    spring security表单认证过程 表单认证过程 Spring security的表单认证过程是由org.springframework.security.web.authentication ...

  9. spring-security-4 (5)spring security Java配置实现自定义表单认证与授权

    前面三篇讲解了spring security的搭建以及简单的表单认证与授权原理.本篇将实现我们自定义的表单登录与认证.  本篇不会再讲项目的搭建过程,因为跟第二节的搭建如出一辙.本篇也不会将项目中所有 ...

随机推荐

  1. 【转】【C#】迭代器IEnumerable和IEnumerator

    迭代器模式是设计模式中行为模式(behavioral pattern)的一个例子,他是一种简化对象间通讯的模式,也是一种非常容易理解和使用的模式.简单来说,迭代器模式使得你能够获取到序列中的所有元素而 ...

  2. 启动nmon报错while load libncurses.so.5 can not open shared(bit64)

    yum install ncurses-devel.i686 也有可能是软件包本身有问题,换一个try

  3. MyBitis(iBitis)系列随笔之四:多表(多对一查询操作)

      前面几篇博客介绍的都是单表映射的一些操作,然而在我们的实际项目中往往是用到多表映射.至于多表映射的关键要用到mybitis的association来加以实现.          这篇介绍的是多表中 ...

  4. 事务基础知识-->Spring事务管理

    Spring虽然提供了灵活方便的事务管理功能,但这些功能都是基于底层数据库本身的事务处理机制工作的.要深入了解Spring的事务管理和配置,有必要先对数据库事务的基础知识进行学习. 何为数据库事务 “ ...

  5. C# 笔记 Func<TResult> 委托、Action<T> 委托

    https://blog.csdn.net/wanglui1990/article/details/79303894 Func<ΤResult> 委托:代理(delegate)一个返回类型 ...

  6. THINKPHP5加载公共头部尾部模板方法

    之前在3.2中用 <include file="public/header" /> 后来发现在thinkphp5中应该这样写才行 {include file=" ...

  7. 杂记之--苹果4s手机呼叫转移怎么设置

    您好,呼叫转移只需在拨号界面输入相应的代码就可以,无需其他设置无条件转移 **21*电话号码#再按拨号键 取消代码:##21# *#21# 再按拨号键无信号,关机转移 **62*电话号码#再按拨号键 ...

  8. JB开发之问题汇总 [jailbreak,越狱技术]

    1.升级到Mac 10.9.1,Xcode 升级到5出现的问题: 1)升级前要做的事情: ①升级/重新安装iOSOpenDev,在终端输入 xcode-select --switch (xcode_d ...

  9. keystore是个嘛东西

    不管是QQ,还是微信,还是支付,涉及到第三方的都的用这个玩意,有时候找不对很坑的 首先我们要区分jks, app,keystore(新建keystoer的文件new就可以了)再进行下一步操作 Ecli ...

  10. 缺陷管理工具JIRA破解版及其安装方法

    JIRA是一个优秀的问题(or bugs,task,improvement,new feature )跟踪及管理软件.    它由Atlassian开发,采用J2EE技术.它正被广泛的开源软件组织,以 ...