Best Python code snippet using tempest_python
account.py
Source:account.py  
1from flask import Flask, request, jsonify2from flask_cors import CORS3from invokes import invoke_http4from passlib.hash import sha256_crypt5import os6from datetime import timedelta, datetime7from password import *8from emailHandling import *9from dotenv import load_dotenv10load_dotenv()11app = Flask(__name__)12CORS(app) 13ACCOUNT_PORT = os.getenv("ACCOUNT_PORT")14USER_PORT = os.getenv("USER_PORT")15SYSTEM_CONFIG_PORT = os.getenv("SYSTEM_CONFIG_PORT")16CERTFILE = os.getenv("CERT_FILE")17KEYFILE = os.getenv("KEY_FILE")18adminDetailsUrl = os.environ.get('adminDetailsUrl') or f"http://localhost:{USER_PORT}/getAdmin"19updateAdminPasswordUrl = os.environ.get('updateAdminPasswordUrl') or f"http://localhost:{USER_PORT}/updateAdminPassword"20addStudentUrl = os.environ.get('addStudentUrl') or f"http://localhost:{USER_PORT}/addStudent"21studentDetailsUrl = os.environ.get('studentDetailsUrl') or f"http://localhost:{USER_PORT}/getStudent"22updateStudentPasswordUrl = os.environ.get('updateStudentPasswordUrl') or f"http://localhost:{USER_PORT}/updateStudentPassword"23taDetailsUrl = os.environ.get('taDetailsUrl') or f"http://localhost:{USER_PORT}/getTA"24addFacultyUrl = os.environ.get('addFacultyUrl') or f"http://localhost:{USER_PORT}/addFaculty"25facultyDetailsUrl = os.environ.get('facultyDetailsUrl') or f"http://localhost:{USER_PORT}/getFaculty"26updateFacultyPasswordUrl = os.environ.get('updateFacultyPasswordUrl') or f"http://localhost:{USER_PORT}/updateFacultyPassword"27addInstructorUrl = os.environ.get('addInstructorUrl') or f"http://localhost:{USER_PORT}/addInstructorUrl"28instructorDetailsUrl = os.environ.get('instructorDetailsUrl') or f"http://localhost:{USER_PORT}/getInstructor"29updateInstructorPasswordUrl = os.environ.get('updateInstructorPasswordUrl') or f"http://localhost:{USER_PORT}/updateInstructorPassword"30def getTestMode():31    getConfigurationUrl = os.environ.get('getConfigurationUrl') or f"http://localhost:{SYSTEM_CONFIG_PORT}/getConfiguration"32    config = invoke_http(getConfigurationUrl, method='GET')33    if config:34        testMode = config['data']['testMode']35    36    return testMode37# Login Authentication38@app.route("/loginAuthentication", methods=["POST"])39def loginAuthentication():40    if request.is_json:41        loginInput = request.get_json()42        inputEmail = loginInput['email']43        inputPassword = loginInput['password']44        acadYear = loginInput['acadYear']45        termNo = loginInput['termNo']46        studentDetails = invoke_http(f"{studentDetailsUrl}/{inputEmail}", method='GET')47        taDetails = invoke_http(f"{taDetailsUrl}/{inputEmail}/{acadYear}/{termNo}", method='GET')48        adminDetails = invoke_http(f"{adminDetailsUrl}/{inputEmail}", method='GET')49        facultyDetails = invoke_http(f"{facultyDetailsUrl}/{inputEmail}", method='GET')50        instructorDetails = invoke_http(f"{instructorDetailsUrl}/{inputEmail}", method='GET')51        if studentDetails["code"] == 200:52            if studentDetails['data']['lastLogin']:53                lastLogin = datetime.strptime(studentDetails['data']['lastLogin'], "%d %b %Y %H:%M")54                if (studentDetails['data']['isLogin'] != 0) and (datetime.now() - lastLogin) < timedelta(hours = 12):55                    return jsonify(56                        {57                            "code": 409,58                            "message": "You have already logged in."59                        }60                    ), 40961            62            hashedPassword = studentDetails["data"]["password"]63            if sha256_crypt.verify(inputPassword, hashedPassword):64                65                if taDetails["code"] == 200:66                    identity = "mixed"67                else:68                    identity = "student"69                output = {70                    "code": 200,71                    "identity": identity,72                    "details": studentDetails["data"]73                }74                return jsonify(75                    {76                        "code": 200,77                        "data": output78                    }79                ), 20080            else:81                return jsonify(82                    {83                        "code": 403,84                        "message": "Wrong password."85                    }86                ), 40387        88        elif facultyDetails["code"] == 200:89            if facultyDetails['data']['lastLogin']:90                lastLogin = datetime.strptime(facultyDetails['data']['lastLogin'], "%d %b %Y %H:%M")91                if (facultyDetails['data']['isLogin'] != 0) and (datetime.now() - lastLogin) < timedelta(hours = 12):92                    return jsonify(93                        {94                            "code": 409,95                            "message": "You have already logged in."96                        }97                    ), 40998            99            hashedPassword = facultyDetails["data"]["password"]100            if sha256_crypt.verify(inputPassword, hashedPassword):101                102                output = {103                    "code": 200,104                    "identity": "faculty",105                    "details": facultyDetails["data"]106                }107                return jsonify(108                    {109                        "code": 200,110                        "data": output111                    }112                ), 200113            else:114                return jsonify(115                    {116                        "code": 403,117                        "message": "Wrong password."118                    }119                ), 403120        elif instructorDetails["code"] == 200:121            if instructorDetails['data']['lastLogin']:122                lastLogin = datetime.strptime(instructorDetails['data']['lastLogin'], "%d %b %Y %H:%M")123                if (instructorDetails['data']['isLogin'] != 0) and (datetime.now() - lastLogin) < timedelta(hours = 12):124                    return jsonify(125                        {126                            "code": 409,127                            "message": "You have already logged in."128                        }129                    ), 409130            hashedPassword = instructorDetails["data"]["password"]131            if sha256_crypt.verify(inputPassword, hashedPassword):132                133                output = {134                    "code": 200,135                    "identity": "instructor",136                    "details": instructorDetails["data"]137                }138                return jsonify(139                    {140                        "code": 200,141                        "data": output142                    }143                ), 200144            else:145                return jsonify(146                    {147                        "code": 403,148                        "message": "Wrong password."149                    }150                ), 403151        152        elif adminDetails["code"] == 200:153            if adminDetails['data']['lastLogin']:154                lastLogin = datetime.strptime(adminDetails['data']['lastLogin'], "%d %b %Y %H:%M")155                if (adminDetails['data']['isLogin'] != 0) and (datetime.now() - lastLogin) < timedelta(hours = 12):156                    return jsonify(157                        {158                            "code": 409,159                            "message": "You have already logged in."160                        }161                    ), 409162            hashedPassword = adminDetails["data"]["password"]163            if sha256_crypt.verify(inputPassword, hashedPassword):164                165                output = {166                    "code": 200,167                    "identity": "admin",168                    "details": adminDetails["data"]169                }170                return jsonify(171                    {172                        "code": 200,173                        "data": output174                    }175                ), 200176            else:177                return jsonify(178                    {179                        "code": 403,180                        "message": "Wrong password."181                    }182                ), 403183        return jsonify(184            {185                "code": 404,186                "message": "User not found."187            }188        ), 404189    else:190        return jsonify(191            {192                "code": 500,193                "message": 'Input is not JSON.'194            }195        ), 500196@app.route("/resetPassword/<string:email>", methods=['PUT'])197def resetPassword(email):198    studentDetails = invoke_http(f"{studentDetailsUrl}/{email}", method='GET')199    adminDetails = invoke_http(f"{adminDetailsUrl}/{email}", method='GET')200    facultyDetails = invoke_http(f"{facultyDetailsUrl}/{email}", method='GET')201    instructorDetails = invoke_http(f"{instructorDetailsUrl}/{email}", method='GET')202    203    rand_password = generateRandomPassword()204    dataOutput = None205    if studentDetails["code"] == 200:206        invoke_http(f"{updateStudentPasswordUrl}/{email}/{rand_password}", method='PUT')207        dataOutput = studentDetails208    elif facultyDetails["code"] == 200:209        invoke_http(f"{updateFacultyPasswordUrl}/{email}/{rand_password}", method='PUT')210        dataOutput = facultyDetails211    elif instructorDetails["code"] == 200:212        invoke_http(f"{updateInstructorPasswordUrl}/{email}/{rand_password}", method='PUT')213        dataOutput = instructorDetails214    elif adminDetails["code"] == 200:215        invoke_http(f"{updateAdminPasswordUrl}/{email}/{rand_password}", method='PUT')216        dataOutput = adminDetails217    if dataOutput == None:218        return jsonify(219            {220                "code": 404,221                "message": "User not found."222            }223        ), 404224    225    testMode = getTestMode()226    sendResetPasswordEmail(email, PASSWORD_RESET_EMAIL_SUBJECT, rand_password, testMode)227    return jsonify(228        {229            "code": 200,230            "data": dataOutput,231            "message": "Password reset and email sent to user."232        }233    ), 200234@app.route("/createStudentAccount", methods=["POST"])235def createStudentAccount():236    if request.is_json:237        accountDetails = request.get_json()238        testMode = getTestMode()239        if testMode == 0:240            rand_password = generateRandomPassword()241        else:242            rand_password = "password"243        hashed_password = hashPassword(rand_password)244        accountInfo = {245            "email": accountDetails['email'].strip(),246            "name": accountDetails['name'],247            "password": hashed_password248            # "actualPassword": rand_password249        }250        studentDetails = invoke_http(addStudentUrl, method="POST", json=accountInfo)251        if studentDetails["code"] == 200:252            sendPasswordEmail(accountDetails['email'].strip(), NEW_ACCOUNT_EMAIL_SUBJECT, rand_password, testMode)253        return studentDetails254    else:255        return jsonify(256            {257                "code": 500,258                "message": 'Input is not JSON.'259            }260        ), 500261@app.route("/createFacultyAccount", methods=["POST"])262def createFacultyAccount():263    if request.is_json:264        accountDetails = request.get_json()265        testMode = getTestMode()266        if testMode == 0:267            rand_password = generateRandomPassword()268        else:269            rand_password = "password"270        hashed_password = hashPassword(rand_password)271        accountInfo = {272            "email": accountDetails['email'].strip(),273            "name": accountDetails['name'],274            "password": hashed_password275            # "actualPassword": rand_password276        }277        facultyDetails = invoke_http(addFacultyUrl, method="POST", json=accountInfo)278        if facultyDetails["code"] == 200:279            sendPasswordEmail(accountDetails['email'].strip(), NEW_ACCOUNT_EMAIL_SUBJECT, rand_password, testMode)280        return facultyDetails281    else:282        return jsonify(283            {284                "code": 500,285                "message": 'Input is not JSON.'286            }287        ), 500288@app.route("/createInstructorAccount", methods=["POST"])289def createInstructorAccount():290    if request.is_json:291        accountDetails = request.get_json()292        testMode = getTestMode()293        if testMode == 0:294            rand_password = generateRandomPassword()295        else:296            rand_password = "password"297        hashed_password = hashPassword(rand_password)298        accountInfo = {299            "email": accountDetails['email'].strip(),300            "name": accountDetails['name'],301            "password": hashed_password302            # "actualPassword": rand_password303        }304        instructorDetails = invoke_http(addInstructorUrl, method="POST", json=accountInfo)305        if instructorDetails["code"] == 200:306            sendPasswordEmail(accountDetails['email'].strip(), NEW_ACCOUNT_EMAIL_SUBJECT, rand_password, testMode)307        return instructorDetails308    else:309        return jsonify(310            {311                "code": 500,312                "message": 'Input is not JSON.'313            }314        ), 500315if __name__=='__main__':316    if os.getenv("LOCAL") == 'False':317        app.run(ssl_context=(CERTFILE, KEYFILE), host='0.0.0.0', port=ACCOUNT_PORT)318    else:...initadmin.py
Source:initadmin.py  
1# coding=utf-82from django.core.management.base import BaseCommand3from account.models import User, SUPER_ADMIN, UserProfile4from utils.shortcuts import rand_str5class Command(BaseCommand):6    def handle(self, *args, **options):7        try:8            admin = User.objects.get(username="root")9            if admin.admin_type == SUPER_ADMIN:10                self.stdout.write(self.style.WARNING("Super admin user 'root' already exists, "11                                                     "would you like to reset it's password?\n"12                                                     "Input yes to confirm: "))13                if raw_input() == "yes":14                    rand_password = rand_str(length=6)15                    admin.set_password(rand_password)16                    admin.save()17                    self.stdout.write(self.style.SUCCESS("Successfully created super admin user password.\n"18                                                         "Username: root\nPassword: %s\n"19                                                         "Remember to change password and turn on two factors auth "20                                                         "after installation." % rand_password))21                else:22                    self.stdout.write(self.style.SUCCESS("Nothing happened"))23            else:24                self.stdout.write(self.style.ERROR("User 'root' is not super admin."))25        except User.DoesNotExist:26            user = User.objects.create(username="root", real_name="root", email="root@oj.com", admin_type=SUPER_ADMIN)27            rand_password = rand_str(length=6)28            user.set_password(rand_password)29            user.save()30            UserProfile.objects.create(user=user)31            self.stdout.write(self.style.SUCCESS("Successfully created super admin user.\n"32                                                 "Username: root\nPassword: %s\n"33                                                 "Remember to change password and turn on two factors auth "...Password_Generator.py
Source:Password_Generator.py  
1import string2import random3Letter=string.ascii_letters4Number= string.digits5Punctuation= string.punctuation6#Determine the password length7def password_length():8    length= input("Please write the password length: ")9    return int(length)10#Generate the password11def password_generator(option,length=11):12    #generate the password13    password= password_content(option)14    #convert it to list and shuffle it15    password=   list(password)16    random.shuffle(password)17    rand_password=  random.choices(password, k= length)18    rand_password=  ''.join(rand_password)19    return rand_password20    21#print("The first password( "+str(len(first_pass))+"):\t\t"+first_pass)22#print("The second password( "+str(len(second_pass))+"):\t\t"+second_pass)23#Choose password content(letter, number, punctuation)24def choose_content():25    letters=    input("Do you want letters? (True/False): ")26    numbers=    input("Do you want numbers? (True/False):")27    punctuations=   input("Do you want punctuations? (True/False): ")28    try:29        letters=    eval(letters.title())30        numbers=    eval(numbers.title())31        punctuations=   eval(punctuations.title())32        return [letters, numbers, punctuations]33    except NameError as e:34        print("Invalid value. Use True or False")35        print("Try again!!")36    return [True,True, True]37def password_content(content):38    password=   ''39    password+=  Letter if content[0] else ''40    password+=  Number if content[1] else ''41    password+=  Punctuation if content[2] else ''42    return password43if __name__=='__main__':44    length=     password_length()45    content=    choose_content()46    passwrod=   password_generator(content, length)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
