Exemple #1
0
def main():
    login()
    email_list = get_email_list(config["RANGE_START_NUMBER"], config["RANGE_END_NUMBER"])
    set_emails(email_list)
    invitations_respones = invitation.invitations()
    invitations_list = invitations_respones["invitations"]
    do_thread(join_team_by_invitations, invitations_list, arg_name="invitations_list", thread_num=20)
    count_number = (config["RANGE_END_NUMBER"] - config["RANGE_START_NUMBER"]) * 20
    Logger.info("总计新增人员:-------------------------{}----------------------".format(count_number))
Exemple #2
0
def authenticate():

    '''This function redirects users who got to the the authenticate page without entering a form to the login page.
       If they did enter a form, it will check if the username and password are in the database.
       If they are, it will redirect them to their home page and flash a message indicating a successful login.
       If they aren't, it will redirect them to the login page and flash a message indicating the issue.
       Whether the username or the password was incorrect.
       If they were both incorrect, the message will only indicate an issue with the username.'''

    loginStatus = ''

    #if the user got here without entering a form, redirect them to the index
    if request.method == 'GET' or not('user' in request.form.keys()):
        return redirect('/')

    #checks the user's login info or account creation
    if "pass2" in request.form.keys():
        loginStatus =  auth.register(request.form['user'],request.form['pass1'],request.form['pass2'])

    else: loginStatus = auth.login(request.form["user"],request.form["pass"])

    #if the user successsfully logs in or creates an acount, redirect them to their profile page
    if loginStatus in ["Account creation successful","Login Successful"]:
        session['user'] = request.form['user']
        return redirect('/home')

    else:
        flash(loginStatus)
        #Redirects to previous page or root if there is none
        return redirect(request.referrer or '/')
Exemple #3
0
def login():
    que = request.args
    login = auth.login(request.args['user'], request.args['pass'])
    if (login == 0):
        return render_template("landing.html", loginStatus="Invalid Login.")
    session['username'] = request.args['user']
    return redirect('/homepage')
Exemple #4
0
def authen():

    global currLat
    global currLong

    message = ''

    if request.method == 'GET' or not ('user' in request.form.keys()):
        return redirect('/')

    if "conf" in request.form.keys():
        message = auth.register(request.form['user'], request.form['pwd'],
                                request.form['conf'])

    else:
        message = auth.login(request.form['user'], request.form['pwd'])

    if message in ["Account creation successful", "Login Successful"]:
        refresh()
        session['user'] = request.form['user']
        return redirect('/track')

    else:
        flash(message)
        print(message)
        return redirect(request.referrer or '/')
Exemple #5
0
def main():
    res_login = login()
    user_uuid = res_login["user"]["uuid"]
    testplan_name_prefix = ""
    thread_num = 1
    """
    1. 提示使用者,输入测试计划name
    2. 并行线程增加任务,线程数量1~n
    3. 线程数量=1,不开thread
    4. 线程数量>1,使用threading.start方式
    5. 多线程的时候,要使用thread.join方式等待线程执行完毕
    """
    testplan_name_prefix = input("请输入testplan_name_prefix: ")
    testplan_name = testplan_name_prefix.strip()
    if testplan_name == "":
        print("您输入的testplan_name_prefix是空值")
    else:
        print("您输入的testplan_name_prefix = {}".format(testplan_name))

    thread_num = input("请输入thread_num: ")
    thread_num = int(thread_num.strip())
    if thread_num < 1:
        raise Exception("线程数量必须>=1")
    else:
        print("您输入的线程数量 = {}".format(thread_num))

    print("开始执行任务...")

    testplan_number = config['RANGE_END_NUMBER'] - config['RANGE_START_NUMBER']
    if thread_num == 1:
        add_testplan([user_uuid], user_uuid, prefix=testplan_name)
        logger.info(
            "总计新增工作项:-------------------- {} 条 ----------------------".format(
                testplan_number))
        print("任务执行完毕...")
        return

    ths = []
    count_thr = 0
    for i in range(thread_num):
        count_thr += 1
        titel = "{}t_{}".format(testplan_name, i)
        th = threading.Thread(target=add_testplan,
                              args=([user_uuid], user_uuid, titel))
        th.start()
        ths.append(th)

    for th in ths:
        print(th.getName())
        th.join()

    if count_thr != 0:
        count_space = count_thr * testplan_number
        logger.info(
            "总计新增工作项:------------------- {} 条 ----------------------".format(
                count_space))

    print("任务执行完毕...")
