Light project --- some of the problems encountered in implementing the backend interface

  1. ImproperlyConfigured: WSGI application 'lightapi.wsgi.application' could not be loaded;

    Plus a 'corsheaders.middleware.CorsMiddleware', but this app is not registered in the above (in fact, is not installed), in the comments after it, you can run in the moddleware

  2. App creation process:

    Run Python manage.py startapp name of the application in a virtual environment

    --- >>> register the application in the settings.py ---- >>> create routes (main route and the sub route) in the url

    - >>> built in models.py table - create adminx.py file>, configure global settings, registry model in this application

    - >>> disposed in the __init__.py default_app_config = "home.apps.HomeConfig" display in xadmin ---

    Application of back office systems sidebar --- >>> apps.py which set verbose_name = 'My Home' setting named custom name

    --- >>> views.py write view functions

    ---- >>> class sequences provided serializers.py

  3. ModuleNotFoundError: No module named 'apps' After creating app, data migration, reported this wrong

    Check the dev.py (settings development environment) did not find the path to this folder apps added to the environment variable

  4. RuntimeError: Model class lightapi.apps.home.models.Banner doesn't declare an explicit app_label and isn't in an application in
    INSTALLED_APPS.

    Each apps.py re-write the file, and then migrate the database does not show a problem, it is metaphysics

    At the same time pay attention to the problem of import package path

    07.28 check in online, that is the absolute path to a relative path, it can -> today out of the question after the discovery changed a bit, really not being given

  5. WARNING basehttp 154 ​​"POST / user / login / mobile / HTTP / 1.1" 403 58 Log distal part of the code, when using the SMS verification code, returns the error!

  6. django.db.utils.InternalError: (1050, "Table 'light_news_category' already exists")

    First execution: python manage.py migrate --fake

    Perform again: python manage.py migrate

  7. __str__ returned non-string (type int)

    The orm table __str__ get rid return parameter on the line

  8. django.db.utils.ProgrammingError: (1146, "Table 'light.light_news_recommend' doesn't exist")

    https://blog.csdn.net/weisubao/article/details/77187876

  9. django.db.utils.InternalError: (1060, "Duplicate column name 'article_id'")

     忘记写如何解决的了
  10. WARNING basehttp 154 ​​"POST / user / register / mobile / HTTP / 1.1" 403 58 back-end routing function is normal, do not know why that is, 403

Solution: Add in the target view class authentication_classes = [] can be, to normal

  1. All comments about the need to get an article using a ListAPIView, but then, all data is conventionally used to acquire a table, then here do not know how to do,

    Later, after a long time to tinker with the source code, come up with get_queryset method, rewritten, he got inside pass over the front end of the article id, and change the sql code to query the database, after a successful goal ,,,

    ---> Just think, I can not be in the class which override the init method directly, you can get self.request ah, so no need to operate in get_queryset inside, but an instant thought, directly inside the class is not self.request, but wondered if you can set @property be set to static properties (tried it, not OK -> may be the reason methods or techniques)

    Fortunately, find a feasible way

        def __init__(self, *args, **kwargs):
            super().__init__()
            self.article_id = ''
    
        def get_queryset(self):
            ..占地方,就删掉了,实际不能删...
    
            queryset = self.queryset
            from django.db.models.query import QuerySet
            if isinstance(queryset, QuerySet):
                self.article_id = self.request.query_params.get("article_id")  # ---------------------
                # Ensure queryset is re-evaluated on each request.
                queryset = queryset.filter(article_id=self.article_id, is_show=True)  # --改的这一条--------------
            return queryset
  2. Why create a data, the foreign key can not make a bit of type int (or str, but must be a number), and some have a database query available data (fiter check out the data)?

    例如:ValueError: Cannot assign "2": "Comment.user" must be a "User" instance.(comment字段关联user表)
  3. And table fans are concerned: Reverse accessor for 'FansAndObserved.user' Clashes with Reverse accessor for 'FansAnd
    Observed.observed'.

    HINT: Add or change a related_name argument to the definition for 'FansAndObserved.observed' or 'FansAndObserved.user'.
    
    我估计是因为我一张表中同时两个字段关联了同一张表,而且设置的是foreiginKey ,是否需要设置成manytomany才行?
    
    ---> 需要关联字段  related_name= ""  ---》 Direct assignment to the reverse side of a related set is prohibited. Use mobile.set() instead.
    
    最终实现结果: related_name= ""  定义的是字段名称,不要和user表里面的字段重复即可 
    
    推测 ---> 应该是用在表中同时关联某一张表多次时,用related_name来区分关联的多个字段
  4. RetrieveAPIView to inherit a single data in the database, but do not want to add to the URL the user id, like this http://api.light.cn:8000/user/userinfo/2, their idea is, the front passed over a token, the token then redis inside out to the corresponding user id, and then come after the single piece of data from the database by a method in retrieveAPIView, in this case URL, should be such that: http: //api.light. cn: 8000 / user / userinfo / token =?. . . (With a specific token)

    ---> 去源码中发现,原本URL该写成这样: http://api.light.cn:8000/user/userinfo/(?P(<pk>\d+)) ,原本以为,此处的 pk 是任意定义的,但是在retrieveAPIView继承的GenericAPIView中定义了:
    
    ```
    # If you want to use object lookups other than pk, set 'lookup_field'.
    # For more complex lookup requirements override `get_object()`.
    lookup_field = 'pk'
    lookup_url_kwarg = None
    ```
    
      上面的那个lookup_field 参数就是识别URL中的pk的,下面的lookup_url_kwarg应该是从传过来的参数中获取值,具体源代码在下面:
    
    ```
    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
    ```
    
    然后过滤的条件就是这两个参数决定的,**这两个参数写在  get_object  方法里面**,
    
    ----》》》》开始的想法是重写get_object方法,但是,写了半天也没有将过滤条件写出来,于是换了思路
    
    ----》》》我去找上一层,其中在 **RetrieveModelMixin** 这个类中有
    
    ```
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
    ```
    
    仔细看看,发现返回的数据也是在这里面操作的,第二行应该是获取queryset数据了,第三行是序列化,那么我只将第二行的数据注释掉,自己从数据库里面拿数据不就行了嘛,,,
    
    ----》》》 实践结果发现,确实拿到了目标数据,并且URL也变成了http://api.light.cn:8000/user/userinfo/?token= 。。。(跟的是具体的token)
  5. Log out of time, redis inside the token is not deleted, this is still to be optimized

Guess you like

Origin www.cnblogs.com/xt12321/p/11306719.html