Esempio n. 1
0
def login():
    print session.ACCESS_TOKEN
    from meli import Meli
    meli = Meli(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    return "<a href='" + meli.auth_url(
        redirect_URI=REDIRECT_URI
    ) + "'> Click para Fazer Login na conta do Mercado Livre </a>"
Esempio n. 2
0
def imagem_upload(idAnuncio):
    #### Buscando as Imagens do Anuncio ####
    import os
    imagensIds = db(Anuncios_Imagens.anuncio == idAnuncio).select()
    imagens = []
    for anuncioImagem in imagensIds:
        if not anuncioImagem.imagem_id:
            imagem = Imagens[anuncioImagem.imagem]
            img = str(imagem.imagem)
            image = os.path.join(request.folder,'uploads', img)
            imagens.append(dict(file=image, id = anuncioImagem['id']))
      
    if session.ACCESS_TOKEN:
        from meli import Meli 
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=session.ACCESS_TOKEN, refresh_token=session.REFRESH_TOKEN)
        for file in imagens:
            imag = meli.imagem("/pictures", file['file'], {'access_token':session.ACCESS_TOKEN})
            status = 'Anunciado com Sucesso....'         
            import json
            ximg = json.loads(imag.content)    
            Anuncios_Imagens[file['id']] = dict(imagem_id=ximg['id'])
            
    else:
        status = 'Antes Faça o Login....'
        item = ''    
    
    #### Buscando Ids das Imagens do Anuncio ####
    anuncioImagens = db(Anuncios_Imagens.anuncio == idAnuncio).select()
    imagens = []
    for imagem in anuncioImagens:
        if imagem.imagem_id:
            img = imagem.imagem_id
            imagens.append(dict(id=img))

    return imagens
Esempio n. 3
0
    def form_valid(self, form):
        try:
            meli = Meli(client_id=self.request.session['CLIENT_ID'],
                        client_secret=self.request.session['CLIENT_SECRET'],
                        access_token=self.request.session['ACCESS_TOKEN'],
                        refresh_token=self.request.session['REFRESH_TOKEN'])
        except KeyError:
            return redirect('login')

        body = {
            "condition": form.cleaned_data['condition'],
            "warranty": form.cleaned_data['warranty'],
            "currency_id": form.cleaned_data['currency_id'],
            "accepts_mercadopago": form.cleaned_data['accepts_mercadopago'],
            "description": form.cleaned_data['description'],
            "listing_type_id": form.cleaned_data['listing_type_id'],
            "title": form.cleaned_data['title'],
            "available_quantity": form.cleaned_data['available_quantity'],
            "price": str(form.cleaned_data['price']),
            "buying_mode": form.cleaned_data['buying_mode'],
            "category_id": form.cleaned_data['category_id']
        }

        response = meli.post("/items", body,
                             {'access_token': meli.access_token})
        if response.status_code != 201:
            form.add_error(field=None, error=response.content)
            return super().form_invalid(form)
        return super().form_valid(form)
Esempio n. 4
0
    def get_publicaciones(self):
        try:
            meli = Meli(client_id=self.request.session['CLIENT_ID'],
                        client_secret=self.request.session['CLIENT_SECRET'],
                        access_token=self.request.session['ACCESS_TOKEN'],
                        refresh_token=self.request.session['REFRESH_TOKEN'])
            ml_user_id = self.request.session['ML_USER_ID']
        except KeyError:
            return redirect('login')
        publicaciones_activas = list()

        response = meli.get(f'/users/{ml_user_id}/items/search',
                            params={'access_token': meli.access_token})
        json_response = json.loads(response.content)
        publicaciones = json_response.get('results')
        if publicaciones:
            for publicacion in publicaciones:
                resp = meli.get(f'/items/{publicacion}',
                                params={'access_token': meli.access_token})
                json_publicacion = json.loads(resp.content)
                if json_publicacion['status'] == 'active':
                    publicaciones_activas.append({
                        'id':
                        str(publicacion),
                        'permalink':
                        json_publicacion['permalink'],
                        'price':
                        json_publicacion['price'],
                        'title':
                        json_publicacion['title']
                    })
        return publicaciones_activas