Exemple #6
0
def authentication():
    # if user already logged in, redirect to homepage(base.html)
    if session.get('username'):
        flash("Yikes! You're already signed in.")
        return redirect(url_for('start'))
    # user entered login form
    elif request.form.get('login'):
        print "login"
        return auth.login()
    # user didn't enter form
    else:
        return render_template('login.html', title="Login", loggedIn=False)
async def print_all_requests(email=None, pw=None, outfile='requests.csv'):
    rsession = login(email, pw)

    requests_data = await gather_all_requests(session=rsession)

    for req in requests_data:
        line = '{url}\t{id}\t{status}\t{date}\t"{desc}"\t"{depts}"\t"{pocs}"'.format(
            url=req['url'],
            id=req['id'],
            status=req['status'],
            date=req['date'],
            desc=req['desc'],
            depts=req['depts'],
            pocs=req['pocs'],
        )

        print(line, file=open(outfile, 'a'))
Exemple #8
0
def main():
    login()
    """
    1. 选择功能: 添加项目、拷贝项目
    2. 添加/拷贝项目:输入本次操作的project name前缀
    3. 拷贝项目:项目模板project uuid
    4. 设定线程数量
    """
    project_uuid = input("请输入project_uuid: ")
    project_uuid = project_uuid.strip()
    if project_uuid == "":
        raise Exception("project_uuid不能为空值")
    else:
        print("您输入的project_uuid = {}".format(project_uuid))

    project_name_prefix = input("请输入project_name_prefix: ")
    project_name_prefix = project_name_prefix.strip()
    if project_name_prefix == "":
        raise Exception("project_name_prefix不能是空值")
    else:
        print("您输入的project_name_prefix = {}".format(project_name_prefix))

    thread_num = input("请输入thread_num: ")
    thread_num = int(thread_num)
    if thread_num < 1:
        raise Exception("线程数量必须>=1")
    else:
        print("您输入的线程数量 = {}".format(thread_num))

    typ = input("""请输入操作类型:
    1. 添加项目
    2. 复制项目
    """)

    _word = {1: "添加项目", 2: "复制项目"}

    print("您输入的操作类型: {}".format(_word[int(typ)]))

    def _inner(prefix, typ_str):
        typ = int(typ_str)
        end = config["RANGE_END_NUMBER"]
        l = len(str(end))
        if typ == 2:
            for i in range(config["RANGE_START_NUMBER"], end):
                _copy_project(project_uuid, prefix + str(i).zfill(l))
        elif typ == 1:
            for item in get_json_list(prefix):
                _add_project(item)

    print("开始执行任务...")

    project_number = config['RANGE_END_NUMBER'] - config['RANGE_START_NUMBER']
    if thread_num == 1:
        _inner(project_name_prefix, typ)
        logger.info(
            "总计新增项目: ----------------- {} 个----------------------".format(
                project_number))
        print("任务执行完毕...")
        return

    ths = []
    count_thr = 0
    for i in range(thread_num):
        th = threading.Thread(target=_inner,
                              args=(project_name_prefix + str(i) + "_", typ))
        th.start()
        ths.append(th)
        count_thr += 1

    for th in ths:
        print(th.getName())
        th.join()

    if count_thr != 0:
        count_projects = count_thr * project_number
        logger.info(
            "总计新增项目:------------------ {} 个----------------------".format(
                count_projects))

    print("任务执行完毕...")
