【问题标题】:forloop in flask code arguments not looping for the second position烧瓶代码参数中的for循环不循环第二个位置
【发布时间】:2020-09-08 15:27:34
【问题描述】:

我正在研究一个用例,通过 PyAD 在 AD 中创建组,并通过 flask 为该文件夹创建文件夹和组。

我使用 for 循环来传递参数和返回响应。如果组存在,则代码不应创建,否则应创建,然后继续创建文件夹并设置权限。

但是对于传入请求的第一组逻辑工作正常,但第二组没有进入循环。

面临使其通过烧瓶和处理响应工作的问题。有没有办法实现它,请帮忙。

app = Flask(__name__)
api = Api(app)
#Class to create fileshare

class Test(Resource):
    def post(self):
        pythoncom.CoInitialize()
        # Get JSON arguments from Payload shared NAS path, directorname  groupname with read access and right access
        parentdir = request.json.get("shareUNCPath")
        dirname = request.json.get("shareFolderName")
        readGroup = request.json.get("readGroup")
        writeGroup = request.json.get("writeGroup")
        domainName = request.json.get("domain")
        groupList = [readGroup,writeGroup]
        #for gn in groupList:
        try:
            j=(len(groupList))+1
            if readGroup == writeGroup:
                j=(len(groupList))-1
            #for gn in len(groupList):
            for i in range(4):
                groupName = groupList[i]
                pyad.set_defaults(username="username", password="password", ldap_server="ldapServer")
                rGroup = adgroup.ADGroup.from_cn(groupName)
                logging.debug("read group {} available in AD ".format(groupName))
                if __name__ == "__main__":
                    os.makedirs(path)
                    igroup, domain, type = win32security.LookupAccountName (domainName, groupName)
                    sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
                    dacl = sd.GetSecurityDescriptorDacl()
                    logging.debug("Domain1 {}, Group1 {}".format(domainName, groupName))
                    if groupName in readGroup:                              
                        dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_READ, igroup)
                    if groupName in writeGroup:
                        dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_WRITE, igroup)
                    isdir = os.path.isdir(path)
                    if isdir == True:
                        sd.SetSecurityDescriptorDacl(1, dacl, 0)
                        win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
                        dacl = sd.GetSecurityDescriptorDacl()
                        cnt=dacl.GetAceCount()
                        for  i in range(0, cnt):
                            rev, access, usersid = dacl.GetAce(i)
                            user, group, type = win32security.LookupAccountSid(domainName, usersid)
                            details = ('Group: {}/{}'.format(group, user), rev,  access)))
                            resp = Response('Successfully created file share {}. Details {}'.format(dirname, details))
                            print (resp)
                                resp.status_code = 200
                                return resp

        except Exception as e:
            errormsg = str(e)
            print (errormsg)
            if "The server is not operational" in errormsg:
                resp = Response('AD operation failed, unable to connect to Active Directory. Error - {}'.format(e))
                print (resp)
                resp.status_code = 301
                return resp
            else:
                try:
                    for i in range(4):
                        groupName = groupList[i]  
                        pyad.set_defaults(username="username", password="pasword",ldap_server="ldapServer")
                        ou = pyad.adcontainer.ADContainer.from_dn(group_OU)
                        rGroup = adgroup.ADGroup.create(
                            name=groupName,
                            security_enabled = True,
                            scope=groupScope,
                            container_object=ou,
                            optional_attributes={"description": description}
                        )
                        if rGroup.Displayname == (groupName):                           
                            if __name__ == "__main__":
                                os.makedirs(path)
                                #groupr = win32security.LookupAccountName ("", readGroup)
                                a.logon()
                                time.sleep(5)
                                igroup, domain, type = win32security.LookupAccountName (domainName, groupName)
                                sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
                                #dacl = win32security.ACL()
                                dacl = sd.GetSecurityDescriptorDacl()
                                #acl = pywintypes.ACL()
                                #set permessions for readGroup with GENERIC_READ level permessions
                                #dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_READ, groupr)
                                if groupName in readGroup:
                                    dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION,con.OBJECT_INHERIT_ACE|con.CONTAINER_INHERIT_ACE,con.GENERIC_READ|con.GENERIC_EXECUTE, igroup)
                                if groupName in writeGroup:
                                    dacl.AddAccessAllowedAce(win32security.ACL_REVISION,con.GENERIC_WRITE, igroup)
                                isdir = os.path.isdir(path)
                                if isdir == True:
                                    sd.SetSecurityDescriptorDacl(1, dacl, 0)
                                    win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
                                    dacl = sd.GetSecurityDescriptorDacl()
                                    cnt=dacl.GetAceCount()
                                    for  i in range(0, cnt):
                                        rev, access, usersid = dacl.GetAce(i)
                                        user, group, type = win32security.LookupAccountSid(domainName, usersid)
                                        details = ('Group: {}/{}'.format(group, user), rev,  access)
                                        #return ("Success Fileshare created: {} ".format(dirname))
                                        resp = Response('Successfully created file share {}. Details {}'.format(dirname, details))
                                        print (resp)
                                        resp.status_code = 200
                                        return resp

            except Exception as e:
                print(e)
                resp = Response('AD operation failed, unable to create to group {}. Error - {}'.format(groupName, e))
                print (resp)
                resp.status_code = 302
                return resp

api.add_resource(Test, '/test')

if __name__ == "__main__":

    #context = ('local.crt', 'local.key')#certificate and key files
    app.run(port="7050", host="0.0.0.0", use_reloader=True)

【问题讨论】:

    标签: python python-3.x for-loop flask flask-restful


    【解决方案1】:

    我查看了您的代码。有两点需要改变。

    • 您使用i 作为外循环和内循环的循环变量
    • 在第一个循环中,您使用异常来触发组创建。这将退出循环,不再处理任何组。您应该在 range(4) 循环内移动异常块。

    这是您的 cmets 代码。

    class Test(Resource):
        def post(self):
            .......
            try:
                ..........
                for i in range(4):  # using i as loop variable, loop will exit if exception
                    ........
                    if __ name __ == "__ main __":  # if group exists, update permissions, throws exception if group does not exist
                        ........
                        if isdir == True:
                            ........
                            for  i in range(0, cnt):  # using i as loop variable, again
                                .........
    
            # here is the problem - if the first group does not exist, an exception is thrown and the other groups are not processed
            except Exception as e:   # group does not exist, must add # You should move this inside the for loop
                ............
                    try:
                        for i in range(4):  # using i as loop variable
                            ...........
                            if rGroup.Displayname == (groupName):                           
                                if __ name __ == "__main__":
                                    .........
                                    if isdir == True:
                                        ........
                                        for  i in range(0, cnt):  # using i as loop variable, again
                                            ..........
    

    澄清一下,整体逻辑应该是这样的:

    for i in range(4):  # each group
        try:
             # update permissions
        except Exception as e:
             # add new group
    

    作为附注,尝试检查组是否存在而不使用 try\except 块。在正常的程序流程中不应使用异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2013-12-12
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多