Esempio n. 5
0
def sincronizar_preco():
    if session.ACCESS_TOKEN:
        from meli import Meli
        meli = Meli(client_id=CLIENT_ID,
                    client_secret=CLIENT_SECRET,
                    access_token=session.ACCESS_TOKEN,
                    refresh_token=session.REFRESH_TOKEN)
        anuncios = db(Anuncios.status == 'active').select()
        #anuncios = db(Anuncios.id == 841).select()
        #anuncios = db(Anuncios.forma == 'Multiplos').select()
        for anuncio in anuncios:
            if anuncio['item_id']:
                if anuncio['forma'] == 'Multiplos':
                    body = dict(variations=buscar_variacao_preco(
                        anuncio['id'], anuncio['preco']))
                else:
                    body = dict(price=float(anuncio['preco']))
                item_args = "items/%s" % (anuncio['item_id'])
                item = meli.put(item_args, body,
                                {'access_token': session.ACCESS_TOKEN})
                if item.status_code != 200:
                    print '%s - %s - %s' % (anuncio['item_id'], anuncio['id'],
                                            item)

        session.flash = 'Preços Atualizado com Sucesso'
    else:
        session.flash = 'Antes Faça o Login....'
    response.js = "location.reload(true)"
    return
Esempio n. 6
0
def atualizar_ean():
    rows = db(Anuncios.id > 0).select()
    for row in rows:
        atributos = []
        buscaAtributos = db(Anuncios_Atributos.anuncio == row.id).select()
        for atributo in buscaAtributos:
            atributo_id = Atributos(atributo.atributo).atributo_id
            atributos.append(dict(id=atributo_id, value_name=atributo.valor))
        if atributos:
            body = dict(attributes=atributos)
            item_id = Anuncios[int(row.id)].item_id
            item_args = "items/%s" % (item_id)

            if session.ACCESS_TOKEN:
                from meli import Meli
                meli = Meli(client_id=CLIENT_ID,
                            client_secret=CLIENT_SECRET,
                            access_token=session.ACCESS_TOKEN,
                            refresh_token=session.REFRESH_TOKEN)

                item = meli.put(item_args, body,
                                {'access_token': session.ACCESS_TOKEN})

                if item.status_code != 200:
                    status = 'Falha na Atualização do Item : item:%s Descrição:%s Tipo:%s' % (
                        item, desc, tipo)
                else:
                    status = 'Anuncio Atualizado com Sucesso....'
            else:
                status = 'Antes Faça o Login....'
                item = ''
Esempio n. 7
0
 def setUp(self):
     self.CLIENT_ID = "123"
     self.CLIENT_SECRET = "a secret"
     self.ACCESS_TOKEN = "a access_token"
     self.REFRESH_TOKEN = "a refresh_token"
     self.NEW_ACCESS_TOKEN = "a new access_token"
     self.NEW_REFRESH_TOKEN = "a new refresh_token"
     self.meli =  Meli(client_id=self.CLIENT_ID, client_secret=self.CLIENT_SECRET, access_token=self.ACCESS_TOKEN, refresh_token=self.REFRESH_TOKEN)
Esempio n. 8
0
def main():
    meli = Meli(client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                access_token=ACCESS_TOKEN,
                refresh_token=REFRESH_TOKEN)
    response = meli.delete("/questions/QUESTION_ID",
                           {'access_token': meli.access_token})
    print response.content
Esempio n. 9
0
def main():
    meli = Meli(client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                access_token=ACCESS_TOKEN,
                refresh_token=REFRESH_TOKEN)

    response = meli.get("/items/ITEM_ID")
    print response.content
Esempio n. 10
0
def main():
    meli = Meli(client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                access_token=ACCESS_TOKEN,
                refresh_token=REFRESH_TOKEN)
    body = {"title": "oculos edicao especial!", "price": 1000}
    response = meli.put("/items/ITEM_+ID", body,
                        {'access_token': meli.access_token})
    print response.content