Exemple #9
0
def main():
    login()
    issue_type_uuid = "KSKtSeMc"
    project_uuid = ""
    task_name_prefix = ""
    thread_num = 1
    """
    1. 提示使用者,输入project_uuid、issue_type_uuid
    2. 并行线程增加任务,线程数量1~n
    3. 线程数量=1,不开thread
    4. 线程数量>1,使用threading.start方式
    5. 多线程的时候,要使用thread.join方式等待线程执行完毕
    """

    project_uuid = input("请输入project_uuid: ")
    project_uuid = project_uuid.strip()
    if project_uuid == "":
        raise Exception("project_uuid不能为空值")
    else:
        print("您输入的project_uuid = {}".format(project_uuid))

    issue_type_uuid = input("请输入issue_type_uuid: ")
    issue_type_uuid = issue_type_uuid.strip()
    if issue_type_uuid == "":
        raise Exception("issue_type_uuid不能为空值")
    else:
        print("您输入的issue_type_uuid = {}".format(issue_type_uuid))

    task_name_prefix = input("请输入task_name_prefix: ")
    task_name_prefix = task_name_prefix.strip()
    if task_name_prefix == "":
        print("您输入的task_name_prefix是空值")
    else:
        print("您输入的task_name_prefix = {}".format(task_name_prefix))

    thread_num = input("请输入thread_num: ")
    thread_num = int(thread_num.strip())
    if thread_num < 1:
        raise Exception("线程数量必须>=1")
    else:
        print("您输入的线程数量 = {}".format(thread_num))

    print("开始执行任务...")

    task_number = config['RANGE_END_NUMBER'] - config['RANGE_START_NUMBER']
    if thread_num == 1:
        add_task(project_uuid, issue_type_uuid, task_name_prefix)
        logger.info(
            "总计新增工作项:-------------------- {} 条 ----------------------".format(
                task_number))
        print("任务执行完毕...")
        return

    ths = []
    count_thr = 0
    for i in range(thread_num):
        count_thr += 1
        th = threading.Thread(target=add_task,
                              args=(project_uuid, issue_type_uuid,
                                    "{}t{}_".format(task_name_prefix, i)))
        th.start()
        ths.append(th)

    for th in ths:
        print(th.getName())
        th.join()

    if count_thr != 0:
        count_task = count_thr * task_number
        logger.info(
            "总计新增工作项:------------------- {} 条 ----------------------".format(
                count_task))

    print("任务执行完毕...")
Exemple #10
0
def main():
    login()
    page_uuid = ""
    space_uuid = ""
    task_name_prefix = ""
    thread_num = 1
    """
    1. 提示使用者,输入页面组space_uuid、输入页面父节点page_uuid
    2. 并行线程增加任务,线程数量1~n
    3. 线程数量=1,不开thread
    4. 线程数量>1,使用threading.start方式
    5. 多线程的时候,要使用thread.join方式等待线程执行完毕
    """

    space_uuid = input("请输入页面组space_uuid: ")
    space_uuid = space_uuid.strip()
    if space_uuid == "":
        raise Exception("页面组space_uuid不能为空值")
    else:
        print("您输入的页面组space_uuid = {}".format(space_uuid))

    page_uuid = input("请输入页面父节点page_uuid: ")
    page_uuid = page_uuid.strip()
    if page_uuid == "":
        raise Exception("页面父节点page_uuid不能为空值")
    else:
        print("您输入的页面父节点page_uuid = {}".format(page_uuid))

    page_name = input("请输入page_name_prefix: ")
    page_name_prefix = page_name.strip()
    if page_name_prefix == "":
        print("您输入的page_name_prefix是空值")
    else:
        print("您输入的page_name_prefix = {}".format(page_name_prefix))

    thread_num = input("请输入thread_num: ")
    thread_num = int(thread_num.strip())
    if thread_num < 1:
        raise Exception("线程数量必须>=1")
    else:
        print("您输入的线程数量 = {}".format(thread_num))

    print("开始执行任务...")

    task_number = config['RANGE_END_NUMBER'] - config['RANGE_START_NUMBER']
    if thread_num == 1:
        update_pages(space_uuid, page_uuid, page_name_prefix)
        logger.info(
            "总计新增工作项:-------------------- {} 条 ----------------------".format(
                task_number))
        print("任务执行完毕...")
        return

    ths = []
    count_thr = 0
    for i in range(thread_num):
        count_thr += 1
        th = threading.Thread(target=update_pages,
                              args=(space_uuid, page_uuid,
                                    "{}t{}_".format(page_name_prefix, i)))
        th.start()
        ths.append(th)

    for th in ths:
        print(th.getName())
        th.join()

    if count_thr != 0:
        count_task = count_thr * task_number
        logger.info(
            "总计新增工作项:------------------- {} 条 ----------------------".format(
                count_task))

    print("任务执行完毕...")
