def scrape(url): r = utils.getUrl(url) bs = BeautifulSoup(r.content) if not bs: return recipe={} title_header = bs.find("h2", {'class': "recipe-title"}) name = title_header.find("span").get_text() recipe["name"]=name ingredients = [] names = bs.findAll("span", {'itemprop': "name"}) amounts = bs.findAll("span", {'itemprop': "amount"}) #skip recipe name names = names[1:] for idx, name in enumerate(names): ingredient = {} ingredient["amount"] = amounts[idx].get_text().strip() ingredient["name"] = name.get_text().strip() ingredients.append(ingredient) div = bs.find("div", {'itemprop':"instructions"}) instructions = div.get_text().strip() recipe["instructions"]=instructions recipe["ingredients"]=ingredients return json.dumps(recipe)
def scrape(url): r = utils.getUrl(url) bs = BeautifulSoup(r.content) if not bs: return recipe={} title_header = bs.find("h1", {'class': "entry-title"}) name = title_header.get_text() recipe["name"]=name ingredients = [] ingredient_list = bs.findAll("li", {'itemprop': "ingredients"}) for item in ingredient_list: ingredient = {} name = item.get_text().strip() dollar_pos = name.find("$") if dollar_pos != -1: name = name[:dollar_pos-1] ingredient["name"] = name ingredients.append(ingredient) instructions = [] instructions_list = bs.findAll("li", {'itemprop':"recipeInstructions"}) for item in instructions_list: instructions.append(item.get_text()) recipe["instructions"]="".join(instructions) recipe["ingredients"]=ingredients return json.dumps(recipe)
def youdaoTrans(text, langFrom, langTo, isSentence=True): if DEBUG_FLAG: print({ "doctype": "json", "type": YOUDAO_LANGUAGES[langFrom] + '2' + YOUDAO_LANGUAGES[langTo], 'i': text }) transType = 'AUTO2' + YOUDAO_LANGUAGES[langTo] if langFrom != 'Auto': transType = YOUDAO_LANGUAGES[langFrom] + '2' + YOUDAO_LANGUAGES[langTo] res = getUrl(url=YOUDAO_URL, params={ "doctype": "json", "type": transType, 'i': text }) if not res.ok: return None res = json.loads(res.text) if DEBUG_FLAG: print(res) errorCode = res["errorCode"] if errorCode != 0: return None translateResult = res["translateResult"] answer = "" for sen in translateResult: for s in sen: answer += s["tgt"] answer += "\n" answer = answer[:-1] return answer
def _get_hosts(self): """ get monitor hosts """ url = self.objects_api % {"tenant_id": self.tenant_id} header = {"X-Auth-Token": self.token} resp = utils.getUrl(url, header=header) return resp.get("hosts", [])
def search(query): results = [] mangas = utils.getUrlContent(utils.getUrl(SEARCH, query.replace(" ", "+"))) for manga in mangas.split('\n'): if manga: obj = manga.split('|') results.append(utils.Content(obj[0].strip(), MAIN+obj[4].strip())) return results
def test_status_api(self): """ Test voyage status api """ url = self.status_api % {"tenant_id": self.tenant_id} header = {"X-Auth-Token": self.token} resp = utils.getUrl(url, header=header) self.assertTrue(resp)
def _get_strategy(self): """ get monitor strategied """ url = self.strategies_api % {'tenant_id': self.tenant_id} header = {'X-Auth-Token': self.token} resp = utils.getUrl(url, header=header) return resp.get("strategies", [])
def addSongsFromLibrary(self, library, song_type): listItems = [] append = listItems.append createItem = self.createItem for song in library: append([utils.getUrl(song), createItem(song, song_type)]) return listItems
def test_strategies_api(self): """ Test voyage strategies api """ header = {"X-Auth-Token": self.token} url = self.strategies_api % {'tenant_id': self.tenant_id} resp = utils.getUrl(url, header=header) self.assertTrue(resp)
def addToQueue(self, params={}): songs = self._getSongs(params) playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC) for song in songs: playlist.add( utils.getUrl(song), utils.createItem(song['display_name'], song['albumart'], song['artistart']))
def test_objects_api(self): """ Test voyage objects api """ url = self.objects_api % {"tenant_id": self.tenant_id} header = {"X-Auth-Token": self.token} resp = utils.getUrl(url, header=header) self.assertTrue(resp) self.hosts=resp.get("hosts", [])
def test_strategy_api(self): """ Test voyage strategy api """ header = {'X-Auth-Token': self.token} for strategy in self.strategies: url = self.strategy_api % {'tenant_id': self.tenant_id, 'strategy_id': strategy['strategy_id']} resp = utils.getUrl(url, header=header) self.assertTrue(resp)
def test_statu_api(self): """ Test voyage statu api """ header = {"X-Auth-Token": self.token} for host in self.hosts: url = self.statu_api % {"tenant_id": self.tenant_id, "host_id": host["host"]["id"]} resp = utils.getUrl(url, header=header) self.assertTrue(resp)
def _get_tenant(self): """ get Tenant id """ url = "http://localhost:35357/v2.0/tenants" header = {"X-Auth-Token": self.token} resp = utils.getUrl(url, header=header) self.assertTrue(resp) for tenant in resp.get("tenants", []): if tenant["name"] == self.tenantname: return tenant["id"]
def getAZ(letter): if letter == '#': letter = '0-9' list = [] content = utils.getUrl(baseUrl + "/tv/sendungen-a-z?buchstabe=" + letter) spl = content.split('<div class="teaser" data-ctrl') for i in range(1, len(spl), 1): entry = spl[i] match = re.compile('href="(.+?)"', re.DOTALL).findall(entry) url = match[0].replace("&", "&") match = re.compile('class="headline">(.+?)<', re.DOTALL).findall(entry) title = match[0] match = re.compile('/image/(.+?)/16x9/', re.DOTALL).findall(entry) thumb = baseUrl + "/image/" + match[0] + "/16x9/0" list.append([title, url, thumb]) return list
def getAZ(letter): if letter == '#': letter = '0-9' list = [] content = utils.getUrl(baseUrl+"/tv/sendungen-a-z?buchstabe="+letter) spl = content.split('<div class="teaser" data-ctrl') for i in range(1, len(spl), 1): entry = spl[i] match = re.compile('href="(.+?)"', re.DOTALL).findall(entry) url = match[0].replace("&","&") match = re.compile('class="headline">(.+?)<', re.DOTALL).findall(entry) title = match[0] match = re.compile('/image/(.+?)/16x9/', re.DOTALL).findall(entry) thumb = baseUrl+"/image/"+match[0]+"/16x9/0" list.append([title, url, thumb]) return list
def getVideosXml(videoId): list = [] content = utils.getUrl(baseUrl+'/ard/servlet/export/collection/collectionId='+videoId+'/index.xml') match = re.compile('<content>(.+?)</content>', re.DOTALL).findall(content) for item in match: clip = re.compile('<clip(.+?)>', re.DOTALL).findall(item)[0] if 'isAudio="false"' in clip: name = re.compile('<name>(.+?)</name>', re.DOTALL).findall(item)[0] length = re.compile('<length>(.+?)</length>', re.DOTALL).findall(item)[0] if not '<mediadata:images/>' in item: thumb = re.compile('<image.+?url="(.+?)"', re.DOTALL).findall(item)[-1] else: thumb = '' id = re.compile(' id="(.+?)"', re.DOTALL).findall(clip)[0] list.append([name, id, thumb, length]) return list
def listAllCriteriaSongs(self, filter_type, filter_criteria): songs = self.api.getFilterSongs(filter_type, unquote_plus(filter_criteria), '') listItems = [] append = listItems.append createItem = self.createItem # add album name when showing all artist songs for song in songs: songItem = createItem(song, 'library') songItem.setLabel("".join( ['[', song['album'], '] ', song['title']])) songItem.setLabel2(song['album']) append([utils.getUrl(song), songItem]) return listItems
def test_update_strategy_api(self): """ Test voyage update strategy api """ header = {'X-Auth-Token': self.token} data = { "set_strategy":{ "newid":2 } } url = self.strategy_post_api % {'tenant_id': self.tenant_id, 'strategy_id': '1'} resp = utils.getUrl(url, method='POST', data=data) self.assertTrue(resp)
def exportLibrary(self, path): songs = self.api.getPlaylistSongs('all_songs') dp = xbmcgui.DialogProgress() dp.create(self.lang(30403), str(len(songs)) + ' ' + self.lang(30213).lower(), self.lang(30404)) count = 0 if not os.path.exists(path): os.mkdir(path) for song in songs: count = count + 1 artist = self._sanitizePath(song['artist']) album = self._sanitizePath(song['album']) if not os.path.exists(os.path.join(path, artist)): os.mkdir(os.path.join(path, artist)) if not os.path.exists(os.path.join(path, artist, album)): os.mkdir(os.path.join(path, artist, album)) if not os.path.isfile(os.path.join( path, artist, 'artist.nfo')) and song['artistart']: with open(os.path.join(path, artist, 'artist.nfo'), "w") as nfo: nfo.write( '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n' ) nfo.write( '<artist>\n\t<name>%s</name>\n\t<thumb>%s</thumb>\n</artist>' % (song['artist'], song['artistart'])) if not os.path.isfile( os.path.join(path, artist, album, 'album.nfo')) and song['albumart']: with open(os.path.join(path, artist, album, 'album.nfo'), "w") as nfo: nfo.write( '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>\n' ) nfo.write( '<album>\n\t<title>%s</title>\n\t<artist>%s</artist>\n\t<thumb>%s</thumb>\n</album>' % (song['album'], song['artist'], song['artistart'])) with open( os.path.join( path, artist, album, str(song['tracknumber']) + '-' + self._sanitizePath(song['title']) + '.strm'), "w") as strm: strm.write(utils.getUrl(song)) dp.update(int(count * 100 / len(songs)))
def scrape(url): r = utils.getUrl(url) bs = BeautifulSoup(r.content) if not bs: return recipe = {} j = bs.find('script', {'type': 'application/ld+json'}) data = json.loads(j.string) print data recipe["name"] = data['description'] recipe["instructions"] = data['recipeInstructions'] recipe["ingredients"] = utils.split_amounts_and_ingredients( data['recipeIngredient'] ) return json.dumps(recipe)
def rec(target): processed.add(target) url = getUrl(target, True) params = getParams(target, '', True) #得到参数 if '=' in target: # if there's a = in the url, there should be GET parameters inps = [] for name, value in params.items(): inps.append({'name': name, 'value': value}) forms.append({0: {'action': url, 'method': 'get', 'inputs': inps}}) response = requester(url, params, headers, True, delay, timeout).text #retireJs(url, response)##检测<script>中是否存在漏洞 # if not skipDOM: # highlighted = dom(response) # clean_highlighted = ''.join([re.sub(r'^\d+\s+', '', line) for line in highlighted]) # if highlighted and clean_highlighted not in checkedDOMs: # checkedDOMs.append(clean_highlighted) # logger.good('Potentially vulnerable objects found at %s' % url) # logger.red_line(level='good') # for line in highlighted: # logger.no_format(line, level='good') # logger.red_line(level='good') forms.append(get_form(response)) #取出response中的所有form表单 matches = re.findall(r'<[aA].*href=["\']{0,1}(.*?)["\']', response) for link in matches: # iterate over the matches # remove everything after a "#" to deal with in-page anchors link = link.split('#')[0] if link.endswith(('.pdf', '.png', '.jpg', '.jpeg', '.xls', '.xml', '.docx', '.doc')): pass else: if link[:4] == 'http': if link.startswith(main_url): storage.add(link) elif link[:2] == '//': if link.split('/')[2].startswith(host): storage.add(schema + link) elif link[:1] == '/': storage.add(main_url + link) else: storage.add(main_url + '/' + link)
def _get_token(self): """ get auth token """ data = { "auth": { "tenantName": self.tenantname, "passwordCredentials": { "username": self.username, "password": self.password } } } url = "http://localhost:35357/v2.0/tokens" resp = utils.getUrl(url, method='POST', data=data) self.assertTrue(resp) return resp["access"]["token"]["id"]
def getVideosXml(videoId): list = [] content = utils.getUrl(baseUrl + '/ard/servlet/export/collection/collectionId=' + videoId + '/index.xml') match = re.compile('<content>(.+?)</content>', re.DOTALL).findall(content) for item in match: clip = re.compile('<clip(.+?)>', re.DOTALL).findall(item)[0] if 'isAudio="false"' in clip: name = re.compile('<name>(.+?)</name>', re.DOTALL).findall(item)[0] length = re.compile('<length>(.+?)</length>', re.DOTALL).findall(item)[0] if not '<mediadata:images/>' in item: thumb = re.compile('<image.+?url="(.+?)"', re.DOTALL).findall(item)[-1] else: thumb = '' id = re.compile(' id="(.+?)"', re.DOTALL).findall(clip)[0] list.append([name, id, thumb, length]) return list
def scrape(url): r = utils.getUrl(url) bs = BeautifulSoup(r.content) if not bs: return recipe={} title_dev = bs.find("div", {'class': "title-wrapper"}) name = title_dev.find("span").get_text() recipe["name"]=name ingredients = [] table = bs.find("table", {'class': "list-ingredients"}) for row in table.findAll("tr"): ingredient = {} cell = row.find("td", {'class': "name"}) if cell is None: continue name = cell.find("span").renderContents().decode("utf8") cell = row.find("td", {'class':"amount-unit"}) if cell is not None: amount = cell.find("span", {'data-view-element': "amount"}).renderContents().decode("utf8") unit = cell.find("span", {'data-view-element': "unit"}).renderContents().decode("utf8") ingredient["name"]=name ingredient["amount"]=amount ingredient["unit"]=unit ingredients.append(ingredient) div = bs.find("div", {'class':"instructions"}) instructions = div.get_text().strip() recipe["instructions"]=instructions recipe["ingredients"]=ingredients return json.dumps(recipe)
def googleTrans(text, langFrom, langTo): if DEBUG_FLAG: print('Using Google Method') res = getUrl(url=GOOGLE_URL, params={ "client": "gtx", "dt": "t", "dj": "1", "ie": "UTF-8", "sl": GOOGLE_LANGUAGES[langFrom], "tl": GOOGLE_LANGUAGES[langTo], "q": text }) if not res.ok: return None sentences = json.loads(res.text)["sentences"] answer = '' for sen in sentences: answer += sen["trans"] answer += '\n' answer = answer[:-1] return answer
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Put Publicar items = [] items.append({'product_id': 162699, 'market_id': 1}) # Claro items.append({'product_id': 162699, 'market_id': 2}) # Linio items.append({'product_id': 162699, 'market_id': 4}) # MeLi items.append({'product_id': 162699, 'market_id': 5}) # Walmart items.append({'product_id': 162699, 'market_id': 6}) # Amazon utils.getAnswer(utils.getUrl('productos/agotar?'), requests.put, data=items)
# -*- coding: utf-8 -*- import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting Kits # utils.parameters['beforeid'] = # utils.parameters['afterid'] = utils.parameters['ids'] = "5999" utils.getAnswer(utils.getUrl('kits?'), requests.get) utils.init() p = [] componentes = [] componentes.append({"sku": '12345698', 'cantidad': 1}) p.append({ 'sku': '123456', 'comentario': 'Prueba de post', "componentes": componentes }) utils.getAnswer(utils.getUrl('kits?'), requests.post, p)
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. items = [] # Los markets pueden variar consulte la lista de markets disponibles en: # Markets may change see markets list at: # /api/markets items.append({'product_id': 162700, 'seller_sku': '7811X', 'stock': 1}) items.append({'product_id': 162700, 'seller_sku': '7911X', 'stock': 2}) items.append({'product_id': 162700, 'seller_sku': '8011X', 'stock': 4}) items.append({'product_id': 162700, 'seller_sku': '8111X', 'stock': 5}) items.append({'product_id': 162700, 'seller_sku': '1182X', 'stock': 6}) utils.getAnswer(utils.getUrl('stock?'), requests.put, items) # Verbo POST # Fecha a considerar el corte de inventario utils.init() data = {'update_stock': '2019-12-01T00:01:02'} utils.getAnswer(utils.getUrl('stock?'), requests.post, data)
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. import sys # Verbo GET utils.init() utils.getAnswer(utils.getUrl('ubicado?'), requests.get) # Verbo POST items = [] items.append({ 'ubicacion': 'INC-001', 'seller_sku': '0697-1000-0010', 'stock': 1 }) items.append({ 'ubicacion': 'INC-001', 'seller_sku': '0697-1000-0020', 'stock': 2 }) items.append({ 'ubicacion': 'INC-002', 'seller_sku': '0697-1000-0010', 'stock': 4 }) items.append({ 'ubicacion': 'INC-002', 'seller_sku': '0697-1000-0020', 'stock': 5 }) items.append({
# -*- coding: utf-8 -*- import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. ################# Recuperacion de productos utils.parameters['limit'] = 3 utils.getAnswer(utils.getUrl('fulfillment?'), requests.get)
def ADDONINSTALL(name, url, cmd, filetype, repourl, fav_path): try: confirm = xbmcgui.Dialog().yesno('Please Confirm', ' Do you wish to install the chosen add-on and', ' its respective repository if needed?', ' ', 'Cancel', 'Install') #On cancel if confirm == 0: url = utils.getUrl() tags = utils.getTag() type = utils.getType() if type == "Official": mode = "official" ADDONLIST(url, mode,tags) elif type == "UnOfficial": mode = "unofficial" ADDONLIST(url, mode,tags) #On install elif confirm == 1: dp = xbmcgui.DialogProgress() dp.create('Download Progress:', 'Downloading repo...', '', 'Please Wait') if url != 'XBMC': checkRepo(url,dp) #Addon installation xml_url = utils.getUrl() link = OPEN_URL(xml_url) match = re.compile(XML_EXPRESSION_ITEM).findall(link) for id, title, icon, repolink, pluginlink, cmd, thumbnail, rating, type, description in match: if title == name: addon_url = pluginlink newfile = addon_url.rsplit('/',1)[1] newfile = newfile.rsplit('?',1)[0] try: version = newfile.rsplit('-',1)[1].rsplit('.',1)[0] except: #version is not available pass addonname = newfile.rsplit('-', 1)[0] addonname = str(addonname) addonname = addonname.replace('[', '') addonname = addonname.replace(']', '') addonname = addonname.replace('"', '') addonname = addonname.replace('[', '') addonname = addonname.replace("'", '') path = xbmc.translatePath(os.path.join('special://home/addons', 'packages')) current, dirs, files = os.walk(xbmc.translatePath('special://home/addons')).next() for dir in dirs: #zipfile already exist if dir == addonname: addon_path = os.path.join(xbmc.translatePath('special://home/addons'),addonname) addon_xml = os.path.join(addon_path,'addon.xml') tree = ET.parse(addon_xml) root = tree.getroot() existingVersion = root.attrib.get('version') if existingVersion == version: addon_cmd = '' xml_url = utils.getUrl() link = OPEN_URL(xml_url) match = re.compile(XML_EXPRESSION_ITEM).findall(link) for id, title, icon, repolink, pluginlink, cmd, thumbnail, rating, type, description in match: if title == name: addon_cmd = cmd icon_path = os.path.join(xbmc.translatePath('special://home/addons'),os.path.join(addonname,'icon.png')) fanart_path = os.path.join(xbmc.translatePath('special://home/addons'),os.path.join(addonname,'fanart.jpg')) if not os.path.exists(fanart_path): fanart_path = FANART copy = [] copy.append(name) copy.append(icon_path) copy.append(fanart_path) copy.append(addon_cmd) fav_file = os.path.join(fav_path, FILENAME) favourite.copyFave(fav_file, copy) #xbmcgui.Dialog().ok('Installed','Now you can use it directly from current folder') return 1 #zipfile not found lib = os.path.join(path, newfile) dp.update(0, 'Downloading plugin...') download(addon_url, lib, dp) if filetype == 'addon': addonfolder = xbmc.translatePath(os.path.join('special://', 'home/addons')) elif filetype == 'media': addonfolder = xbmc.translatePath(os.path.join('special://', 'home')) elif filetype == 'main': addonfolder = xbmc.translatePath(os.path.join('special://', 'home')) time.sleep(2) addonname = extract.all(lib, addonfolder, dp) addon_cmd = '' xml_url = utils.getUrl() link = OPEN_URL(xml_url) match = re.compile(XML_EXPRESSION_ITEM).findall(link) for id, title, icon, repolink, pluginlink, cmd, thumbnail, rating, type, description in match: if title == name: addon_cmd = cmd icon_path = os.path.join(addonfolder, os.path.join(addonname, 'icon.png')) fanart_path = os.path.join(xbmc.translatePath('special://home/addons'), os.path.join(addonname, 'fanart.jpg')) if not os.path.exists(fanart_path): fanart_path = FANART copy = [] copy.append(name) copy.append(icon_path) copy.append(fanart_path) copy.append(addon_cmd) fav_file = os.path.join(fav_path, FILENAME) favourite.copyFave(fav_file, copy) #Updated plugin addon_path = os.path.join(xbmc.translatePath('special://home/addons'),addonname) addon_xml = os.path.join(addon_path,'addon.xml') tree = ET.parse(addon_xml) root = tree.getroot() exVersion = root.attrib.get('version') digits = exVersion.rsplit('.') newVersion = '' #if int(digits[2]) != 0: # newVersion = exVersion.rsplit('.',1)[0] + '.0' #elif int(digits[1]) != 0: # newVersion = exVersion.split('.',1)[0] + '.0.0' #else: # newVersion = '0.0.0' newVersion = '0.0.0' root.set('version', newVersion) tree.write(addon_xml) #xbmc.executebuiltin( 'UpdateLocalAddons' ) #xbmc.executebuiltin( 'UpdateAddonRepos' ) #xbmcgui.Dialog().ok('Installed','Now you can use it directly from current folder') #updatePath = xbmc.translatePath('special://home/addons/plugin.program.tlbb.content/addonUpdate.py') #xbmc.executebuiltin( "RunScript(" + updatePath + ")") return 1 except Exception as e: xbmcgui.Dialog().ok('Error','Installation failed') path = utils.getCurrentPath() thepath = xbmc.translatePath(path) label = os.path.basename(thepath) link = "ReplaceWindow(10001,%s?label=%s&mode=%d&path=%s)" % (sys.argv[0] , label, 400, urllib.quote_plus(thepath)) xbmc.executebuiltin(link)
# -*- coding: utf-8 -*- import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting Kits # utils.parameters['beforeid'] = # utils.parameters['afterid'] = utils.parameters['orders'] = "1052" utils.getAnswer(utils.getUrl('cobros?'), requests.get) # utils.init() # utils.parameters['orders'] = "1052" # p={ # 'caja':'5', # 'monto':'659', # 'sucursal':'La Fe', # 'ticket':'123456' # } # utils.getAnswer(utils.getUrl('cobros?'), requests.post, [p]) # utils.init() # utils.parameters['ids'] = "4" # p={ # 'motivo':'Cliente se arrepintio', # } # utils.getAnswer(utils.getUrl('cobros?'), requests.put, [p])
# -*- coding: utf-8 -*- import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting Tracking Numbers utils.parameters['orders'] = '131303' # utils.parameters['beforeid'] = # utils.parameters['afterid'] = # Genera la guia y la descarga, solamente una guia a la vez utils.getAnswer(utils.getUrl('guias?'), requests.post) # El get funciona para multiples guias pero solamente las descarga ya deben de existir #utils.getAnswer(utils.getUrl('guias?'), requests.get)
v['bullet1'] = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' v['bullet2'] = 'Lorem Ipsum has been the industry s standard dummy text ever since the 1500s' v['bullet3'] = '' v['bullet4'] = '' v['bullet5'] = '' v['atributos'] = [{ 'atributo': 'EAN', 'valor': '9856472536978' }, { 'atributo': 'SELLER_SKU', 'valor': '9815-1' }] items = [v] utils.getAnswer(utils.getUrl('variacion?'), requests.post, items) # PUT Variacion utils.init() v = {} v['product_id'] = 163766 v['sku'] = '9815-1' v['color'] = "Negro Noche" v['base'] = "Negro".upper() # ;ist be upper case v['stock'] = 0 v['imagen1'] = 'https://www.w3schools.com/w3css/img_lights.jpg' v['imagen2'] = 'https://www.w3schools.com/w3css/img_snowtops2.jpg' v['imagen3'] = 'https://www.w3schools.com/w3css/img_snowtops3.jpg' v['imagen4'] = 'https://www.w3schools.com/w3css/img_snowtops4.jpg' v['imagen5'] = ''
def getNewestVersion(): s = session() s.keep_alive = False info = getUrl(VERSION_URL) info = loads(info.text) return info
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting stand alone category utils.parameters['ids'] = 7209 # remover this parameter to get all categories utils.getAnswer(utils.getUrl('categorias?'), requests.get) # Getting attributes from a category utils.getAnswer(utils.getUrl('categorias/atributos/7416?'), requests.get)
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting markets utils.getAnswer(utils.getUrl('markets?'), requests.get) # Posting market utils.init() # One market at a time market = {'market_id': 1, 'activo': 1, 'proteccion': 1} utils.getAnswer(utils.getUrl('markets?'), requests.post, market)
p = {} p['product_id'] = 163766 # Yous ID code p['nombre'] = "Test product for API Guide" p['descripcion'] = "This is a test for add items from API to Marketsync products" p['ficha'] = """ Alta de la ficha técnica ----------------------------------------- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""" p['palto'] = 11 # Centimeters height p['pancho'] = 11 # Centimeters width p['plargo'] = 22 # Centimeters deep p['ppeso'] = 1.2 # Kilograms weight p['etiquetas_web'] = "Test1_Value,Test2_Value" atributos = [] atributos.append({'atributo': 'BRAND', 'valor': 'New Waves'}) p['atributos'] = atributos items = [p] utils.getAnswer(utils.getUrl('productos?'), requests.put, items) ############### Eliminación de Productos DELETE # utils.init() # items = [] # items.append({'product_id':0}) # your id here # utils.getAnswer(utils.getUrl('productos?'), requests.delete, items)
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting countries utils.getAnswer(utils.getUrl('paises?'), requests.get)
# -*- coding: utf-8 -*- import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting Orders utils.parameters['limit'] = 2 utils.getAnswer(utils.getUrl('pedidos?'), requests.get) # Posting new SalesOrders utils.init() p = {} p['referencia'] = '123456' p['fecha_pedido'] = '2019-12-01T10:00:00' p['fecha_autoriza'] = '2019-12-01T10:35:10' p['subtotal'] = '1000' p['total'] = '1160' p['email'] = '*****@*****.**' p['entregara'] = 'MySelf' p['telefono'] = '' p['direccion'] = 'Priv Reforma # 108' p['entrecalles'] = 'Abasolo y Montero' p['colonia'] = 'Los Treviño' p['ciudad'] = 'Santa Catarina' p['estado'] = 'Nuevo León' p['observaciones'] = 'Bodega Blanca' p['cp'] = '61588' p['estatus'] = 'pendiente' p['mensajeria'] = '' p['guias'] = ''
'market_id': 1, 'oferta': 101, 'precio': 201 }) # Claro items.append({ 'product_id': 163766, 'market_id': 2, 'oferta': 102, 'precio': 202 }) # Linio items.append({ 'product_id': 163766, 'market_id': 4, 'oferta': 104, 'precio': 204 }) # MeLi items.append({ 'product_id': 163766, 'market_id': 5, 'oferta': 105, 'precio': 205 }) # Walmart items.append({ 'product_id': 163766, 'market_id': 6, 'oferta': 106, 'precio': 206 }) # Amazon utils.getAnswer(utils.getUrl('precios?'), requests.put, items)
import requests import utils # Review config.example file and rename it to config.py, do not forget to erase your keys. # Getting colors utils.getAnswer(utils.getUrl('colores?'), requests.get)