Esempio n. 11
0
def alterar_item():
    idAnuncio = session.anuncio['id']

    ## Faz Uploads das imagens e retorna Ids
    imagens = imagem_upload(idAnuncio)

    body = dict(title=session.anuncio['title'],
                price=session.anuncio['price'],
                available_quantity=session.anuncio['available_quantity'],
                shipping=session.anuncio['frete'],
                attributes=session.anuncio['attributes'],
                pictures=imagens,
                )

    #### Buscar Variações ####
    variacao = buscar_variacao(idAnuncio,imagens)

    bodyvariacao = dict(title=session.anuncio['title'],
                        shipping=session.anuncio['frete'],
                        attributes=session.anuncio['attributes'],
                        variations=variacao,
                        )
    
    listing_type_id = dict(id=session.anuncio['listing_type_id']) 
    description = session.anuncio['description']

    item_args = "items/%s" %(session.anuncio['item_id'])
    descricao_args = "%s/description" %(item_args)
    tipo_args = "%s/listing_type" %(item_args)
    
    if session.ACCESS_TOKEN:
        from meli import Meli    
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=session.ACCESS_TOKEN, refresh_token=session.REFRESH_TOKEN)

        if session.anuncio['forma'] == 'Multiplos':
            item = meli.put(item_args, bodyvariacao, {'access_token':session.ACCESS_TOKEN})
        else:
            item = meli.put(item_args, body, {'access_token':session.ACCESS_TOKEN})
        
        desc = meli.put(descricao_args,description, {'access_token':session.ACCESS_TOKEN})
        tipo = meli.post(tipo_args, listing_type_id, {'access_token':session.ACCESS_TOKEN})

        if item.status_code != 200 or desc.status_code != 200:
            status = 'Falha na Atualização do Item : item:%s Descrição:%s' %(item,desc)
        else:
            status = 'Anuncio Atualizado com Sucesso....'

    else:
        status = 'Antes Faça o Login....'
        item = ''   

    response.flash = status
    response.js = "$('#anunciospublicar').get(0).reload()"

    return 
Esempio n. 12
0
def autorize():
    from meli import Meli
    meli = Meli(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    if request.vars.code:
        meli.authorize(request.vars.code, REDIRECT_URI)
    session.ACCESS_TOKEN = meli.access_token
    session.REFRESH_TOKEN = meli.access_token
    Empresa[1] = dict(token1=session.ACCESS_TOKEN,
                      token2=session.REFRESH_TOKEN)
    #meli = Meli(client_id=CLIENT_ID,client_secret=session.CLIENT_SECRET, access_token=session.ACCESS_TOKEN, refresh_token=REFRESH_TOKEN)
    return meli.access_token
Esempio n. 13
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        client_id = settings.CLIENT_ID
        client_secret = settings.CLIENT_SECRET
        meli = Meli(client_id, client_secret)

        context['redirect_uri'] = meli.auth_url(
            redirect_URI=settings.CALLBACK_URL)

        self.request.session['CLIENT_ID'] = client_id
        self.request.session['CLIENT_SECRET'] = client_secret
        return context
Esempio n. 14
0
def anunciar_item():
    idAnuncio = session.anuncio['id']

    ## Faz Uploads das imagens e retorna Ids
    imagens = imagem_upload(idAnuncio)
    #### Buscar Variações ####
    variacao = buscar_variacao(idAnuncio,imagens)

    body = dict(title=session.anuncio['title'],
                category_id=session.anuncio['category_id'],
                price=session.anuncio['price'],
                currency_id=session.anuncio['currency_id'],
                available_quantity=session.anuncio['available_quantity'],
                buying_mode=session.anuncio['buying_mode'],
                listing_type_id=session.anuncio['listing_type_id'],
                condition=session.anuncio['condition'],
                warranty=session.anuncio['warranty'],
                description=session.anuncio['description'],
                shipping=session.anuncio['frete'],
                pictures=imagens,
                variations = variacao,
                )
    
    bodyAtributo = dict(attributes=session.anuncio['attributes'])

    if session.ACCESS_TOKEN:
        from meli import Meli 
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET, access_token=session.ACCESS_TOKEN, refresh_token=session.REFRESH_TOKEN)
        item = meli.post("/items", body, {'access_token':session.ACCESS_TOKEN})
    else:
        status = 'Antes Faça o Login....'
        item = ''    

    import json
    if item.status_code == 201:
        status = 'Anunciado com Sucesso....'
    	### Salvando item_id no banco de dados
        xitem = json.loads(item.content)    
        Anuncios[int(idAnuncio)] = dict(item_id=xitem['id'])
        ### Salvando Atributos no ML
        atrib_args = "items/%s" %(xitem['id'])
        atrib = meli.put(atrib_args, bodyAtributo, {'access_token':session.ACCESS_TOKEN})
        if atrib.status_code != 200:
            status = 'Falha na Atualização do Item : item:%s ' %(atrib)        
    else:
        status = 'Falha na Atualização do Item : item:%s ' %(item)        
    response.flash = status
    response.js = "$('#anunciospublicar').get(0).reload()"

    return