Exemple #11
0
def home():
    if "login" in request.form:
        message = auth.login(request.form["user"], request.form["pass"])
        flash(message)
        if message != "Login successful":
            return redirect(url_for("login"))
        else:
            session["username"] = request.form["user"]
    if "register" in request.form:
        message = auth.register(request.form["user"], request.form["pass"],
                                request.form["confirmpass"],
                                request.form["display"])
        flash(message)
        if message == "Account creation successful":
            account.change_avatar(
                request.form["user"], "https://api.adorable.io/avatars/285/" +
                request.form["user"] + ".png")
        return redirect(url_for("login"))
    if "username" not in session:
        return redirect(url_for("login"))
    if "additems" in request.args:
        print(request.args)
        date = request.args["Date"].split("-")
        print("Success Date")
        title = request.args["Title"]
        print("Success Title")
        day = date[1]
        print("Success Day")
        year = date[2]
        print("Success year")
        month = date[0]
        print("Success Month")
        time = request.args["Time"]
        print("Success Time")
        address = request.args["Address"]
        print("Success Address")
        description = request.args["Description"]
        print("Sucess Description")
        priority = int(request.args["priority"])
        print("Success priority")
        private = request.args["private"]
        if private == "public":
            private = 1
        else:
            private = 0
        if "Alerts" in request.args.keys():
            alerts = request.args["Alerts"]
        else:
            alerts = "off"
        print("Success alerts")
        adders.add_event(session["username"], title, day, year, month, time,
                         address, description, private, alerts, priority)
        print("Added")
    if "edititems" in request.args:
        print("EDITING FROM APP.PY")
        info = ["", "", "", "", "", "", "", "", "", ""]
        date = request.args["Date"].split("-")
        info[0] = request.args["Title"]
        info[1] = date[1]
        info[2] = date[2]
        info[3] = date[0]
        info[4] = request.args["Time"]
        print(info[4])
        info[5] = request.args["Address"]
        info[6] = request.args["Description"]
        private = request.args["private"]
        if private == "public":
            info[7] = 1
        else:
            info[7] = 0
        if "Alerts" in request.args.keys():
            info[8] = request.args["Alerts"]
        else:
            info[8] = "off"
        info[9] = int(request.args["priority"])
        oldname = request.args["name"]
        olddate = request.args["date"].split("-")
        oldmonth = olddate[0]
        oldday = olddate[1]
        oldyear = olddate[2]
        oldtime = request.args["time"]
        print(request.args)
        print(info)
        calendar.edit_event(session["username"], oldname, oldmonth, oldday,
                            oldyear, oldtime, info)
    if "delete" in request.args:
        print("Deleting FROM APP.PY")
        calendar.remove_event(session["username"], request.args["title"],
                              request.args["month"], request.args["day"],
                              request.args["year"], request.args["time"])
    print("ARGS:")
    print(request.args)
    display = getters.get_display(session["username"])[0]
    avatar = getters.get_avatar(session["username"])[0]
    if avatar == None:
        avatar = "https://api.adorable.io/avatars/285/" + session[
            "username"] + ".png"

    date = datetime.date.today()
    year = str(date.year)
    month = ""
    day = ""
    if date.month < 10:
        month = "0" + str(date.month)
    else:
        month = str(month)
    if date.day < 10:
        day = "0" + str(date.day)
    else:
        day = str(date.day)
    if any("item" in x for x in request.args):
        for item in request.args:
            name = request.args.get(item).split("&|")[0]
            time = ""
            try:
                time = request.args.get(item).split("&|")[1]
            except:
                time = ""
            calendar.complete_event(session["username"], name, month, day,
                                    year, time)
    todo = calendar.get_todo(session["username"], month, day, year)
    print(todo)
    numR = friends.num_requests(session["username"])
    return render_template("home.html",
                           avatar=avatar,
                           display=display,
                           todo=todo,
                           m=month,
                           d=day,
                           y=year,
                           numR=numR)
