Best Python code snippet using pytest-benchmark
4_json_file_opt.py
Source:4_json_file_opt.py
1# coding = utf-82import json3"""4author:xuwenyuan5date: 2019-04-306describeï¼å¯¹jsonæ件æä½ï¼7 1.æå符串ä¿åæjsonæ件8 2.读åjsonæ件9 3.Json模ådumpsãloadsãdumpãloadå½æ°ä»ç»[åé¢å¸¦sçï¼ä¸æ件æå
³]10"""11class SaveASJson(object):12 def __init__(self):13 self.persons = [14 {15 'username': "å¼ ä¸",16 'age': 18,17 'country': 'china'18 },19 {20 'username': 'æå',21 'age': 20,22 'country': 'china'23 },24 {25 'username': 'çäº',26 'age': 32,27 'country': 'china'28 }29 ]30 self.persons_dic = {'username': "zhangsan", 'age': 18, 'country': 'china'}31 self.persons_str = 'zhangsanå¼ ä¸'32 @staticmethod33 def save_file(json_string, file_name, coding):34 """35 ä¿åæ件å½æ°ï¼æå符串ä¿åææ件36 :param json_string:37 :param file_name:38 :param coding:39 :return:40 """41 with open(file_name, 'w', encoding=coding) as fp:42 fp.write(json_string)43 @staticmethod44 def dump_save_file(json_string, file_name, coding):45 """46 使ç¨dumpå½æ°ï¼ä¿åæ件47 # json.dump(json_string, fp) è¿æ ·åä¼ä¸æä¹±ç ï¼48 # å¦æè¦ä¿åå«æä¸æçå符串ï¼å»ºè®®å ä¸ensure_ascii=False,json.dumpé»è®¤ä½¿ç¨asciiå符ç 49 :param json_string: è¦ä¿åçjsonå符串50 :param file_name: è¦ä¿åçæ件å称51 :param coding: å符ç¼ç (å¦utf-8)52 :return: 没æè¿åå¼53 """54 with open(file_name, 'w', encoding=coding) as fp:55 json.dump(json_string, fp, ensure_ascii=False)56 @staticmethod57 def read_json_file(file_name, coding):58 """59 使ç¨json.load读åjsonæ件60 :param file_name: æ件å61 :param coding: ç¼ç ï¼å¦utf-8ï¼62 :return: <class 'list'>63 """64 with open(file_name, 'r', encoding=coding) as fp:65 persons = json.load(fp)66 return persons67 @staticmethod68 def read_file(file_name, coding):69 """70 ä¼ ç»ç读åæ件æ¹æ³ï¼è¯¦è§ï¼https://www.cnblogs.com/zywscq/p/5441145.html71 :param file_name: æ件å称72 :param coding: ç¼ç 73 :return: è¿åæ件å
容74 """75 with open(file_name, 'r', encoding=coding) as f:76 content = f.read()77 return content78if __name__ == '__main__':79 save_json = SaveASJson()80 # è¿æ ·ä¼ä¸æä¹±ç 81 # json_str = json.dumps(save_json.persons_dic)82 # print(type(save_json.persons_dic))83 # print(type(json_str))84 # print(json_str)85 # è¿æ ·ä¸ä¼ä¸æä¹±ç 86 # json_str = json.dumps(save_json.persons).encode('utf-8').decode('unicode_escape')87 # è°ç¨ä¿åå½æ°88 # SaveASJson.save_file(json_str, 'person.json', 'utf-8')89 # SaveASJson.dump_save_file(save_json.persons, 'person2.json', 'utf-8')90 # 读åjsonæ件91 # person_list = SaveASJson.read_json_file('person2.json', 'utf-8')92 # print(type(person_list))93 # print(person_list)94 # 1.json.dumps()95 # ## ç¨äºå°æpython对象(dictç±»å/listç±»å)çæ°æ®è½¬æstr(jsonæ ¼å¼çstr)ï¼96 # ## (1).å 为å¦æç´æ¥å°dictç±»å/listç±»åçæ°æ®åå
¥jsonæ件ä¸ä¼åçæ¥éï¼å æ¤å¨å°æ°æ®åå
¥æ¶éè¦ç¨å°è¯¥å½æ°;97 # ## (2).json.dumpsä¼æ ¼å¼åpython对象ç代ç ï¼è½¬æ¢æjsonsæ åæ ¼å¼ã98 # 1.1 è¿æ ·ä¼æ¥é99 # SaveASJson.save_file(save_json.persons, 'person.json', 'utf-8')100 # 1.2 å
转æ¢ï¼ååå
¥ï¼ä¸ä¼æ¥é101 # persons = json.dumps(save_json.persons, ensure_ascii=False)102 # SaveASJson.save_file(persons, 'person.json', 'utf-8')103 # 2.json.dump()104 # ## json.dump() (1) ç¨äºå°dict/listç±»åçæ°æ®è½¬æstrï¼(2) 并åå
¥å°jsonæ件ä¸ã105 # SaveASJson.dump_save_file(save_json.persons, 'person.json', 'utf-8')106 # 3.json.loads()107 # ## json.loads() ç¨äºå°strç±»åçæ°æ®è½¬ædict/list108 tt = SaveASJson.read_file('person.json', 'utf-8')109 print(tt)110 '''111 #112 print(type(save_json.persons))113 # æpython对象ï¼list/dictï¼è½¬æstr (jsonå符串) 114 persons = json.dumps(save_json.persons)115 print(type(persons))116 persons_list = json.loads(persons)117 print(type(persons_list))118 print(persons_list[0]["username"])119 120 print(type(save_json.persons_str))121 print(save_json.persons_str)122 person_str1 = json.dumps(save_json.persons_str, ensure_ascii=False)123 print(type(person_str1))124 print(person_str1)125 if person_str1 == save_json.persons_str:126 print('true')127 else:128 print('false')129 print(save_json.persons_str[0:5])130 print(person_str1[0:5])131 132 ...
request_examples.py
Source:request_examples.py
1'''2How to import:3'''4from __init__ import APIREST5'''6Example get product by sku and print results and status code:7'''8fetch = APIREST(query_to = 'products', filter= 'prod_by_sku',filter_field = 'prod_sku', save_json= True).get()9fetch_status = fetch.get('response').get('status')10fetch_result = fetch.get('results')11print(fetch_status)12print(fetch_result)13'''14Products queries examples:15'''16# Get All products:17APIREST(query_to = 'products', filter= 'all_products', save_json= True, pagesize = 500).get()18# Get Product by Id:19APIREST(query_to = 'products', filter= 'by_id',filter_field = 'prod_id', save_json= True).get()20# Get Product by sku:21APIREST(query_to = 'products', filter= 'prod_by_sku',filter_field = 'prod_sku', save_json= True).get()22# Get Product Stock Quantity:23APIREST(query_to = 'stockItems', filter= 'prod_stock',filter_field = 'prod_sku', save_json= True).get()24# Get all categories25APIREST(query_to = 'categories', save_json= True).get()26# Get Prodcut Stock Quantity:27APIREST(query_to = 'stockItems', filter= 'prod_stock',filter_field = 'prod_sku', save_json= True).get()28# Post special price:29data ={ "prices": [30 {31 "price": price,32 "store_id": 1,33 "sku": product_sku,34 "price_from": "2021-01-01 00:00:00",35 "price_to": "2021-06-01 00:00:00",36 }37 ]38 }39APIREST(query_to = 'products/special-price', data = data).post()40# Update product Quantity and price:41data = {"product":42 {"sku" : product_sku,43 "price": price,44 "extension_attributes":{45 "stock_item": {46 "qty": quantity,47 "min_qty": 0,48 "is_in_stock": 'true',49 "manage_stock": 'true'50 }51 }52 }53 }54APIREST(ksc = self.ksc_out, query_to = 'products/'+ 'product_sku', data = data, service = self.service).put()55# Update product images:56data = {"product": {"sku" : 'product_sku', "media_gallery_entries": images}}57APIREST( query_to = 'products/'+ 'product_sku', data = data).put()58# Delete product:59APIREST(query_to = 'products/'+ 'product_sku').delete()60'''61Customer queries examples:62'''63# By customer Id:64APIREST(query_to = 'customers', filter= 'by_customer_id',filter_field = '18', save_json= True).get()65#By customer address Id:66APIREST(query_to = 'customers', filter= 'by_address_id',filter_field = '10', save_json= True).get()67# By customer shipping address Id:68APIREST(query_to = 'customers', filter= 'by_shipping_id', filter_field = '16', save_json= True).get()69# By customer billing address Id:70APIREST(query_to = 'customers', filter= 'by_billing_id', filter_field = '6', save_json= True).get()71'''72Orders queries examples:73'''74# Get orders since created date:75APIREST(query_to = 'orders', filter= 'by_create_date', filter_field = '2021-03-08 00:00:00', save_json= True).get()76# Get orders since updated date and created 14 days before:77APIREST(query_to = 'orders', filter= 'by_create_and_update_date', filter_field = '2021-03-08 00:00:00', save_json= True).get()78# Post order:79data = {"entity": {}80 }...
SavedInfo.py
Source:SavedInfo.py
1from flask import Flask, request2from flask_restful import Api, Resource3from flask_restful import reqparse, abort4from mark_parser import mark_parser5from flask_cors import CORS6import uuid7import json8import os9env_dist = os.environ 10import sys11sys.path.append("..")12from web_backend.common.util import *13class SavedInfo(Resource):14 @middleware_test15 @current_window_required16 def get(self, mpproject_id):17 print("fix for test:", mpproject_id)18 print("get save:", mpproject_id)19 save_json = mark_parser.MPProject(mpproject_id).save_json20 if not os.path.exists(save_json):21 f = open(save_json, 'w')22 f.write("{}")23 f.close()24 with open(save_json, 'r') as loadfile:25 return json.load(loadfile)26 @current_window_required27 def post(self, mpproject_id):28 print("save:", mpproject_id)29 save_json = mark_parser.MPProject(mpproject_id).save_json30 data = request.get_data()31 print(data)32 js_data = json.loads(data.decode("utf-8"))33 print("js_data:")34 print(js_data)35 if not os.path.exists(save_json):36 f = open(save_json, 'w')37 f.write("{}")38 f.close()39 with open(save_json, 'w+') as outfile:40 json.dump(js_data, outfile) ...
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!!