Best Python code snippet using lisa_python
citrix_sharefile_adapter.py
Source:citrix_sharefile_adapter.py
...28 return token29 def get_authorization_header(self):30 token = self.authenticate()31 return {'Authorization': 'Bearer {}'.format(token['access_token'])}32 def get_hostname(self):33 token = self.authenticate()34 print(token)35 return '{}.sf-api.com'.format(token['subdomain'])36 def get_root(self, get_children=False):37 uri_path = '/sf/v3/Items(allshared)'38 if get_children:39 uri_path = '{}?$expand=Children'.format(uri_path)40 print('GET {}{}'.format(self.get_hostname(), uri_path))41 http = httplib.HTTPSConnection(self.get_hostname())42 http.request('GET', uri_path, headers=self.get_authorization_header())43 response = http.getresponse()44 print(response.status, response.reason)45 items = json.loads(response.read())46 print(items['Id'], items['CreationDate'], items['Name'])47 if 'Children' in items:48 children = items['Children']49 for child in children:50 print(child['Id'], items['CreationDate'], child['Name'])51 def get_item_by_id(self, item_id):52 uri_path = '/sf/v3/Items({})'.format(item_id)53 print('GET {}{}'.format(self.get_hostname(), uri_path))54 http = httplib.HTTPSConnection(self.get_hostname())55 http.request('GET', uri_path, headers=self.get_authorization_header())56 response = http.getresponse()57 print(response.status, response.reason)58 items = json.loads(response.read())59 print(items['Id'], items['CreationDate'], items['Name'])60 def get_folder_with_query_parameters(self, item_id):61 uri_path = '/sf/v3/Items({})?$expand=Children&$select=Id,Name,Children/Id,Children/Name,Children/CreationDate'.format(item_id)62 print('GET {}{}'.format(self.get_hostname(), uri_path))63 http = httplib.HTTPSConnection(self.get_hostname())64 http.request('GET', uri_path, headers=self.get_authorization_header())65 response = http.getresponse()66 print(response.status, response.reason)67 items = json.loads(response.read())68 print(items['Id'], items['Name'])69 if 'Children' in items:70 children = items['Children']71 for child in children:72 print(child['Id'], child['CreationDate'], child['Name'])73 http.close()74 def create_folder(self, parent_id, name, description):75 uri_path = '/sf/v3/Items({})/Folder'.format(parent_id)76 print('POST {}{}'.format(self.get_hostname(), uri_path))77 folder = {'Name': name, 'Description': description}78 headers = self.get_authorization_header()79 headers['Content-Type'] = 'application/json'80 http = httplib.HTTPSConnection(self.get_hostname())81 http.request('POST', uri_path, json.dumps(folder), headers=headers)82 response = http.getresponse()83 print(response.status, response.reason)84 new_folder = json.loads(response.read())85 print('Created Folder {}'.format(new_folder['Id']))86 http.close()87 def update_item(self, item_id, name, description):88 uri_path = '/sf/v3/Items({})'.format(item_id)89 print('PATCH {}{}'.format(self.get_hostname(), uri_path))90 folder = {'Name': name, 'Description': description}91 headers = self.get_authorization_header()92 headers['Content-type'] = 'application/json'93 http = httplib.HTTPSConnection(self.get_hostname())94 http.request('PATCH', uri_path, json.dumps(folder), headers=headers)95 response = http.getresponse()96 print(response.status, response.reason)97 http.close()98 def delete_item(self, item_id):99 uri_path = '/sf/v3/Items({})'.format(item_id)100 print('DELETE {}{}'.format(self.get_hostname(), uri_path))101 http = httplib.HTTPSConnection(self.get_hostname())102 http.request('DELETE', uri_path, headers=self.get_authorization_header())103 response = http.getresponse()104 print(response.status, response.reason)105 http.close()106 def download_item(self, item_id, local_path):107 uri_path = '/sf/v3/Items({})/Download'.format(item_id)108 print('GET {}{}'.format(self.get_hostname(), uri_path))109 http = httplib.HTTPSConnection(self.get_hostname())110 http.request('GET', uri_path, headers=self.get_authorization_header())111 response = http.getresponse()112 location = response.getheader('location')113 redirect = None114 if location:115 redirect_uri = urlparse.urlparse(location)116 redirect = httplib.HTTPSConnection(redirect_uri.netloc)117 redirect.request('GET', '{}?{}'.format(redirect_uri.path, redirect_uri.query))118 response = redirect.getresponse()119 with open(local_path, 'wb') as target:120 b = response.read(1024 * 8)121 while b:122 target.write(b)123 b = response.read(1024 * 8)124 print(response.status, response.reason)125 http.close()126 if redirect:127 redirect.close()128 def upload_file(self, folder_id, local_path):129 uri_path = '/sf/v3/Items({})/Upload'.format(folder_id)130 print('GET {}{}'.format(self.get_hostname(), uri_path))131 http = httplib.HTTPSConnection(self.get_hostname())132 http.request('GET', uri_path, headers=self.get_authorization_header())133 response = http.getresponse()134 upload_config = json.loads(response.read())135 if 'ChunkUri' in upload_config:136 upload_response = self.multipart_form_post_upload(upload_config['ChunkUri'], local_path)137 print(upload_response.status, upload_response.reason)138 else:139 print('No Upload URL received')140 def multipart_form_post_upload(self, url, filepath):141 newline = b'\r\n'142 filename = os.path.basename(filepath)143 data = []144 headers = {}145 boundary = '----------{}'.format(int(time.time()))146 headers['content-type'] = 'multipart/form-data; boundary={}'.format(boundary)147 data.append('--{}'.format(boundary))148 data.append('Content-Disposition: form-data; name="{}"; filename="{}"'.format('File1', filename))149 data.append('Content-Type: {}'.format(self.get_content_type(filename)))150 data.append('')151 data.append(open(filepath, 'rb').read())152 data.append('--{}--'.format(boundary))153 data.append('')154 data_str = newline.join([item if isinstance(item, bytes) else bytes(item, 'utf-8') for item in data])155 headers['content-length'] = len(data_str)156 uri = urlparse.urlparse(url)157 http = httplib.HTTPSConnection(uri.netloc)158 http.putrequest('POST', '{}?{}'.format(uri.path, uri.query))159 for hdr_name, hdr_value in headers.items():160 http.putheader(hdr_name, hdr_value)161 http.endheaders()162 http.send(data_str)163 return http.getresponse()164 @staticmethod165 def get_content_type(filename):166 return mimetypes.guess_type(filename)[0] or 'application/octet-stream'167 def get_clients(self):168 uri_path = '/sf/v3/Accounts/GetClients'169 print('GET {}{}'.format(self.get_hostname(), uri_path))170 http = httplib.HTTPSConnection(self.get_hostname())171 http.request('GET', uri_path, headers=self.get_authorization_header())172 response = http.getresponse()173 print(response.status, response.reason)174 feed = json.loads(response.read())175 if 'value' in feed:176 for client in feed['value']:177 print(client['Id'], client['Email'])178 def create_client(self, email, firstname, lastname, company, clientpassword, canresetpassword, canviewmysettings):179 uri_path = '/sf/v3/Users'180 print('POST {}{}'.format(self.get_hostname(), uri_path))181 client = {'Email': email, 'FirstName': firstname, 'LastName': lastname, 'Company': company,182 'Password': clientpassword,183 'Preferences': {'CanResetPassword': canresetpassword, 'CanViewMySettings': canviewmysettings}}184 headers = self.get_authorization_header()185 headers['Content-type'] = 'application/json'186 http = httplib.HTTPSConnection(self.get_hostname())187 http.request('POST', uri_path, json.dumps(client), headers=headers)188 response = http.getresponse()189 print(response.status, response.reason)190 new_client = json.loads(response.read())191 print('Created Client {}'.format(new_client['Id']))...
utils.py
Source:utils.py
...16 host = urlparse.urlparse(url).netloc17 if ":" in host:18 host.split(":", 1)[0]19 return host20def get_hostname(url):21 """22 Return the hostname ``url`` belongs to; 'www' is stripped.23 >>> get_hostname("http://example.com/sdf")24 'example.com'25 >>> get_hostname("http://www.example.com/")26 'example.com'27 >>> get_hostname("http://www2.example.com/")28 'example.com'29 >>> get_hostname("http://www.static.example.com/")30 'static.example.com'31 >>> get_hostname("http://awww.static.example.com/")32 'awww.static.example.com'33 >>> get_hostname("http://static.example.com/")34 'static.example.com'35 >>> get_hostname("fsdf")36 'fsdf'37 >>> get_hostname("127.0.0.1")38 '127.0.0.1'39 """40 url = add_scheme_if_missing(url)41 try:42 domain = urlparse.urlparse(url).hostname or ''43 except Exception:44 domain = ''45 else:46 domain = re.sub(r'^www\d*\.', '', domain)47 return domain48def add_scheme_if_missing(url):49 """50 Add scheme to an url if it is missing.51 >>> add_scheme_if_missing("example.com")52 'http://example.com'53 >>> add_scheme_if_missing("https://example.com")54 'https://example.com'55 >>> add_scheme_if_missing("ftp://example.com")56 'ftp://example.com'57 """58 url = url.strip()59 return url if has_scheme(url) else "http://" + url60def get_robotstxt_url(url):61 """62 >>> get_robotstxt_url("https://example.com/foo/bar?baz=1")63 'https://example.com/robots.txt'64 """65 if not isinstance(url, urlparse.ParseResult):66 url = urlparse.urlparse(url)67 return "%s://%s/robots.txt" % (url.scheme, url.netloc)68def is_external_url(source_url, target_url):69 """70 Return True if URLs are external to each other.71 >>> is_external_url("http://example.com/foo", "http://example.com/bar")72 False73 >>> is_external_url("http://example.com/foo", "http://example2.com/bar")74 True75 Subdomains are not considered external:76 >>> is_external_url("http://example.com", "http://static.example.com")77 False78 If the domain is the same but TLDs differ links are also *not* considered79 external:80 >>> is_external_url("http://example.com", "http://static.example.co.uk")81 False82 """83 p1 = get_hostname(source_url)84 p2 = get_hostname(target_url)85 return p1 != p286if __name__ == "__main__":...
Connections.py
Source:Connections.py
1hostname = "http://159.69.87.82:8181/"2def get_hostname():3 return hostname4def authenticate() -> str:5 return get_hostname() + "authenticate"6def get_categories() -> str:7 return get_hostname() + "categories"8def get_products() -> str:9 return get_hostname() + "products/"10def create_transaction() -> str:11 return get_hostname() + "transactions/create"12def get_all_transactions() -> str:13 return get_hostname() + "transactions/all"14def request_user_info() -> str:15 return get_hostname() + "identification/request-user/"16def get_users() -> str:17 return get_hostname() + "users"18def add_user_mapping() -> str:19 return get_hostname() + "identification/add-card-mapping"20def connection_status() -> str:21 return get_hostname() + "admin"22def get_all_cards() -> str:23 return get_hostname() + "identification/cards"24# class BackendURLs:25# AUTHENTICATE = hostname + "authenticate"26# GET_CATEGORIES = hostname + "categories"27# GET_PRODUCTS = hostname + "products/"28# CREATE_TRANSACTION = hostname + "transactions/create"29# REQUEST_USER_INFO = hostname + "identification/request-user/"30# GET_USERS = hostname + "users"...
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!!