async def print_my_requests(email=None, pw=None, outfile=None):

    my_requests = []

    # log in
    rsession = login(email=email, pw=pw)

    # gather urls for all requests
    requests_data = await gather_all_requests(session=rsession)

    # fetch each request page
    request_pages = await fetch_request_pages(session=rsession,
                                              request_data=requests_data)
    for req in request_pages:
        # if it has the envelope, add it to the collection
        if req.find_all(class_='qa-envelope'):
            r_id = re.search('Request ([0-9]{2}-[0-9]+) -',
                             str(req.title)).group(1)
            my_requests.append({
                'url':
                '{}/requests/{}'.format(BASE_URL, r_id),
                'id':
                r_id,
                'status':
                req.find(class_='request-state').text.strip(),
                'date':
                datetime.datetime.strptime(
                    req.find(
                        class_='request_date').find('strong').text.strip(),
                    '%B %d, %Y'),
                'desc':
                req.find(class_='request-text').text.strip().replace(
                    '"', '\''),
                'depts':
                req.find(class_='current-department').text.strip(),
                'pocs':
                req.find(class_='request-detail').text.strip(),
                'requester':
                req.find(class_='requester-details').find(
                    class_='fa-envelope').next_sibling.strip(),
            })

    # sort collection by request date
    sorted(my_requests, key=lambda i: i['date'])
    # print collection to console and file
    out_path = os.path.abspath(os.path.join(DATA_DIR, outfile))
    url_list_path = os.path.abspath(
        os.path.join(DATA_DIR, 'my_request_urls.txt'))
    with open(out_path, 'w') as file:
        for req in my_requests:
            line = '{url}\t{id}\t{status}\t{date}\t"{desc}"\t"{depts}"\t"{pocs}"\n'.format(
                url=req['url'],
                id=req['id'],
                status=req['status'],
                date=req['date'],
                desc=req['desc'],
                depts=req['depts'],
                pocs=req['pocs'],
            )
            file.write(line)
            print(req['url'] + '\n', file=open(url_list_path, 'a'))
