Start chatting

Yesterday, I bought a skipping rope in JD. I plan to exercise myself in the back. Usually sitting for a long time and do not exercise, resulting in a variety of small problems or quite a lot, it is suggested that we also in the study, more relax the body. For example, like a list of a big brother with sister running, with sister badminton, are very good exercise. For me this kind of lazy person, buy a rope to jump, otherwise may go up 6 floors all have to breathe!

review

In the last section, we customized a simple permissions system and designed the associated table concepts. But the tables only have corresponding models, and there is no actual operation interface written, so today we will improve them!

The TestCase table we wrote last time has some problems. First of all, there is no params field, and there is no body field. Of course, there may be many fields missing, which we can add in the future development process.

In the dao /init.py joins the newly created table

Modify TestCase table

Write interfaces for adding, deleting, and checking projects and project roles

First of all, let’s make one requirement clear. Since projects have the concept of public and private, the logic for the project that the user can see should look like this:

  • The average user

    You can see public and private projects (the user is in the member, member or creator)

  • The administrator

    You can see all the items

    Since we need to get the corresponding project through the user ID, we first write the project_Role-related interface

Write the app/dao/project/ProjectRoleDao. Py

from app.models import db
from app.models.project_role import ProjectRole
from app.utils.logger import Log


class ProjectRoleDao(object) :
    log = Log("ProjectRoleDao")

    @staticmethod
    def list_project_by_user(user_id) :
        Param user_id: :return: """
        try:
            projects = ProjectRole.query.filter_by(user_id=user_id, deleted_at=None).all(a)return [p.id for p in projects], None
        except Exception as e:
            ProjectRoleDao.log.error(F "query user:{user_id}Project failure,{e}")
            return[].F "failed to query project,{e}"

    @staticmethod
    def add_project_role(user_id, project_id, project_role, user) :
        """ add user for the project :param user_id: User ID :param project_id: Project ID :param project_role: User role: param user: founder :return: """
        try:
            role = ProjectRole.query.filter_by(user_id=user_id, project_id=project_id, project_role=project_role,
                                               deleted_at=None).first()
            if role is not None:
                # Indicates that the role already exists
                return "The user already exists"
            role = ProjectRole(user_id, project_id, project_role, user)
            db.session.add(role)
            db.session.commit()
        except Exception as e:
            ProjectRoleDao.log.error(F "Failed to add project user,{e}")
            return F "Failed to add project user,{e}"
        return None

Copy the code

Here we have temporarily written two interfaces, one is to get the user’s project through the user, the other is to add the user to the project, the code is very simple, also wrote some comments. Because we need to do a quick demonstration for the time being, we can provide the function of adding and checking for the time being, and the subsequent interface will be supplemented slowly.

Write the app/dao/project/ProjectRole. Py

Since we can already get the project that he has access to through the user_id, then we can integrate it with the common project. Since there can’t be too many projects, we’ll just use the in operator.

select * from project where deleted_at is null and (owner = user or project_id in(Identified user items)or private is false);
Copy the code

It must be undeleted, owner=user, and non-private or to which the user has permission.

They are visible to all projects if they are to the super administrator.

from sqlalchemy import or_

from app import pity
from app.dao.project.ProjectRoleDao import ProjectRoleDao
from app.models import db
from app.models.project import Project
from app.utils.logger import Log


class ProjectDao(object) :
    log = Log("ProjectDao")

    @staticmethod
    def list_project(user, role, page, size, name=None) :
        """ Query/Obtain project list :param user: current user: param role: current user role: param Page: current page: param Size: current size: param name: project name: return: ""
        try:
            search = [Project.deleted_at == None]
            ifrole ! = pity.config.get("ADMIN"):
                project_list = ProjectRoleDao.list_project_by_user(user)
                search.append(or_(Project.id in project_list, Project.owner == user, Project.private == False))
            if name:
                search.append(Project.name.ilike("% {} %".format(name)))
            data = Project.query.filter(*search)
            total = data.count()
            return data.order_by(Project.created_at.desc()).paginate(page, per_page=size).items, total, None
        except Exception as e:
            ProjectDao.log.error(F "obtain user:{user}Item list failed,{e}")
            return 0.0.F "obtain user:{user}Item list failed,{e}"

    @staticmethod
    def add_project(name, owner, user, private) :
        try:
            data = Project.query.filter_by(name=name, deleted_at=None).first()
            if data is None:
                return "Project already exists"
            pr = Project(name, owner, user, private)
            db.session.add(pr)
            db.session.commit(pr)
        except Exception as e:
            ProjectDao.log.error(F "New items:{name}Failure,{e}")
            return 0.0.F "New items:{name}Failure,{e}"

Copy the code

The focus here is on list_Project, which determines if the user is ADMIN. If not, it queries the items owned by the user, which translates to the SQL we just wrote.

Finally, the items are sorted by their creation time, paging and returning the total number of items, and the third parameter is an error message.

Write concrete interfaces

  • /project/insertProject
  • /project/listProject
  • /project/insertProjectRole

Write the method app/handler/page.py for fetching paging

from flask import request

# Default page number and page number
PAGE = 1
SIZE = 10


class PageHandler(object) :

    @staticmethod
    def page() :
        """ Get page and size :return: """
        page = request.args.get("page")
        if page is None or not page.isdigit():
            page = PAGE
        size = request.args.get("size")
        if size is None or not size.isdigit():
            size = SIZE
        return int(page), int(size)

Copy the code

If we don’t get page/size or they’re not non-numbers, then we give a default value.


Space is limited, this content to here first! If I don’t cook, I’ll starve!