def connect_oauth(): """ This function connects to Project Place API with OAuth1 It uses environement variables. For development only, it can use a dict called env-var in env-var.py at the project root. """ PP_BASE_URL = os.environ.get('PP_BASE_URL', get_env_variable('PP_BASE_URL')) CLIENT_KEY = os.environ.get('PP_CLIENT_KEY', get_env_variable('CLIENT_KEY')) CLIENT_SECRET = os.environ.get('PP_CLIENT_SECRET', get_env_variable('CLIENT_SECRET')) access_token_key = os.environ.get('PP_access_token_key', get_env_variable('access_token_key')) access_token_secret = os.environ.get( 'PP_access_token_secret', get_env_variable('access_token_secret')) if access_token_key is None: print('Getting request token...:', ) oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET) r = requests.post(PP_BASE_URL + 'initiate', auth=oauth) credentials = parse_qs(r.content) request_token_key = credentials.get('oauth_token')[0].decode('ascii') request_token_secret = credentials.get('oauth_token_secret')[0].decode( 'ascii') print(request_token_key, 'with secret', request_token_secret) print("Opening webbrowser to authenticate request token") webbrowser.open(PP_BASE_URL + '/authorize?oauth_token=' + request_token_key) oauth_verifier = raw_input('Input oauth_verifier: ') print("Exchanging request token for access token") oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET, resource_owner_key=request_token_key, resource_owner_secret=request_token_secret, verifier=oauth_verifier) r = requests.post(PP_BASE_URL + 'token', auth=oauth) credentials = parse_qs(r.content) access_token_key = credentials.get('oauth_token')[0].decode('ascii') access_token_secret = credentials.get('oauth_token_secret')[0].decode( 'ascii') print("Successfully fetch access token", access_token_key, 'with secret', access_token_secret) print('Getting user profile...', ) oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET, resource_owner_key=access_token_key, resource_owner_secret=access_token_secret) r = requests.get(url=PP_BASE_URL + '1/user/me/profile', auth=oauth) print( json.dumps(r.json(), sort_keys=True, indent=4, separators=(',', ': '))) return (oauth)
def test_uploadPhoto(): oauth = OAuth(client_key=consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) h = {'Content-Type': 'application/json', 'Accept': 'application/json'} uploadPhoto('ANOTHER TEST ITEM AA', oauth=oauth, h=h, post=True)
def GetOauthDetails(): frappe.errprint("in get oauth details") oauth = OAuth(client_key='c069f82639779dba424a19da7bb3946e', client_secret='2586f31b9c69084ac431def208f055d1', resource_owner_key='f296cbe24a82dec20dd8878a43e4e2fd', resource_owner_secret='aa9625f1580a21d2d6d3c51d063f2456') return oauth
def GetCount(): frappe.errprint("in get count details") oauth = OAuth(client_key='c069f82639779dba424a19da7bb3946e', client_secret='2586f31b9c69084ac431def208f055d1', resource_owner_key='f296cbe24a82dec20dd8878a43e4e2fd', resource_owner_secret='aa9625f1580a21d2d6d3c51d063f2456') h = {'Content-Type': 'application/json', 'Accept': 'application/json'} r = requests.get( url='http://staging.digitales.com.au.tmp.anchor.net.au/api/rest/count', headers=h, auth=oauth) d = json.loads(r.content) return d
def getProducts(): oauth = OAuth(client_key=consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) h = {'Content-Type': 'application/json', 'Accept': 'application/json'} r = requests.get(url='%s/index.php/rest/V1/products?searchCriteria=test' % MAGENTO_HOST, headers=h, auth=oauth) print r.content items = json.loads(r.content) print items["items"]
def postCategory(item): oauth = OAuth(client_key=consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) h = {'Content-Type': 'application/json', 'Accept': 'application/json'} product = """ { "category": { "name": "%s", "isActive": true } } """ % (item.item_group_name) print "**************** ", product r = requests.post(url='%s/index.php/rest/V1/categories' % MAGENTO_HOST, headers=h, data=product, auth=oauth) print r print r.content if r.status_code == 200: r_magento = json.loads(r.content) item.magento_id = r_magento['id'] print "MAGENTO ID: ", item.magento_id frappe.msgprint("""Successfully added Category: {0}""".format( item.item_group_name)) elif r.status_code == 400: print "STATUS 400" r = requests.get(url='%s/index.php/rest/V1/categories' % MAGENTO_HOST, headers=h, auth=oauth) # print r.content r_magento = json.loads(r.content) print r_magento for cat in r_magento['children_data']: print cat if cat['name'] == item.name: item.magento_id = cat['id'] frappe.msgprint("""Category {0} already exists.""".format( item.item_group_name))
def GetOauthDetails(): """ get auth object """ try: oauth_details = frappe.db.get_value('API Configuration Page', None, '*', as_dict=1) oauth = OAuth(client_key=oauth_details.client_key, client_secret=oauth_details.client_secret, resource_owner_key=oauth_details.owner_key, resource_owner_secret=oauth_details.owner_secret) return oauth except Exception, e: create_scheduler_exception(e, 'GetOauthDetails', frappe.get_traceback())
import json CLIENT_KEY = u'2fbf522ed6ba4f07723f9347d6aaf2c3' CLIENT_SECRET = u'6d6d7d95edacc1e7a337ae26792c41d9844054ba' # BASE_URL = u'https://api-pptest.projectplace.com/' BASE_URL = u'https://rnd3.demo.projectplace.com/' # If you already have an access token and secret, fill those in here. That will bypass the whole authentication # flow and allow you to issue requests immediately. (I.e if you have a robot account or an already authenticated user. access_token_key = None access_token_secret = None if access_token_key is None: print('Getting request token...:') oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET) print(oauth) r = requests.post(BASE_URL + 'initiate', auth=oauth) credentials = parse_qs(r.content) request_token_key = credentials.get(b'oauth_token')[0].decode('ascii') request_token_secret = credentials.get(b'oauth_token_secret')[0].decode( 'ascii') print(request_token_key, 'with secret', request_token_secret) print("Opening webbrowser to authenticate request token") webbrowser.open(BASE_URL + '/authorize?oauth_token=' + request_token_key) oauth_verifier = input('Input oauth_verifier: ') print("Exchanging request token for access token") oauth = OAuth(CLIENT_KEY, client_secret=CLIENT_SECRET,
1. 100 records per api request 2. JSONS nested within JSONS 3. unnecessary/duplicate item info for almost every order Various dataframes created and merged """ import requests from requests_oauthlib import OAuth1Session from requests_oauthlib import OAuth1 as OAuth import pandas as pd import numpy as np import json from pandas.io.json import json_normalize # place oauth details here: client_key, client_secret, resource_owner_key, resource_owner_secret oauth = OAuth(client_key, client_secret, resource_owner_key, resource_owner_secret) h = {'Content-Type': 'application/json', 'Accept': 'application/json'} uri = 'https://modernica.net/shop/api/rest/orders' def orders(uri, pages, startpg): # order details producer df_final = pd.DataFrame() def unpk(df): # each item/address in an order is stored in its own JSON print('pg {}. {} pages remaining.'.format(startpg, pages)) unpacked = pd.DataFrame() for column in df: # take each JSON and append to new dataframe a = pd.read_json(df[column].to_json(), orient='index')
def postProduct(item): if item.request_from == "ERPNEXT": oauth = OAuth(client_key=consumer_key, client_secret=consumer_secret, resource_owner_key=access_token, resource_owner_secret=access_token_secret) h = {'Content-Type': 'application/json', 'Accept': 'application/json'} net_weight = item.net_weight or 0.0 price = item.standard_rate or 0.0 category_magento_id = frappe.db.sql( """SELECT magento_id FROM `tabItem Group` WHERE name=%s""", (item.item_group)) category_ids = '1' if category_magento_id[0][0] != None: category_ids = category_magento_id[0][0] else: frappe.throw( "Item Cateogry {0} has no magento_id. Try saving Item Group in Item Group." .format(item.item_group)) images = """ "media_gallery_entries": [ """ test_images = '' photos = frappe.db.sql( """SELECT file_url,name FROM `tabFile` WHERE attached_to_name=%s AND attached_to_doctype='Item' AND synced_to_erpnext=0""", (item.item_code)) print photos photo_count = 0 for photo in photos: with open(frappe.get_site_path() + photo[0], "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) if photo_count > 0: images += """, """ image_types = ['jpg', 'jpeg', 'png'] image_type_is = '' for type in image_types: if photo[0].endswith(type): image_type_is = type break if image_type_is == 'jpg': image_type_is = 'jpeg' if image_type_is == '': frappe.throw( 'file type not supported. Will only support the .ff:'. format(image_types)) """ "media_type": "image", "label": "Image", "disabled": false, "types": [ "image", "small_image", "thumbnail" ], "file": "string", "content": { "base64_encoded_data": "%s", "type": "image/png", "name": "%s" """ images += """ { "media_type": "image", "label": "%s", "disabled": false, "content": { "base64_encoded_data": "%s", "type": "image/%s", "name": "%s" } } """ % (photo[1], encoded_string, image_type_is, photo[1]) test_images += """ { "media_type": "image", "label": "%s", "disabled": false, "content": { "type": "image/%s", "name": "%s" } } """ % (photo[1], image_type_is, photo[1]) photo_count += 1 images += """] """ print "Image type is: ", image_type_is print test_images product = """ { "product": { "sku": "%s", "name": "%s", "price": %.2f, "attribute_set_id":4, "weight": %f, "status": %d, "custom_attributes": [ { "attribute_code": "category_ids", "value": "%s" }, { "attribute_code": "description", "value": "%s" }, { "attribute_code": "short_description", "value": "%s" }, { "attribute_code": "meta_description", "value": "%s" } ], %s } } """ % (item.item_code, item.item_code, price, net_weight, item.disabled, category_ids, item.description, item.description, item.description, images) exists = frappe.db.sql( """SELECT Count(*) FROM `tabItem` WHERE item_code=%s""", (item.item_code)) r = requests.post(url='%S/index.php/rest/V1/products?ERPNext=true' % MAGENTO_HOST, headers=h, data=product, auth=oauth) if r.status_code == 200: frappe.msgprint( """Successfully updated/created item: {0} in Magento.""". format(item.item_code)) else: frappe.throw("Unsuccessful. Status Code {0}. Response: {1}".format( r.status_code, r.content)) r_magento = json.loads(r.content) if not item.magento_id: item.magento_id = r_magento['id'] print "MAGENTO ID: ", item.magento_id