async def download_all_request_files(req_id,
                                     email=None,
                                     pw=None,
                                     download_files=True):
    # log in
    rsession = login(email=email, pw=pw)

    # get the "request id", which is different from the one in the URL for some stupid reason
    request_id = parse_request_id(rsession, req_id)

    doc_links = []
    for state in DOCUMENTS_SECTIONS:
        # fetch the section
        section_soup = fetch_section_soup(rsession, request_id, state)
        section_links = []

        # collect section-level document links on first page
        section_first_page_links = []
        s_num = 1
        for sfp_link in section_soup.find_all(class_='document-link'):
            section_first_page_links.append(
                parse_doc_link(sfp_link, s_num, doc_links))
            s_num = s_num + 1
        # and add them to the main collection
        print('Adding {} document links to collection.'.format(
            len(section_first_page_links)))
        section_links.extend(section_first_page_links)

        # collect folders, if any
        document_folders = section_soup.find_all(class_='fa-folder')
        # if there are folders, we need the labels to fetch the folder content
        folder_labels = []
        for folder in document_folders:
            folder_labels.append(parse_folder_label(folder))

        # use the folder labels to fetch content of each folder
        for label in folder_labels:
            folder_soup = fetch_folder_soup(rsession, label, state, request_id)

            # collect folder-level document links on first page of folder
            folder_first_page_links = []
            ffp_num = 1
            for ffp_link in folder_soup.find_all(class_='document-link'):
                folder_first_page_links.append(
                    parse_doc_link(ffp_link, ffp_num, doc_links,
                                   sub_dir=label))
                ffp_num = ffp_num + 1
            # and add them to the main collection
            print('Adding {} document links to collection.'.format(
                len(folder_first_page_links)))
            section_links.extend(folder_first_page_links)

            # check for additional folder-level pages
            if folder_soup.find_all(class_='pagination'):
                # determine how many pages there are in the folder
                folder_page_count = parse_folder_page_count(folder_soup)
                # collect document links from each folder page
                for fp_page in range(2, folder_page_count + 1):
                    # fetch the folder page
                    folder_page_soup = fetch_folder_page_soup(
                        rsession, label, state, request_id, fp_page)

                    # collect folder-level document links on the folder page
                    folder_page_links = []
                    fp_num = 1
                    for fp_link in folder_page_soup.find_all(
                            class_='document-link'):
                        folder_page_links.append(
                            parse_doc_link(fp_link,
                                           fp_num,
                                           doc_links,
                                           sub_dir=label))
                        fp_num = fp_num + 1
                    # and add them to the main collection
                    print('Adding {} document links to collection.'.format(
                        len(folder_page_links)))
                    section_links.extend(folder_page_links)

        # check for additional section-level pages
        if section_soup.find_all(class_='pagination'):
            # determine how many pages there are in the section
            section_page_count = parse_section_page_count(section_soup)
            # collect document links from each section page
            for s_page in range(2, section_page_count + 1):
                # fetch section page
                section_page_soup = fetch_section_page_soup(
                    rsession, state, request_id, s_page)

                # collect section-level document links on section page
                section_page_links = []
                sp_num = 1
                for sp_link in section_page_soup.find_all(
                        class_='document-link'):
                    links = parse_doc_link(sp_link, sp_num, doc_links)
                    section_page_links.append(links)
                    sp_num = sp_num + 1
                # and add them to the main collection
                print('Adding {} document links to collection.'.format(
                    len(section_page_links)))
                section_links.extend(section_page_links)

        doc_links.extend(section_links)

    link_filename = '{}_links.txt'.format(req_id)
    link_file_path = os.path.abspath(os.path.join(DATA_DIR, link_filename))
    with open(link_file_path, 'w') as file:
        for l in doc_links:
            file.write(l['url'] + '\n')

    if download_files:
        batches = batch_data(data=doc_links, batch_size=50)
        for batch in batches:
            await asyncio.gather(*[
                adownload_file(
                    url=d['url'],
                    filename=d['filename'],
                    headers=rsession.headers,
                    cookies=rsession.cookies,
                    sub_dir='{}/{}'.format(req_id, d['sub_dir']),
                    msg='',
                ) for d in batch
            ])

    rsession.close()
async def download_all_documents(email=None, pw=None):
    """Download all the files found at /documents. Can be run without auth, but will only include
    all files with auth.

    Args:
        email (str):
        pw (str):
    """
    rsession = login(email, pw)

    # fetch the first page of the documents list to calculate the number of pages.
    count_response = rsession.get(
        '{}?documents_smart_listing[per_page]=100'.format(DOCUMENTS_URL))

    # get the total number of results...
    results_count = int(
        bs(count_response.content, 'html.parser').find(class_='count').text)
    # and calculate number of pages when 100 results are shown per page.
    page_count = math.ceil(results_count / 100)
    # build a list of urls from the page numbers and other parameters
    per_page_param = 'documents_smart_listing[per_page]={}'.format(100)
    sort_param = 'documents_smart_listing[sort][count]=desc'
    params = '&'.join([per_page_param, sort_param])
    page_params = [
        'documents_smart_listing[page]={}'.format(p)
        for p in range(1, page_count + 1)
    ]
    list_page_urls = [
        '{}/documents?{}&{}'.format(BASE_URL, pp, params) for pp in page_params
    ]

    # use asession to asynchronously fetch each of the urls in the list
    asession = aiohttp.ClientSession(
        headers=rsession.headers,
        cookies=rsession.cookies,
    )
    dl_data = []

    async with asession:
        # fetch each page of the documents list
        list_page_responses = await asyncio.gather(
            *[afetch(asession, u) for u in list_page_urls])
        doc_page_urls = set()

        for list_page_response in list_page_responses:
            response_text = list_page_response['text']
            soup = bs(response_text, 'html.parser')
            doc_links = soup.find_all(class_='document published')
            print('found {} links on page.'.format(len(doc_links)))
            doc_page_urls.update(
                ['{}{}'.format(BASE_URL, link['href']) for link in doc_links])

        # fetch each of the document pages to get the full filename (since the list tends to cut them off)
        doc_page_responses = await asyncio.gather(
            *[afetch(asession, d) for d in doc_page_urls])
        num = 1

        for doc_page_response in doc_page_responses:
            doc_page = bs(doc_page_response['text'], 'html.parser')
            page_header = doc_page.find(class_='document-header')

            if page_header:
                filename = build_filename(page_header,
                                          doc_page_response['url'])
            else:
                filename = 'missing filename {}'.format(
                    parse_document_id(doc_page_response['url']))

            if not filename:
                print('failed to parse filename for file at {}'.format(
                    doc_page_response['url']))
            dl_data.append({
                'filename': filename,
                'url': doc_page_response['url'],
                'num': num,
            })
            num = num + 1
        total = len(dl_data)

        # download each file and save it to the appropriate location
        await asyncio.gather(*[
            adownload_file(
                headers=rsession.headers,
                cookies=rsession.cookies,
                url=d['url'],
                filename=d['filename'],
                sub_dir='documents',
                msg='{}/{}'.format(d['num'], total),
            ) for d in dl_data if d['url']
        ])
