def test_env_instance(self, instance_mock, registry_mock, *args): self.assertFalse(registry_mock.set_default_instance.called) connect(1, 2, 3, a=1, b=2, c=3) self.assertTrue(registry_mock.set_default_instance.called) registry_mock.set_default_instance.assert_called_once_with(instance_mock)
def test_env_instance(self, instance_mock, registry_mock, *args): instance_mock.return_value = 'test_instance' self.assertFalse(registry_mock.set_used_instance.called) connect(1, 2, 3, a=1, b=2, c=3) self.assertTrue(registry_mock.set_used_instance.called) registry_mock.set_used_instance.assert_called_once_with(instance_mock)
def test_env_instance(self, instance_mock, registry_mock, *args): self.assertFalse(registry_mock.set_default_instance.called) connect(1, 2, 3, a=1, b=2, c=3) self.assertTrue(registry_mock.set_default_instance.called) registry_mock.set_default_instance.assert_called_once_with( instance_mock)
def __init__(self): creds = pickle.load(open("creds", "rb")) self.con = syncano.connect(email=creds["email"], password=creds["password"]) instance = self.con.Instance self.instance = list(instance.please.all())[0] self.voting = self.instance.classes.get(name="voting")
def main(): registry = syncano.connect(api_key=syncano.APIKEY) parent = os.getcwd() for solution in get_solutions(registry): # print(solution) if not solution['description']: continue LOG.info('importing_solution {id}: {description}'.format(**solution)) temp_instance = registry.instances.create( name='solution_import_{id}'.format(**solution) ) try: import_solution(solution, temp_instance) dirname = label_to_path(solution['label']) if not os.path.exists(dirname): os.mkdir(dirname) os.chdir(dirname) with open('README.md', 'wb') as readme: readme.write(solution['description']) readme.write('\n') subprocess.check_call(['syncano', 'sync', 'pull', '-a', temp_instance.name]) os.chdir(parent) except exceptions.SyncanoRequestError as e: LOG.exception(e) finally: temp_instance.delete()
def push(context): """ Push configuration changes to syncano. """ con = syncano.connect(api_key=context.key) instance = con.instances.get(name=context.instance) context.project.push_to_instance(instance, classes=context.classes, scripts=context.scripts, all=context.all)
def test_connect(self, open_mock): self.assertFalse(open_mock.called) connection = connect(1, 2, 3, a=1, b=2, c=3) open_mock.assert_called_once_with(1, 2, 3, a=1, b=2, c=3) self.assertTrue(open_mock.called) self.assertEqual(connection, registry)
def setUpClass(cls): cls.API_KEY = os.getenv('INTEGRATION_API_KEY') cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL') cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD') cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT') cls.connection = syncano.connect(host=cls.API_ROOT, email=cls.API_EMAIL, password=cls.API_PASSWORD, api_key=cls.API_KEY)
def syncano(self): if self._syncano: return self._syncano syncano_connection = syncano.connect( api_key=self.config.get('P2S', 'SYNCANO_ADMIN_API_KEY'), instance_name=self.config.get('P2S', 'SYNCANO_INSTANCE_NAME'), ) self._syncano = syncano_connection return self._syncano
def test_connect(self, open_mock, registry_mock): registry_mock.return_value = registry_mock self.assertFalse(registry_mock.called) self.assertFalse(open_mock.called) connection = connect(1, 2, 3, a=1, b=2, c=3) open_mock.assert_called_once_with(1, 2, 3, a=1, b=2, c=3) self.assertTrue(open_mock.called) self.assertEqual(connection, registry_mock)
def setUpClass(cls): cls.API_KEY = os.getenv('INTEGRATION_API_KEY') cls.API_EMAIL = os.getenv('INTEGRATION_API_EMAIL') cls.API_PASSWORD = os.getenv('INTEGRATION_API_PASSWORD') cls.API_ROOT = os.getenv('INTEGRATION_API_ROOT') cls.connection = syncano.connect( host=cls.API_ROOT, email=cls.API_EMAIL, password=cls.API_PASSWORD, api_key=cls.API_KEY )
def syncano(self): if self._syncano: return self._syncano syncano_connection = syncano.connect( api_key=config.get('P2S', 'SYNCANO_ADMIN_API_KEY'), host=config.get('P2S', 'SYNCANO_APIROOT'), instance_name=config.get('P2S', 'SYNCANO_INSTANCE_NAME'), ) self._syncano = syncano_connection return self._syncano
def pull(context): """ Pull configuration from syncano and store it in current directory. Updates syncano.yml configuration file, and places scripts in scripts directory. When syncano.yml file exists. It will pull only objects defined in configuration file. If you want to pull all objects from syncano use -a/--all flag. """ con = syncano.connect(api_key=context.key) instance = con.instances.get(name=context.instance) context.project.update_from_instance(instance, context.all, context.classes, context.scripts) context.project.write(context.file)
def create_connection(config, instance_name=None): config = config or ACCOUNT_CONFIG_PATH ACCOUNT_CONFIG.read(config) api_key = ACCOUNT_CONFIG.get('DEFAULT', 'key') connection_dict = { 'api_key': api_key, } instance_name = get_instance_name(config, instance_name) if instance_name: connection_dict['instance_name'] = instance_name try: return syncano.connect(**connection_dict) except SyncanoException: raise BadCredentialsException()
def test_register(self): connection = syncano.connect( host=os.getenv('INTEGRATION_API_ROOT'), ) email = 'syncano.bot+997999{}@syncano.com'.format(random.randint(100000, 50000000)) connection.connection().register( email=email, password='******', first_name='Jan', last_name='Nowak' ) # test if LIB has a key now; account_info = connection.connection().get_account_info() self.assertIn('email', account_info) self.assertEqual(account_info['email'], email)
def login(args): """ Log in to syncano using email and password and store ACCOUNT_KEY in configuration file. """ email = os.environ.get('SYNCANO_EMAIL', None) if email is None: email = raw_input("email: ") password = os.environ.get('SYNCANO_PASSWORD', None) if password is None: password = getpass("password: ").strip() connection = syncano.connect().connection() try: ACCOUNT_KEY = connection.authenticate(email=email, password=password) ACCOUNT_CONFIG.set('DEFAULT', 'key', ACCOUNT_KEY) with open(args.config, 'wb') as fp: ACCOUNT_CONFIG.write(fp) except SyncanoException as error: print(error)
def login(context, config, instance_name): """ Log in to syncano using email and password. """ config = config or ACCOUNT_CONFIG_PATH context.obj['config'] = config email = os.environ.get('SYNCANO_EMAIL') or click.prompt("email") password = os.environ.get('SYNCANO_PASSWORD') or click.prompt( "password", hide_input=True).strip() connection = syncano.connect().connection() try: ACCOUNT_KEY = connection.authenticate(email=email, password=password) ACCOUNT_CONFIG.set('DEFAULT', 'key', ACCOUNT_KEY) if instance_name: ACCOUNT_CONFIG.set('DEFAULT', 'instance_name', instance_name) with open(context.obj['config'], 'wt') as fp: ACCOUNT_CONFIG.write(fp) click.echo("INFO: Login successful.") except SyncanoException: raise BadCredentialsException()
def __init__(self, config_path): self.connection = syncano.connect() self.config_path = config_path
#!/usr/bin/env python # -*- coding: utf8 -*- import RPi.GPIO as GPIO import MFRC522 import signal import requests import json import time import syncano import os from syncano.models import Object connection = syncano.connect(instance_name=os.environ['INSTANCE_NAME'], api_key=os.environ['SYNCANO_API_KEY'], user_key=os.environ['SYNCANO_USER_KEY']) #----------- CONFIGURATION ------- global pinNumber global curr_state global prev_state __input = {'sensor': 11} output = { 'relay': 13, 'greenDiode': 18, 'redDiode': 16, 'buzzer': 7, 'sensor': 11 } pinNumber = [] #---------------- END CONFIG -------- class keypad():
from syncano.models import Object from tempfile import * import syncano import requests import zipfile import tempfile import os syncano.connect(api_key="SYNCANO ACCOUNT KEY") file_url = ARGS.get('file_url', None) if file_url is None: raise ValueError("You didn't pass file_url to your CodeBox Execution") # gets pdf file from url pdf_file = requests.get(file_url) # set up temporary directory and save the pdf file in it temp_directory = tempfile.mkdtemp() pdf_file_name = temp_directory + "/pdf_file.pdf" f = open(pdf_file_name, "wb") f.write(pdf_file.content) f.close() # make request for conversion and then save contents to zip headers = { # Get your mashape api key here, make sure to sign up for a mashape account # first. Replace username in the link below with your mashape username # and get your key! # https://www.mashape.com/YOUR_USERNAME/applications/default-application
# https://developers.google.com/maps/documentation/geocoding/intro import requests, syncano, json from syncano.models.base import Object accesstoken = 'INSERT_GOOGLEMAPS_API_TOKEN_HERE' connection = syncano.connect(api_key='INSERT_SYNCANO_API_KEY_HERE') #extract values from the ARGS #if only lat & lon are passed, the solution will store it #if an address is provided, the solution will convert it into coordinates and then store it # you can pass those ARGS e.g. in a webhook by calling: # https://api.syncano.io/v1/instances/<instance>/webhooks/p/<public_link>/?lat=1234&lon=1234 # or in a direct CodeBox call: # CodeBox.please.run(instance_name='YOUR_INSTANCE_NAME', id=the_CodeBox_id, payload={'lat': '1234', 'lon': '1234'}) lat = ARGS.get("lat", None) lon = ARGS.get("lon", None) address = ARGS.get("address", None) if address is None: if lat is None and lon is None: raise ValueError("ERROR: no parameters found") if lat is None or lon is None: raise ValueError("ERROR: coordinate is invalid") if address is not None: base_url = "https://maps.googleapis.com/maps/api/geocode/json?address=" accesstoken = '&key=' + accesstoken address = address.strip(" ").replace(" ", "+") url = base_url + address + accesstoken
def __init__(self, context): con = syncano.connect(api_key=context.obj['key']) self.instance = con.instances.get(name=context.obj['instance']) self.project = context.obj['project'] self.context = context self.project_file = os.path.relpath(context.obj['file'])
def __init__(self): creds = pickle.load(open("creds","rb")) self.con = syncano.connect(email=creds["email"],password=creds["password"]) instance = self.con.Instance self.instance = list(instance.please.all())[0] self.voting = self.instance.classes.get(name="voting")
from twilio.rest import TwilioRestClient from syncano.models import Object import syncano # Make connection to Syncano syncano.connect(api_key="SYNCANO_API_KEY") syncano_instance_name = "ENTER_INSTANCE_NAME_HERE" # Your Twilio Account Sid and Auth Token from twilio.com/user/account account_sid = "ENTER_YOUR_ACCOUNT_SID_HERE" auth_token = "ENTER_YOUR_AUTH_TOKEN_HERE" client = TwilioRestClient(account_sid, auth_token) # connect with twilio message_body = ARGS.get('body', None) # Arg 'body' is passed to CodeBox media_url = ARGS.get('media_url', None) # Arg 'media_url' -- gif, jpeg, or png to_number = ARGS.get('to_number', None) # Arg 'to_number' is receiving number, ie; "+13475555717" if to_number is None: raise ValueError("You didn't pass to_number") elif message_body is None and media_url is None: raise ValueError("You didn't pass any 'body' or 'media_url'") from_number = "+12015552508" # Replace with your Twilio number or shortcode message = client.messages.create(body=message_body, media_url=media_url, to=to_number, from_=from_number) message_sid = message.sid # id of message for looking up with twilio # We store the message in syncano stored_message = Object.please.create(class_name="message", message=message_body,
from syncano.models import Object from qrcode import * import syncano import StringIO syncano.connect(api_key="YOUR_API_KEY_HERE") # Get Unique Data for solution from ARGs # Unique data can be any String data = ARGS.get("data", None) if data is None: raise ValueError("You did not pass any data for the QRCode") # version is size, read more on parameters here # https://pypi.python.org/pypi/qrcode qr = QRCode(version=5, error_correction=ERROR_CORRECT_L) # Generate QRCode object qr.add_data(data) # Adds QR code data qr.make() # Generate the QRCode itself # Generate and save image as StringIO file image = qr.make_image() output = StringIO.StringIO() image.save(output) contents = output.getvalue() output.close() # Save QRCode image to Syncano class "qrcode" Object.please.create(instance_name="YOUR_INSTANCE_NAME_HERE", class_name="qrcode", image=contents,
import requests import json import syncano from datetime import datetime from syncano.models import Object url = "https://dash.readme.io/api/projects/" + CONFIG["project"] + "/" \ + CONFIG["version"] + "/export" headers = {"Cookie": CONFIG["cookie"]} r = requests.get(url, headers=headers) parsed = json.loads(r.content) file_path = "/tmp/backup" with open(file_path, "w") as f: json.dump(parsed, f) f.close() connection = syncano.connect(api_key=CONFIG["account_key"]) file = open(file_path, "r") Object.please.create(instance_name=META["instance"], class_name="readme_backup", file=file)
from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser from syncano.models import Object import syncano # Make google developer account here, follow instructions to get # the google DEVELOPER_KEY # https://developers.google.com/youtube/v3/getting-started DEVELOPER_KEY = "Put your developer key here" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" syncano.connect(api_key="SYNCANO_API_KEY") query = ARGS.get("query", None) order = ARGS.get( "order", "relevance" ) # If you don't specify order, we default the order to 'relevance' max_results = ARGS.get("max_results", 10) # Can be 0-10, default is 10 if query is None: raise ValueError("You did not pass 'query'") def youtube_search(query, order, max_results): youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) # Call the search.list method to retrieve results matching the specified # query term. # https://developers.google.com/youtube/v3/guides/implementation/search
from syncano.models import Object from tempfile import * import syncano import requests import zipfile import tempfile import os syncano.connect(api_key="SYNCANO ACCOUNT KEY") file_url = ARGS.get('file_url', None) if file_url is None: raise ValueError("You didn't pass file_url to your CodeBox Execution") # gets pdf file from url pdf_file = requests.get(file_url) # set up temporary directory and save the pdf file in it temp_directory = tempfile.mkdtemp() pdf_file_name = temp_directory + "/pdf_file.pdf" f = open(pdf_file_name, "wb") f.write(pdf_file.content) f.close() # make request for conversion and then save contents to zip headers = { # Get your mashape api key here, make sure to sign up for a mashape account # first. Replace username in the link below with your mashape username # and get your key! # https://www.mashape.com/YOUR_USERNAME/applications/default-application "X-Mashape-Key": "PLACE API KEY HERE",
import syncano import json password = json.load(open("password.p", "rb")) connection = syncano.connect(email="*****@*****.**", password=password)
# https://developer.venmo.com/docs/quickstart import requests, syncano, json from syncano.models.base import Object # extract phone, note, and amount from the ARGS # if none are passed, it will raise an error # you can pass those ARGS e.g. in a webhook by calling: # https://api.syncano.io/v1/instances/<instance>/webhooks/p/<public_link>/?phone=1234¬e=helloworld&amount=0.01 # or in a direct CodeBox call: # CodeBox.please.run(instance_name='YOUR_INSTANCE_NAME', id=the_CodeBox_id, payload={'phone': '1234', 'note': 'helloworld', 'amount': '0.01'}) accesstoken = 'INSERT_VENMO_ACCESS_TOKEN_HERE' connection = syncano.connect(api_key='SYNCANO_API_KEY') # a valid US 'phone', 'email' or Venmo 'user_id' is required phone = ARGS.get("phone", None) note = ARGS.get("note", None) amount = ARGS.get("amount", None) data = {} data['access_token'] = accesstoken data['phone'] = phone data['note'] = note data['amount'] = amount missing = [] for key in data: if data[key] is None: missing.append(key) if len(missing) > 0: parameters = ""
from syncano.models import Object, CodeBox import syncano syncano_account_key = CONFIG["syncano_account_key"] syncano.connect(api_key=syncano_account_key) instance_name = CONFIG["instance_name"] all_cities = Object.please.list(instance_name=instance_name, class_name="city_weather") update_city_weather_codebox_id = CONFIG["update_city_weather_codebox_id"] # For loop that updates the weather for all cities for city in all_cities: # This CodeBox updates the weather for a city CodeBox.please.run(instance_name=instance_name, id=update_city_weather_codebox_id, payload={"object_id":city.id}) ''' This codebox loops through all the city objects and updates their weather by running the CodeBox with the label "update_city_weather" We run this CodeBox on a schedule. The updates for the city objects all go into the channel "weather_realtime" The channel has a room name which is ID of the city, we get this unique ID from the open weather map api. Each city is in a different channel room. This makes parsing the changes on the front end easy! Dont forget these three things in the CONFIG file - syncano_account_key - instance_name