Esempio n. 15
0
def importar_anuncios():

    import json

    form = SQLFORM.factory(
        Field('anuncio_id','string',label='Id do Anuncio:'),
        Field('offset','integer',label='Inicio:', default=0),
        Field('limit','integer',label='Quantidade:',default=50),
        table_name='importaranuncio',
        submit_button='Carregar Anuncios',
        )

    xitens = []
    btnAtualizar = ''

    if form.process().accepted:

        anuncio_id = form.vars.anuncio_id
        offset = form.vars.offset
        limit = form.vars.limit 

        # Cunsulta de itens na Api do mercado livre
        from meli import Meli
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)

        if anuncio_id:
            argsItem = "items/%s" %(anuncio_id)
            busca = meli.get(argsItem)
            
            if busca.status_code == 200:
                itens = json.loads(busca.content)    
                xitens.append(itens)
        else:
            argsItem = "sites/MLB/search?seller_id=%s&offset=%s&limit=%s" %(USER_ID,offset,limit)
            busca = meli.get(argsItem)
            
            if busca.status_code == 200:
                itens = json.loads(busca.content)    
                xitens = itens['results']
        
        atualizar_anuncios(xitens)
        
        
    elif form.errors:
        response.flash = 'Erro no Formulário'

    return dict(form=form,itens = xitens,btnAtualizar=btnAtualizar)
Esempio n. 16
0
    def get(self, request, *args, **kwargs):
        try:
            code = request.GET['code']
            meli = Meli(self.request.session['CLIENT_ID'],
                        self.request.session['CLIENT_SECRET'])
        except KeyError:
            return redirect('login')

        meli.authorize(code=code, redirect_URI=settings.CALLBACK_URL)
        response = meli.get('/users/me',
                            params={'access_token': meli.access_token})
        json_response = json.loads(response.content)
        self.request.session['ML_USER_ID'] = json_response['id']

        self.request.session['ACCESS_TOKEN'] = meli.access_token
        self.request.session['REFRESH_TOKEN'] = meli.refresh_token
        return super().get(request, *args, **kwargs)
Esempio n. 17
0
def multiplos():
    # Cunsulta de itens na Api do mercado livre
    import json
    from meli import Meli
    meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)
    xitens = []
    rows = db(Anuncios.forma == 'Multiplos').select()
    for row in rows:
        anuncio_id = row.item_id
        argsItem = "items/%s" %(anuncio_id)
        busca = meli.get(argsItem)
        
        if busca.status_code == 200:
            itens = json.loads(busca.content)    
            xitens.append(itens)
    
    atualizar_anuncios(xitens)
    return
Esempio n. 18
0
def sugerir_categoria():
    if request.vars.categoria == '':
        from meli import Meli

        args = "sites/MLB/category_predictor/predict?title=%s" %(request.vars.titulo)
        meli = Meli(client_id=CLIENT_ID,client_secret=CLIENT_SECRET)
        busca = meli.get(args) 
        import json
        if busca.status_code == 200:
            sugestao = json.loads(busca.content)
            categoria = buscar_categoria(sugestao['id'])

            Categorias.update_or_insert(Categorias.categoria_id==sugestao['id'],
                categoria_id = sugestao['id'],
                categoria = categoria['categoria'],
                frete = categoria['valorFrete'],)
            
            return "jQuery('#anuncios_categoria').append(new Option('%s', '%s')).val('%s');" % (categoria['categoria'],sugestao['id'],sugestao['id'])