Exemple #15
0
def main():
    res_login = login()
    user_uuid = res_login["user"]["uuid"]
    thread_num = 1
    """
    1. 提示使用者,输入用例库:testcase_library、testcase_module的uuid
    2. 并行线程增加任务,线程数量1~n
    3. 线程数量=1,不开thread
    4. 线程数量>1,使用threading.start方式
    5. 多线程的时候,要使用thread.join方式等待线程执行完毕
    """

    testcase_library_uuid = input("请输入用例库testcase_library_uuid: ")
    testcase_library = testcase_library_uuid.strip()
    if testcase_library == "":
        raise Exception("页面组testcase_library_uuid不能为空值")
    else:
        print("您输入的用例库testcase_library_uuid = {}".format(testcase_library))

    testcase_module_uuid = input("请输入用例模块的testcase_module_uuid: ")
    testcase_module = testcase_module_uuid.strip()
    if testcase_module == "":
        raise Exception("用例模块的testcase_module_uuid不能为空值")
    else:
        print("您输入的用例模块testcase_module_uuid = {}".format(testcase_module))

    testcase_name_prefix = input("请输入testcase_name_prefix: ")
    testcase_name = testcase_name_prefix.strip()
    if testcase_name == "":
        print("您输入的testcase_name_prefix是空值")
    else:
        print("您输入的testcase_name_prefix = {}".format(testcase_name))

    thread_num = input("请输入thread_num: ")
    thread_num = int(thread_num.strip())
    if thread_num < 1:
        raise Exception("线程数量必须>=1")
    else:
        print("您输入的线程数量 = {}".format(thread_num))

    print("开始执行任务...")

    testcase_number = config['RANGE_END_NUMBER'] - config['RANGE_START_NUMBER']
    if thread_num == 1:
        add_testcase(testcase_library,
                     testcase_module,
                     user_uuid,
                     prefix=testcase_name)
        logger.info(
            "总计新增工作项:-------------------- {} 条 ----------------------".format(
                testcase_number))
        print("任务执行完毕...")
        return

    ths = []
    count_thr = 0
    for i in range(thread_num):
        count_thr += 1
        time.sleep(0.5)
        th = threading.Thread(target=add_testcase,
                              args=(testcase_library, testcase_module,
                                    user_uuid,
                                    "{}t{}_".format(testcase_name, i)))
        th.start()
        time.sleep(0.5)
        ths.append(th)

    for th in ths:
        print(th.getName())
        th.join()

    if count_thr != 0:
        count_testcase = count_thr * testcase_number
        logger.info(
            "总计新增工作项:------------------- {} 条 ----------------------".format(
                count_testcase))

    print("任务执行完毕...")