Best Python code snippet using tempest_python
app.py
Source:app.py
1# https://docs.nextcloud.com/server/latest/admin_manual/configuration_user/reset_user_password.html2import re3import requests4import secrets5import os6from flask import Flask, request, redirect, render_template, send_file7from flask_mail import Mail, Message8from flask_recaptcha import ReCaptcha9import urllib.parse10an_api_key = os.environ.get("AN_API_KEY") # Expects an Action Nework API Key11nc_host = os.environ.get("NC_HOST") # Expects the root URL of the NextCloud instance12nc_user = os.environ.get("NC_USER") # Expects a nextcloud username for an account with API access13nc_password = os.environ.get("NC_PASSWORD") # Expects an app password for the username above)14nc_url = nc_host.replace("://","://{}:{}@".format(nc_user, nc_password)) 15nc_instance_name = os.environ.get("NC_INSTANCE_NAME")16an_instance_name = os.environ.get("AN_INSTANCE_NAME")17app = Flask(__name__)18app.config['MAIL_SERVER'] = os.environ.get("MAIL_SERVER")19app.config['MAIL_PORT'] = os.environ.get("MAIL_PORT")20app.config['MAIL_USE_SSL'] = os.environ.get("MAIL_USE_SSL")21app.config['MAIL_USERNAME'] = os.environ.get("MAIL_USERNAME")22app.config['MAIL_DISPLAYNAME'] = os.environ.get("MAIL_DISPLAYNAME")23app.config['MAIL_PASSWORD'] = os.environ.get("MAIL_PASSWORD")24app.config['RECAPTCHA_ENABLED'] = True25app.config['RECAPTCHA_SITE_KEY'] = os.environ.get("RECAPTCHA_SITE_KEY")26app.config['RECAPTCHA_SECRET_KEY'] = os.environ.get("RECAPTCHA_SECRET_KEY")27recaptcha = ReCaptcha(app=app)28mail = Mail(app)29def an_status_check(person):30 "Action Network Status Check. This will need to be customised depending on the fields that should be checked in any given instance."31 if(person['custom_fields']['Membership_Status'] == 'Current' and person['custom_fields']['Local_Party'] == "Stroud District Green Party"):32 return True33 else:34 return False35@app.route("/")36def main():37 return render_template('form.html', nc_host=nc_host, email='', message='')38@app.route("/action", methods=['GET', 'POST'])39def check_user():40 email = request.form['email']41 if recaptcha.verify():42 nc_users = search_nc_user(email)43 if not nc_users['ocs']['meta']['status'] == 'ok':44 return render_template('error.html', nc_host=nc_host, nc_instance_name=nc_instance_name)45 if len(nc_users) > 1:46 return render_template('error.html', nc_host=nc_host, nc_instance_name=nc_instance_name)47 elif len(nc_users['ocs']['data']['users']) == 1:48 if reset_nc_password(nc_users['ocs']['data']['users'][0], email):49 return render_template('message.html', nc_host=nc_host, message="E-mail sent")50 else:51 return render_template('error.html', nc_host=nc_host, nc_instance_name=nc_instance_name)52 else:53 # We didn't find a nextcloud user, check them in ActionNetwork54 an_user = search_an_users(email)55 if an_user:56 create_nc_user(an_user, email)57 else:58 msg = Message("{} account information".format(nc_instance_name),59 sender=(app.config['MAIL_DISPLAYNAME'], app.config['MAIL_USERNAME']),60 recipients=[email],61 body=render_template('mail_no_account.txt', nc_instance_name=nc_instance_name, an_instance_name=an_instance_name, email=email))62 mail.send(msg)63 64 return render_template('message.html', nc_host=nc_host, message="E-mail sent")65 else:66 return render_template('form.html', nc_host=nc_host, email=email, message='CAPTCHA not completed correctly. Please try again.')67def search_nc_user(email):68 "Search for a NextCloud user by e-mail address"69 nc_headers = {'OCS-APIRequest': 'true'}70 ncr = requests.get(71 nc_url+"/ocs/v1.php/cloud/users?format=json&search={}".format(urllib.parse.quote(email)), headers=nc_headers)72 return ncr.json()73def create_nc_user(an_user, email):74 "Create a new nextcloud user based on an Action Network user"75 nc_headers = {'OCS-APIRequest': 'true'}76 password = secrets.token_urlsafe(15)77 username = re.sub(r'\W+', '', an_user['given_name']+an_user['family_name'])78 displayname = "{} {}".format(an_user['given_name'], an_user['family_name'])79 payload = {"userid": username,80 "password": password,81 "displayName": displayname,82 "email": email,83 "groups[]": ["Members"]84 }85 ncr = requests.post(nc_url+"/ocs/v1.php/cloud/users?format=json",86 data=payload,87 headers=nc_headers)88 print("Trying to create user")89 print(payload)90 print(ncr.json())91 if ncr.json()['ocs']['meta']['status'] == 'ok':92 msg = Message("Your {} account has been created".format(nc_instance_name),93 sender=(app.config['MAIL_DISPLAYNAME'],94 app.config['MAIL_USERNAME']),95 recipients=[email],96 body=render_template('mail_new_account.txt', nc_host=nc_host, displayname=displayname, username=username, email=email, password=password, nc_instance_name=nc_instance_name))97 mail.send(msg)98 return True99 else:100 return False101 102 pass103 104def reset_nc_password(user, email):105 "Create a new password for a NextCloud user and send it to them by e-mail"106 nc_headers = {'OCS-APIRequest': 'true'} 107 password = secrets.token_urlsafe(15)108 ncr = requests.put(nc_url+"/ocs/v1.php/cloud/users/{}?format=json".format(user),109 data={"key":"password", "value": password},110 headers=nc_headers)111 if ncr.json()['ocs']['meta']['status'] == "ok":112 msg=Message("Your {} account password has been reset".format(nc_instance_name),113 sender=(app.config['MAIL_DISPLAYNAME'],114 app.config['MAIL_USERNAME']),115 recipients=[email],116 body=render_template('mail_password_reset.txt', nc_host=nc_host, user=user, email=email, password=password, nc_instance=nc_instance_name))117 mail.send(msg)118 return True119 else:120 return False121def search_an_users(email):122 "Search for an Action Network user by e-mail address"123 an_headers = {'OSDI-API-Token': an_api_key }124 anr = requests.get("https://actionnetwork.org/api/v2/people?filter=email_address eq '{}'".format(email),125 headers=an_headers)126 try:127 if len(anr.json()['_embedded']['osdi:people']) == 1:128 if an_status_check(anr.json()['_embedded']['osdi:people'][0]):129 return anr.json()['_embedded']['osdi:people'][0]130 else:131 return False132 else:133 return False134 except:135 return False136if __name__ == '__main__':...
ncov_clockin.py
Source:ncov_clockin.py
1import re2import requests3# from SmartDjango import E4NC_HOST = 'https://nco.zjgsu.edu.cn'5LOGIN_URI = NC_HOST + '/login'6MOBILE_USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) ' \7 'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 ' \8 'Mobile/15E148 Safari/604.1'9HEADERS = {"User-Agent": MOBILE_USER_AGENT}10# @E.register()11# class NcovClockinServiceError:12# pass13class NcovClockinService:14 @staticmethod15 def login(student_id, password):16 session = requests.Session()17 with session.get(NC_HOST, headers=HEADERS) as r:18 html = r.content.decode()19 uuid = re.search(20 'var uuid = "(.*?)";', html, flags=re.S).group(1)21 session.cookies.set('_ncov_uuid', uuid)22 with session.post(LOGIN_URI, data={23 "name": student_id,24 "psswd": password,25 }, headers=HEADERS) as r:26 _ = r.content.decode()27 print(session.cookies)...
constants.py
Source:constants.py
1DEVICE_USERNAME = "vagrant"2DEVICE_PASSWORD = "vagrant"3NC_HOST = "127.0.0.1"4NC_PORT = "2223"5NC_SAVE_CONFIG_RPC = '<cisco-ia:save-config xmlns:cisco-ia="http://cisco.com/yang/cisco-ia"/>'6NC_CONN_PARAMS = {7 "host": NC_HOST,8 "port": NC_PORT,9 "username": DEVICE_USERNAME,10 "password": DEVICE_PASSWORD,11 "hostkey_verify": False12}13NETMIKO_CONN_PARAMS = {14 "ip": NC_HOST,15 "username": DEVICE_USERNAME,16 "password": DEVICE_PASSWORD,17 "device_type": "cisco_ios",18 "port": 2222,...
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!!