Esempio n. 19
0
def atualizar_estoque():

    anuncios = db(Anuncios.id > 0).select()
    for anuncio in anuncios:
        estoque = sugerido(anuncio)['estoque']
        Anuncios[anuncio.id] = dict(estoque=estoque)

    form = FORM.confirm('Atualizar Estoque',
                        {'Voltar': URL('default', 'index')})

    if form.accepted:

        if session.ACCESS_TOKEN:
            from meli import Meli
            meli = Meli(client_id=CLIENT_ID,
                        client_secret=CLIENT_SECRET,
                        access_token=session.ACCESS_TOKEN,
                        refresh_token=session.REFRESH_TOKEN)

            anuncios = db(Anuncios.id > 0).select()
            #anuncios = db(Anuncios.forma == 'Multiplos').select()
            for anuncio in anuncios:
                if anuncio['item_id']:
                    variacao = []
                    if anuncio['forma'] == 'Multiplos':
                        body = dict(
                            variations=buscar_variacao_estoque(anuncio['id']))
                    else:
                        body = dict(
                            available_quantity=float(anuncio['estoque']))
                    item_args = "items/%s" % (anuncio['item_id'])
                    item = meli.put(item_args, body,
                                    {'access_token': session.ACCESS_TOKEN})
                    if item.status_code != 200:
                        print '%s - %s - %s' % (anuncio['item_id'],
                                                anuncio['id'], item)

            response.flash = 'Estoque Atualizado com Sucesso....'

        else:
            status = 'Antes Faça o Login....'

    return dict(form=form)
Esempio n. 20
0
def main():
    meli = Meli(client_id=CLIENT_ID,
                client_secret=CLIENT_SECRET,
                access_token=ACCESS_TOKEN,
                refresh_token=REFRESH_TOKEN)
    body = {
        "condition":
        "new",
        "warranty":
        "60 dias",
        "currency_id":
        "BRL",
        "accepts_mercadopago":
        True,
        "description":
        "Lindo Ray_Ban_Original_Wayfarer",
        "listing_type_id":
        "bronze",
        "title":
        "oculos Ray Ban Aviador  Que Troca As Lentes  Lancamento!",
        "available_quantity":
        64,
        "price":
        289,
        "subtitle":
        "Acompanha 3 Pares De Lentes!! Compra 100% Segura",
        "buying_mode":
        "buy_it_now",
        "category_id":
        "MLB5125",
        "pictures": [{
            "source":
            "http://upload.wikimedia.org/wikipedia/commons/f/fd/Ray_Ban_Original_Wayfarer.jpg"
        }, {
            "source":
            "http://en.wikipedia.org/wiki/File:Teashades.gif"
        }]
    }
    response = meli.post("/items", body, {'access_token': meli.access_token})
    print response.content
Esempio n. 21
0
def active():
	meli = Meli(client_id=6586834806530948,client_secret='ml67hw3RbWcbQ6CQx3A3WXLdpf0hDyd5', access_token='APP_USR-385949866070932-051116-2a67a8e2c0732cf6d43ec2af7318a854-463010681',refresh_token='')
	# with open('playdoh3mltest.json') as file:
	# data = json.load(file)
	# for i in range(len(data)):
	# 	body=data[i]
	# 	response = meli.put("/items", body, {'access_token':meli.access_token})
	# 	print response.content


	headers = {
	    'Content-Type': 'application/json',
	}

	params = (
	    ('access_token', 'MY_ACCESS_TOKEN'),
	)

	data = '{"status":"paused"}'

	response = requests.put('https://api.mercadolibre.com/items/MLM711228874', headers=headers, params=params, data=data)

	print(response)
