python16_day24【restful、crm表构、认证】
一、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表构、认证】的更多相关文章
- Yii2 restful api创建,认证授权以及速率控制
Yii2 restful api创建,认证授权以及速率控制 下面是对restful从创建到速率控制的一个详细流程介绍,里面的步骤以及截图尽可能详细,熟悉restful的盆友可能觉得过于繁琐,新手不妨耐 ...
- Form authentication(表单认证)问题
前言 最近在做ASP.NET MVC中表单认证时出了一些问题,特此记录. 问题 进行表单认证时,在 PostAuthenticateRequest 事件中从Cookie值中解密票据.如下: prote ...
- SharePoint 2013 修改表单认证登录页面
前 言 之前的博客我们介绍了如何为SharePoint配置表单登陆,但是,登陆页面是丑.很丑.非常丑.特别非常丑!我们现在就介绍一下如何定制SharePoint表单登陆页面! SharePoint 表 ...
- SharePoint 2013 表单认证使用ASP.Net配置工具添加用户
前 言 上面一篇博客,我们了解到如何为SharePoint 2013配置表单身份认证,但是添加用户是一个麻烦事儿:其实,我们还可以用Asp.Net的配置工具,为SharePoint 2013添加表单用 ...
- php laravel加密 form表单认证 laravel分页
use Illuminate\Support\Facades\Crypt; echo Crypt::encrypt(123); //加密echo "<br>";//解密 ...
- SharePoint 表单认证创建用户
前言 本文介绍如何在SharePoint表单登陆中添加表单用户,前提是已经配置了表单认证,如果没配置表单登陆,需要先配置表单登陆: 1. 打开Visual Studio,如下图: 2. 新建一个项目 ...
- springboot结合jwt实现基于restful接口的身份认证
基于restful接口的身份认证,可以采用jwt的方式实现,想了解jwt,可以查询相关资料,这里不做介绍~ 下面直接看如何实现 1.首先添加jwt的jar包,pom.xml中添加依赖包: <de ...
- spring security 表单认证的流程
spring security表单认证过程 表单认证过程 Spring security的表单认证过程是由org.springframework.security.web.authentication ...
- spring-security-4 (5)spring security Java配置实现自定义表单认证与授权
前面三篇讲解了spring security的搭建以及简单的表单认证与授权原理.本篇将实现我们自定义的表单登录与认证. 本篇不会再讲项目的搭建过程,因为跟第二节的搭建如出一辙.本篇也不会将项目中所有 ...
随机推荐
- Http缺省的请求方法是。(选择1项)
A.PUT B.GET C.POST D.TRACE 解答:B
- Python 资料性网站。
伯乐在线:http://blog.jobbole.com/category/python/ http://blog.chinaunix.net/uid/22334392/cid-24327-list- ...
- 基于SSH框架实际开发时遇到的问题及解决办法
1. 发现通过注解注入bean不起作用(对应的.java文件上没有'S'标记) 需要在pring .xml配置文件中加 <!-- 使用自动注解就必须配置加入自动扫描加载容器的包 --> & ...
- js 版本号
在web项目开发过程中,我们经常会引用css.js文件,更新文件后常出现缓存问题(明明更改了代码,在浏览器上访问的时候却没有发生变化),这种情况我们通常采用以下两种解决方案: 1.手动清除浏览器缓存 ...
- STL容器:list双向链表学习
list是一个双向列表容器,完成了标准C++数据结构中链表的所有功能; list与vector和deque类似,只不过其中的对象提供了对元素的随机访问. STL以双向链表的方式实现list,访问需要从 ...
- Spring security UserDetailsService autowired注入失败错误
最近使用spring mvc + spring security 实现登录权限控制的时候,一直不能成功登录,检查过后是dao一直无法注入为null CustomUserDetailConfig.jav ...
- SurvivalShooter学习笔记(九.游戏暂停、结束)
这里先补充一个得分管理器: 玩家得分设置成一个静态变量: public class ScoreManager : MonoBehaviour { public static int score; // ...
- Dynamics CRM 2015 Update 1 系列(3): API的那些事 - Old APIs VS New APIs
今天我们来看看API的变化.新系统中,去掉了一些经常使用的数据处理API,比如:SetStateRequest, SetBusinessUnitRequest, SetParentBusinessUn ...
- STL map 的 key 元素
在做 compiler 语义分析时, 需要用到 map<?,?> 在别人的代码上做扩展, 所以有些代码是不能动的 这时, 需要一个 map<symbol,int> 的数据结构, ...
- chrome/FF 解析遇到 { 行为一致,返回不一致
测试的时候,发现一个问题,FF下: chrome 下: 你会发现,FF 在解析一直到返回的时候,都是把 {x:1} 当做一个语句块去解析的,而 chrome 在返回的时候返回了对象,把 {x:1} 当 ...