継承コードの読み取りとコメント

9583 ワード

一、Django部分(Journal/User)
  • journal(以下のpyファイルのみが役に立ち、その他は管理されません)
  • models.py + serializers.py:(モデル+シーケンス化メソッド、シーケンス化json生成
  • ユーザIPレコードUserIp(ip=char,count=int)対応シーケンス化,id,ip,count
  • アクセス数VisitCount(count=int)対応シーケンス化、id、count
  • 日付レコードDayCount(day=date,count=int)対応シーケンス化,id,date,coun
  • urls.py
  • localhost:8000/api/journal/visit/呼び出しviewsにアクセスします.Visit
  • localhost:8000/api/journal/statistics/呼び出しviewsにアクセスします.Statistics

  • views.py
  • Visit
        POST  ,
    
    
    count    VisitCount     
    #     ,        ,      ,    ,    。
    count = VisitCount.objects.all()
    
    
      request.META  HTTP   IP,   IP  UserIp count+1,
          UserIp, count   1
    
     if 'HTTP_X_FORWARDED_FOR' in request.META:
                client_ip = request.META['HTTP_X_FORWARDED_FOR']
                client_ip = client_ip.split(",")[0]
            else:
                client_ip = request.META['REMOTE_ADDR']
    
            exist = UserIp.objects.filter(ip=str(client_ip))
            if exist:
                uip = exist[0]
                uip.count += 1
            else:
                uip = UserIp()
                uip.ip = client_ip
                uip.count = 1
            uip.save()
    
                   ,     count+1,      DayCount  ,date       ,count  1
    
     date = timezone.now().date()
            today = DayCount.objects.filter(day=date)
            if today:
                day_record = today[0]
                day_record.count += 1
            else:
                day_record = DayCount()
                day_record.dayTime = date
                day_record.count = 1
            day_record.save()
    
      HTTP201(  )
    
  • Statistics
        Get  ,
    data = {
    "visit_count": vist_count['count__sum'],  #   IP     
    "date_count_list": date_count_list_serializer.data, #  DayCount json
    "network_api_count": network_api_count, #    
    "user_count":user_count #    
    }
    #        
    {
        "visit_count": 12,
        "date_count_list": [
            {
                "id": 1,
                "day": "2020-04-06",
                "count": 12
            }
        ],
        "network_api_count": 1,
        "user_count": 2
    }
    


  • user
  • models.py + serializers.py:
  • test.pyユーザー登録テストデータのセットであり、python manage.py test user/はテストを自動化することができる.
  • urls.py
    urlpatterns = [
        url(r'^register/$', views.UserRegister.as_view()),
        url(r'^login/$',obtain_jwt_token),
        url(r'^info/$',views.UserInfo.as_view())
    ]
       
      localhost:8000/api/user/register/    views.UserRegistor
      localhost:8000/api/user/login/    obtain_jwt_token,    ,       ,          
      localhost:8000/api/user/ingo/    views.UserInfo
    
  • utils.pyユーザ認証に関する設定は、
  • にかかわらず
  • views.py
  • UserRegistor
        POST  ,      
     def post(self, request):
            serializer = UserSerializer(data=request.data)#json->  
            if serializer.is_valid():#       
                serializer.save()#      
                #        token     
                payload = jwt_payload_handler(serializer.instance)
                token = jwt_encode_handler(payload)
                res = serializer.data
                res["token"] = token
                return Response(res, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)#     HTTP400
    
  • UserInfo
      Get  ,
          Json
        
    {
        "id": 1,
        "password": "pbkdf2_sha256$120000$gCiyqC4gkN1k$/IVeCbd5gsu2T5RMNRpO50MxeC9vx14diuKXgSGDx9A=",
        "username": "pandapan",
        "email": "[email protected]",
        "is_active": true,
        "is_staff": true
    }
    



  • 二、先端部分
    三、後端部分
    permission.py、モデル操作に対するユーザーの権限を定義します.
    from NeuralNetwork.models import Network
    
    class ChangeModel(object):
    
    
    
    def has_permission(self, request,view):
        aquire_object = Network.objects.get(pk=view.kwargs['pk'])
        if request.method == 'GET' or request.user.id == aquire_object.creator_id:
            return True
        else:
            return False
        #  Network         id     get  ,  true,   false
    
    
    

    model.py:
    class Network(models.Model):
    
    creator = models.ForeignKey('user.User',on_delete=models.CASCADE,null=True)
    structure = models.TextField()
    name = models.TextField(null=True)
    time = models.DateTimeField(auto_now=True)
    

    Networkには4つのプロパティ、作成者ID、モデル名、作成時間、structureがあります.ここでstrutureはjson型テキストであり、networkの完全な構造が記録されている.
    serializers.py,networkをシーケンス化し,従来と比較する
    views.py、重要なファイル、一連のインタラクティブな操作を定義しました
    class NetworkList(APIView):
        permission_classes = (permissions.IsAuthenticated,)
    #             
    ```
    def get(self, request):
        user_id = request.GET['id']
        if user_id is None:
            return Response("need user id", status=status.HTTP_400_NOT_FOUND)
        network_list = Network.objects.filter(creator=user_id).values('id', 'time', 'creator_id', 'name')
        return Response(list(network_list), status=status.HTTP_200_OK)
    #           Network   ,   structure  ,       
    
    def post(self, request):
    
        creator = request.user.id
        data = {
            "name": request.data["name"],
            "creator": creator,
            "structure": json.dumps(request.data["structure"])
        }
        serializer = NetworkSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    ```
    #        Network
    class NetworkDetail(APIView):
        permission_classes = (ChangeModel,)
    # permission.py   ,    ID network ID  
    ```
    def get_object(self, pk):
        try:
            return Network.objects.get(pk=pk)
        except Network.DoesNotExist:
            raise Http404
    #  ID pk Network
    def get(self, request, pk):
        net = self.get_object(pk)
        serializer = NetworkSerializer(net)
        return Response(serializer.data)
    #  ID pk Network,      ,     
    def put(self, request, pk):
        net = self.get_object(pk)
        data = {
            "name": request.data["name"],
            "structure": json.dumps(request.data["structure"])
        }
        serializer = NetworkSerializer(net, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    #  id=pk network
    def delete(self, request, pk):
        net = self.get_object(pk)
        net.delete()
        return Response(status=status.HTTP_200_OK)
    #  id pk Network
    ```
    
    @api_view(['POST'])
    def gen_code(request):
        result = {}
        try:
            result["Main"], result["Model"], result["Ops"] = ops.main_func(request.data)
            #  translate/ops.py  main_func      ,       
        except Exception as e:
            return Response({str(e)}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(result, status=status.HTTP_200_OK)
    
    #todo:                 ,             !!!!!!!
    @api_view(['POST'])
    def download_project(request):
        data = request.data
        write_file(data)
        zipf = zipfile.ZipFile("project_VisualPytorch.zip", 'w',zipfile.ZIP_DEFLATED)
        #          
        pre_len = len(settings.FILE_DIR)
        for parent, dirnames, filenames in os.walk(settings.FILE_DIR):
            for filename in filenames:
                pathfile = os.path.join(parent, filename)
                arcname = pathfile[pre_len:].strip(os.path.sep)  #     
                zipf.write(pathfile, arcname)
        zipf.close()
        # setting.FILE_DIR(          )            
    ```
    response = StreamingHttpResponse(file_iterator("project_VisualPytorch.zip"))
    response['Content-Type'] = 'application/zip'
    response['Content-Disposition'] = 'attachment;filename="project_VisualPytorch.zip"'
    #             ,          file_iterator zip          ,    。          。
    return response
    ```
    
    def file_iterator(file_name, chunk_size=512):
        with open(file_name, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    
    def write_file(data):
        if os.path.exists(os.path.join(settings.FILE_DIR,"project/Main.py")):
            os.remove(os.path.join(settings.FILE_DIR,"project/Main.py"))
        if os.path.exists(os.path.join(settings.FILE_DIR,"project/Model.py")):
            os.remove(os.path.join(settings.FILE_DIR,"project/Model.py"))
        if os.path.exists(os.path.join(settings.FILE_DIR,"project/Ops.py")):
            os.remove(os.path.join(settings.FILE_DIR,"project/Ops.py"))
        if os.path.exists("project_VisualPytorch.zip"):
            os.remove("project_VisualPytorch.zip")
            #                     
        root_dir = os.path.join(settings.FILE_DIR, "project")
        file_main = open(os.path.join(root_dir, "Main.py"), "w")
        file_model = open(os.path.join(root_dir, "Model.py"), "w")
        file_ops = open(os.path.join(root_dir, "Ops.py"), "w")
        file_main.write(data['main'])
        file_model.write(data['model'])
        file_ops.write(data['ops'])
        #