私が表示するdjango分析-4(views.py)

21575 ワード

世界観
標準のView Class
Class View(CBV)に相当します.
CBV
継承とブレンドの機能により、コードとシステムを再使用してビューを整理できます.
GET,POSTなどのHTTPメソッドに基づく処理コードを記述する場合,if関数の代わりにメソッド名を用いてコードの構造をより明確にする.
マルチセンタのオブジェクト指向技術を利用し,Generic View,Mixin Classなどを用いて,コードの再利用と開発効率を向上させる.
世界観の四つの分類
ベースビュー(Base View):ビュークラスを作成し、他の共通ビューの親となるデフォルトの共通ビュー
Generic Display View:オブジェクトのリストまたはオブジェクトの詳細を表示するビュー
Generic Edit View:フォームからオブジェクトを作成、変更、削除するビュー
Generic Date View:日付オブジェクトに基づく年/月/日ページの表示
BaseViewの作成
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views import View

@method_decorator(csrf_exempt, name = 'dispatch')
class BaseView(View):

    @staticmethod
    def response(data={}, message='', status=200):
        result = {
            'data' : data,
            'message' : message,
        }
        return JsonResponse(result, status = status)
@method_decorator
@method decoratorはname値を指定し、クラスメソッドに対してこのdecoratorを使用できます.
The @method_decorator decorator transforms a function decorator into a method decorator so that it can be used on an instance method.
クラス内のメソッドにレコーダをすぐに適用できません.
CBVの各インスタンスを装飾するには,クラス自体を装飾する必要がある.
method decorator decoratorはfunction decoratorをmethod decoratorに変換し、インスタンスメソッドに使用できます.
method decoratorは*argsと*kwarsをパラメータとしてクラスの装飾方法に渡す.
def as_view(cls, **initkwargs):
	.
    	.
    	.
    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)
As viewメソッドは、ビュークラスを初期化し、プロセッサに戻る機能を提供します.
Handler
これは、ロッグの情報をどのように操作するかを決定するエンジンです.ログ・レコードのログ・レベルがハンドラのログ・レベルより低い場合、ハンドラはメッセージを無視します.
getattr(object, name[, default])
objectに存在する属性の値を取得します.
dispatch
要求を受信してHTTP応答を返す方法.GETリクエストはget()を呼び出し,POSTリクエストはpost()メソッドを呼び出す.
@staticmethod
静的メソッドはパラメータにselfを指定しません.したがって、インスタンスプロパティにアクセスできません.静的メソッドは、メソッド実行の外部状態に影響を及ぼさない純粋な関数(pure function)を作成するために使用される.入力値が同じ場合、純関数は常に同じ出力値を返します.
静的メソッドは、インスタンスの状態を変更しないメソッドを作成するために使用されます.
基本ビューを作成する理由は,将来生成するビューの重複部分を防止し,開発生産性を向上させ,コードの再利用性を向上させるためである.
response関数はdic形式のデータとmessageをパラメータとして受信し,json形式のresultを返す.
Json
Javascriptオブジェクト構文で構造化データを表す文字ベースの標準フォーマットです.
Web開発ではUIはJavascriptが一般的に使用され、内部アプリケーションロジックはpythonが一般的に開発され、JavaScriptとpythonの間でデータを交換する際にjson変換が使用され、以下に示す.
dictのタイプはdictで、jsonのタイプはstrです.
だからキー値で近づくことはできません.
json_val = json.dumps(dict1) (dict -> json)
dict2 = json.loads(json_val) (json -> dict)
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views import View
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.core.validators import validate_email, ValidationError
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required


@method_decorator(csrf_exempt, name='dispatch')
class BaseView(View):

    @staticmethod
    def response(data={}, message='', status=200):
        result = {
            'data': data,
            'message': message,
        }
        return JsonResponse(result, status=status)


class UserCreateView(BaseView):
    def post(self, request):
        username = request.POST.get('username', '')
        if not username:
            return self.response(message="아이디를 입력해주세요", status=400)
        passwrod = request.POST.get('password', '')
        if not password:
            return self.response(message="패스워드를 입력해주세요", status=400)
        email = request.POST.get('email', '')
        try:
            validate_email(email)
        except ValidationError:
            return self.response(message="올바른 이메일을 입력해주세요", status=400)

        try:
            user = User.objects.create_user(username, email, password)
        except IntegrityError:
            return self.response(message='이미 존재하는 아이디입니다.', status=400)

        return self.response({'user.id': user.id})


class UserLoginView(BaseView):
    def post(self, request):
        username = request.POST.get('username', '')
        if not username:
            return self.response(message='아이디를 입력해주세요.', status=400)
        password = request.POST.get('password', '')
        if not password:
            return self.response(message='패스워드를 입력해주세요.', status=400)

        user = authenticate(request, username=username, password=password)
        if user is None:
            return self.response(message='입력 정보를 확인해주세요.', status=400)
        login(request, user)
        return self.response()


class UserLogoutView(BaseView):
    def get(self, request):
        logout(request)
        return self.response()
これは簡単な登録、ログイン、ログアウトビューで、今回はdjangoを使用して基本的なlogin、logoutを提供します.
特に見ることはありませんが.
request.POST.get('username', '')
request.GET.get('username', '')
request.POSTは、要求されたPOST値を辞書形式で返す.
pythonでは、dictは[「key」を使用して「key」に対応する値(「value」)を返し、存在しない場合はkeyErrorを生成します.
.get('key')
dictから特定のキー値を取得する別の方法
.get("key")が存在しないkeyである場合は、Noneを返します.
たとえば.get(「key」、「defaultvalue」)では、キー値がない場合はデフォルト値を設定できます.
user = authenticate()
django.contrib.authにはdjangoの認証システムが含まれています.
authenticate(request=None, **credentials)
requestパラメータとcredentuasパラメータを受信し、有効であればuserオブジェクトを返します.
create_user()
UserManagerクラスの関数としてユーザーを作成します.
def create_user(self, username, email=None, password=None, **extra_fields):
super()
  • の子クラスで親クラスのコンテンツを使用する場合は、
  • を使用します.
    @method_decorator(login_required, name='dispatch')
    class HomeView(TemplateView):
    
        template_name = 'home.html'
    
        def get_context_data(self, **kwargs):
            context = super(HomeView, self).get_context_data(**kwargs)
    
            user = self.request.user
            followees = FollowRelation.objects.filter(follower=user).values_list('followee__id', flat=True)
            lookup_user_ids = [user.id] + list(followees)
            context['contents'] = Content.objects.select_related('user').prefetch_related('image_set').filter(
                user__id__in=lookup_user_ids
            )
    
            return context
    overriding defget context dataでsuperを使用するのは、superによって既存の実装get context dataをインポートするためです.
    def get context dataも、継承中に親定義のすべてのdef get context dataを実行するために実行されます.
    通常、get context dataは、すべての親クラスのコンテキストデータを現在のクラスのコンテキストデータとマージします.コンテキストを変更するクラスでこの操作を保持するには、get context dataをスーパークラスから呼び出す必要があります.