Esempio n. 22
0
def buscar_categoria(categoriaId):
    import json
    from meli import Meli
    meli = Meli(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    ### Buscar Categoria ###
    args = "categories/%s" % (categoriaId)
    categoria = meli.get(args)
    if categoria.status_code == 200:
        categoria = json.loads(categoria.content)

    ### Concatena Nome da Categoria ###
    nomeCategoria = ''
    for r in categoria['path_from_root']:
        if nomeCategoria:
            nomeCategoria = nomeCategoria + '/' + r['name']
        else:
            nomeCategoria = r['name']

    ### Buscar Dimensoes por Categoria ###
    valorFrete = 0
    argsDimensoes = '%s/shipping' % (args)
    categoriaDimensoes = meli.get(argsDimensoes)
    if categoriaDimensoes.status_code == 200:
        dimensoes = json.loads(categoriaDimensoes.content)

        ### Buscar Valor de Frete pelas Dimensoes da Categoria ###
        argsFrete = '/users/%s/shipping_options/free?dimensions=%sx%sx%s,%s' \
        %(USER_ID,dimensoes['height'],dimensoes['width'],dimensoes['length'],dimensoes['weight'])
        categoriaFrete = categoria = meli.get(argsFrete)

        if categoriaFrete.status_code == 200:
            frete = json.loads(categoriaFrete.content)
            valorFrete = frete['coverage']['all_country']['list_cost']

    return dict(categoria=nomeCategoria,
                categoriaId=categoriaId,
                valorFrete=valorFrete)
Esempio n. 23
0
from flask import Flask, request
import json
from meli import Meli
import os

meli = Meli(client_id=os.environ['CLIENT_ID'],
            client_secret=os.environ['CLIENT_SECRET'])

app = Flask(__name__)


@app.route('/')
def login():
    href = meli.auth_url(redirect_URI=request.url_root + 'authorize')
    return '<a href="' + href + '">Login</a>'


@app.route('/authorize')
def authorize():
    if request.args.get('code'):
        meli.authorize(request.args.get('code'),
                       request.url_root + 'authorize')
    print(meli.access_token)
    print(meli.refresh_token)
    return json.dumps({
        "ML_TOKEN": meli.access_token,
        "ML_REFRESH_TOKEN": meli.refresh_token
    })
Esempio n. 24
0
def login():
    from meli import Meli
    meli = Meli(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
    return "<a href='" + meli.auth_url(
        redirect_URI=REDIRECT_URI) + "' target='_blank'>Login</a>"
Esempio n. 25
0
import pprint
from bottle import template

LIB_PATH = os.path.join('.', 'python3-sdk', 'lib')
print(LIB_PATH)
sys.path.append(LIB_PATH)
from meli import Meli

from bottle import Bottle, run, request

CLIENT_ID = '6383285056445610'
CLIENT_SECRET = 'Zya79p7R8hLkQaRfficgmEA8bNf30a7B'
REDIRECT_URI = '''http://*****:*****@app.get('/')
@app.get('/login')
def login():
    return "<a href='" + meli.auth_url(
        redirect_URI=REDIRECT_URI) + "'>Clique aqui para Login</a>"


@app.get('/redirect')
@app.get('/authorize')
Esempio n. 26
0
                    "src": producto['image'],
                    "position": 0
                }
            ]
        }
        return (self.wcapi.post("products", data).json())


full23 = Wooadd("https://full23.com/core/api/index.php/a3wfnrg2x4kr929c")

a = full23.clean_store()

# full23.add_item("MLV466061309")
userid = full23.get_user()
items = []
mel = Meli(client_id=5747735731654676, client_secret="ITYNDyPRzGGArOuwJk2684LwDiGotzCW", access_token=key,
           refresh_token=refresh)
params = {'access_token': key, "limit": 50}
resp = mel.get("/users/" + str(userid) + "/items/search", params=params).json()
for i in resp['results']:
    items.append(i)

times = math.ceil(int(resp['paging']['total']) / 50) + 1
offset = 0

for i in range(0, int(times)):
    params = {'access_token': key, "limit": 50, "offset": offset}
    resp = mel.get("/users/" + str(userid) + "/items/search", params=params).json()
    for i in resp['results']:
        items.append(i)

    offset = offset + 50
Esempio n. 27
0
 def __init__(self, url):
     self.auth = self.get_auth(url)
     self.meli = Meli(client_id=5747735731654676, client_secret="ITYNDyPRzGGArOuwJk2684LwDiGotzCW",
                      access_token=self.auth['access_token'],
                      refresh_token=self.auth['refresh_token'])
Esempio n. 28
0
from meli import Meli
import meli_helper as mh

meli = Meli(
    client_id=4669479355659461,
    client_secret="IJX5fYHL99zo6nYWFNiBA7s4DCZODPQA",
    access_token=
    "APP_USR-4669479355659461-112714-aee0f899297f53438eae54206150c96f__L_F__-278083628"
)
conn = mh.check_connection(meli)
print(conn)
Esempio n. 29
0
import ConfigParser

config = ConfigParser.RawConfigParser()
configFilePath = r'config.txt'
config.read(configFilePath)

try:
    code = config.get('file', 'code')
    url = config.get('file', 'url')
    client_id = config.get('file', 'client_id')
    client_secret = config.get('file', 'client_secret')
except ConfigParser.NoOptionError:
    print('Could not read configuration file')
    sys.exit(1)

meli = Meli(client_id=client_id, client_secret=client_secret)


def decode(element):
    """
    Convierte unicode a string
    """
    return unicodedata.normalize('NFKD', element).encode('ascii', 'ignore')


def get_meli_users_info(users, items):
    """
    Genera un .json a partir de informacion extraida de usuarios de la SDK de MercadoLibre
    """
    meli_users_json = []
    users_items = zip(users, items)
Esempio n. 30
0
def importar_vendas():
    import json
    from datetime import datetime

    form = SQLFORM.factory(
        Field('order_id', 'string', label='Id do Pedido:'),
        Field('offset', 'integer', label='Inicio:', default=0),
        Field('limit',
              'integer',
              label='Quantidade:',
              default=50,
              requires=IS_INT_IN_RANGE(1, 51, error_message='Entre 1 e 50 !')),
        table_name='importarvendas',
        submit_button='Importar Pedidos',
    )

    itens = []

    if form.process().accepted:

        order_id = form.vars.order_id
        offset = form.vars.offset
        limit = form.vars.limit

        if session.ACCESS_TOKEN:
            from meli import Meli
            meli = Meli(client_id=CLIENT_ID,
                        client_secret=CLIENT_SECRET,
                        access_token=session.ACCESS_TOKEN,
                        refresh_token=session.REFRESH_TOKEN)

            if order_id:
                args = "orders/%s" % (order_id)
                busca = meli.get(args, {'access_token': session.ACCESS_TOKEN})
                if busca.status_code == 200:
                    xitens = json.loads(busca.content)
                    itens.append(xitens)
            else:
                args = "/orders/search/recent?seller=%s&sort=date_desc&order.status=paid&offset=%s&limit=%s" % (
                    USER_ID, offset, limit)
                busca = meli.get(args, {'access_token': session.ACCESS_TOKEN})
                #busca = meli.get("/orders/search/recent?seller=158428813&sort=date_desc&order.status=paid", {'access_token':session.ACCESS_TOKEN})

                if busca.status_code == 200:
                    itens = json.loads(busca.content)
                    itens = itens['results']

        for item in itens:

            body = "/shipments/%s" % (item['shipping']['id'])
            busca = meli.get(body, {'access_token': session.ACCESS_TOKEN})

            if busca.status_code == 200:
                shipping = json.loads(busca.content)

                Clientes.update_or_insert(
                    Clientes.id == item['buyer']['id'],
                    id=item['buyer']['id'],
                    nome="%s %s" %
                    (item['buyer']['first_name'], item['buyer']['last_name']),
                    cnpj_cpf=item['buyer']['billing_info']['doc_number'],
                    tipo=item['buyer']['billing_info']['doc_type'],
                    endereco=shipping['destination']['shipping_address']
                    ['address_line'],
                    bairro=shipping['destination']['shipping_address']
                    ['neighborhood']['name'],
                    cidade=shipping['destination']['shipping_address']['city']
                    ['name'],
                    estado=shipping['destination']['shipping_address']['state']
                    ['name'],
                    cep=shipping['destination']['shipping_address']
                    ['zip_code'],
                    fone="%s %s" % (item['buyer']['phone']['area_code'] or '',
                                    item['buyer']['phone']['number'] or ''),
                    email=item['buyer']['email'],
                    apelido=item['buyer']['nickname'],
                )

                Pedidos.update_or_insert(Pedidos.id == item['shipping']['id'],
                                         id=item['shipping']['id'],
                                         buyer_id=item['buyer']['id'],
                                         date_created=datetime.strptime(
                                             item['date_created'][:10],
                                             '%Y-%m-%d'),
                                         status=shipping['status'])

                Pedidos_Itens.update_or_insert(
                    Pedidos_Itens.id == item['id'],
                    id=item['id'],
                    shipping_id=item['shipping']['id'],
                    payments_id=item['payments'][0]['id'],
                    item=item['order_items'][0]['item']['title'],
                    item_id=item['order_items'][0]['item']['id'],
                    quantidade=item['order_items'][0]['quantity'],
                    valor=item['order_items'][0]['unit_price'],
                    taxa=0,
                    frete=0,
                )

        else:
            status = 'Antes Faça o Login....'

    elif form.errors:
        response.flash = 'Erro no Formulário'

    return dict(itens=itens, form=form)