def __init__(self, url, user, key, api_type): try: if api_type == "DRF": self.api = slumber.API(url, auth=DRFApikeyAuth(user, key)) else: self.api = slumber.API(url, auth=TastypieApikeyAuth(user, key)) self.api.generatortype.get() except Exception, ex: raise SaltsApiException("Error connection with salts: %s" % ex)
def get_credly(email=None, password=None): if email and password: return slumber.API(CREDLY_API_URL, auth=ApiAuth(CREDLY_API_KEY, CREDLY_APP_SECRET, email=email, password=password), append_slash=False) return slumber.API(CREDLY_API_URL, auth=ApiAuth(CREDLY_API_KEY, CREDLY_APP_SECRET), append_slash=False)
def main(): init() base_url = "%s/api/v3/" % settings.scrumdo_host api = slumber.API(base_url, auth=(settings.scrumdo_username, settings.scrumdo_password)) base_url = "%s/api/v3/" % settings.backup_scrumdo_host api_backup = slumber.API(base_url, auth=(settings.scrumdo_username, settings.scrumdo_password)) fix_all_labels(api, api_backup)
def __slumber_api(self): url = self.__url() if self.api_key: auth = PopItApiKeyAuth(api_key=self.api_key) else: auth = (self.user, self.password) return slumber.API(url, auth=auth, append_slash=False)
def __init__(self, token): api_session = requests.session() api_session.headers['Authorization'] = 'Bearer %s' % token api_session.headers['User-Agent'] = 'c14 python wrapper' self.api = slumber.API(API_URL, session=api_session, append_slash=False)
def __init__(self, api_url, user_name=None, api_key=None): """Initializes the uploader. Parameters ========== api_url : string This should point to your API and have a trailing slash, e.g. 'http://clevelandwiki.org/api/'. user_name : string, optional, default=None The user name for you API key. If you don't provide this here, then you will be prompted to enter it on initialization. api_key : string, optional, default=None The api_key for this user. If you don't provide this here, then you will be prompted to enter it on initialization. """ if user_name is None: self.user_name = raw_input("What is your username?\n") else: self.user_name = user_name if api_key is None: self.api_key = getpass.getpass("What is your api_key?\n") else: self.api_key = api_key self.api = slumber.API(api_url, append_slash=False)
def project_list(request, organization_slug): access_token = request.session.get("access_token") api = slumber.API("%s/api/v2/" % settings.SCRUMDO_HOSTNAME) projects = api.organizations(organization_slug).projects.get( access_token=access_token) return render_to_response("project_list.html", {'projects': projects}, context_instance=RequestContext(request))
def __init__(self, token): api_session = requests.session() api_session.headers['Authorization'] = 'Bearer %s' % token api_session.headers['User-Agent'] = 'c14 python wrapper' self.api = slumber.API(API_URL, session=api_session, append_slash=False) self.LIST_PARAM = dict({'count':None, 'max_id':None, 'since_id':None}) self.LIST_JOB = dict({'status':None, 'count':None, 'max_id':None, 'since_id':None})
def channels(self, options): text_file = open(CHANNELS_FILE, "w") api = slumber.API(API_ENDPOINT, auth=API_AUTH) channels = api.channel.get() # print channels for channel in channels['objects']: if channel['enable_monitoring'] and channel['type'] == 'stream': channel_id = channel['id'] stream_url = channel['stream_url'] channel_name = channel['name'] text_file.write("# Channel: %s \n" % channel_name) text_file.write("l%s = input.http(id='inl%s',poll_delay=5.,autostart=true,'%s')\n" % (channel_id, channel_id, stream_url)) text_file.write("l%s = mksafe(l%s)\n" % (channel_id, channel_id)) text_file.write("l%s = rewrite_metadata(insert_missing=true,[(\"channel\",\"%s\")],l%s)\n" % (channel_id, channel_id, channel_id)) text_file.write("l%s = on_metadata(id='ml%s',notify, l%s)\n" % (channel_id, channel_id, channel_id)) text_file.write("output.dummy(l%s)\n" % (channel_id)) text_file.write("l%ssample = output.file.wav(id='l%srec',start=false,'samples/l%ssample.wav', l%s)\n" % (channel_id, channel_id, channel_id, channel_id)) text_file.write("\n\n\n") text_file.close() print 'doine'
def main(): init() base_url = "%s/api/v3/" % settings.scrumdo_host api = slumber.API(base_url, auth=(settings.scrumdo_username, settings.scrumdo_password)) set_defaults(api)
def test_send_content_type_only_if_body_data_exists(self): apiuri = "http://example/api/v1/" newuri = "http://example/api/v1/myresource/" ses = mock.Mock(spec=requests.session()) r = mock.Mock(spec=requests.Response) r.status_code = 201 r.headers = {} ses.request.return_value = r api = slumber.API(apiuri, session=ses) # Empty post request api.myresource.post() ses.return_value.status_code = 201 ses.return_value.headers = {} self.assertEqual(ses.request.call_count, 1) ses.request.assert_called_with('POST', newuri, headers={'accept': 'application/json'}, data=None, files=None, params={}) api.myresource.post(data=dict(key='value')) self.assertEqual(ses.request.call_count, 2) ses.request.assert_called_with('POST', newuri, headers={ 'accept': 'application/json', 'content-type': 'application/json' }, data='{"key": "value"}', files=None, params={})
def resolve_url(site_id, view_name, args=None, kwargs=None, language=None): if site_id not in local_settings.SITES: raise ImproperlyConfigured("[Cross site] Configuration error: The given site identifier is not configured in the settings") site_conf = local_settings.SITES[site_id] language = translation.get_language() if language is None else language resolve_args = {'view_name': view_name, 'args': args, 'language': language} if kwargs: kwargs_prefix = uuid.uuid4() resolve_args["kwargs_prefix"] = kwargs_prefix prefixed_kwargs = prefix_kwargs(kwargs_prefix, kwargs) resolve_args.update(prefixed_kwargs) api_url = get_api_url(site_conf["scheme"], site_conf["domain"]) session = requests.Session() session.verify = local_settings.VERIFY_SSL_CERT api = slumber.API(api_url, session=session, auth=local_settings.API_AUTH_CREDENTIALS) resolver = RESOLVE_API_VIEW_URL.replace('/', '') url = getattr(api, resolver).get(**resolve_args)['url'] return url
def contact_type_rename(args): """Rename an existing contact type Args: oldname: the current name of the contact type newname: what the new name should be """ api = slumber.API(settings.strongpoc_server) existing_contact_type = api.contact_types.get(name=args.oldname) if not existing_contact_type: sys.exit("Contact type {} not found!".format(args.oldname)) if len(existing_contact_type) > 1: sys.exit( "Found more than one contact type when looking for {}!".format( args.oldname)) try: api.contact_types(existing_contact_type[0]["id"]).put( {"name": args.newname}) except slumber.exceptions.HttpClientError as error: sys.exit(error.content) print "Renamed contact type {} to {}".format(args.oldname, args.newname)
def _storage_api(): """ Returns slumber access to storage API. """ storage_service_url = _storage_service_url() username = get_setting('storage_service_user', 'test') api_key = get_setting('storage_service_apikey', None) api = slumber.API(storage_service_url, auth=TastypieApikeyAuth(username, api_key)) return api
def __init__( self, base_url, app_key, user_key, corp_org_id, response_format=None, service_type=None, ): self.base_url = base_url self.app_key = app_key self.user_key = user_key self.corp_org_id = corp_org_id if not service_type: service_type = self.SERVICE_TYPE if not service_type: raise ImproperlyConfigured("service_type is required") if not response_format: response_format = DEFAULT_AGILE_RESPONSE_FORMAT base_url = parse.urljoin( base_url, '{0}.svc/{1}'.format(service_type, response_format)) self.api = slumber.API(base_url=base_url, format='json', append_slash=False)
def handle(self, *args, **options): api = slumber.API(settings.FUM_API_ENDPOINT, auth=_slumber_auth.TokenAuth( settings.FUM_ACCESS_TOKEN)) cache = get_cache("user_hashes") c = 1 while True: data = api.users.get(page=c) for user in data["results"]: user_hash = hashlib.sha512(str(user)).hexdigest() cache_key = "user-refresh-hash-%s" % user["username"] stored_hash = cache.get(cache_key) if stored_hash == user_hash: sd.incr( "login_frontend.management.refresh_users.no_changes") continue cache.set(cache_key, user_hash, 86400 + random.randint(0, 7200)) sd.incr("login_frontend.management.refresh_users.refresh") status = refresh_user(user) if status: sd.incr("login_frontend.management.refresh_users.updated") self.stdout.write('Refreshed %s (%s, %s, %s)' % (user.get("username"), user.get("email"), user.get("phone1"), user.get("phone2"))) if "next" not in data or data["next"] is None: break c += 1 self.stdout.write('Successfully fetched all users')
def service_provider_rename(args): """Rename an existing service provider Args: oldname: the current name of the service provider newname: what the new name should be """ api = slumber.API(settings.strongpoc_server) existing_service_provider = api.service_providers.get(name=args.oldname) if not existing_service_provider: sys.exit("Service provider {} not found!".format(args.oldname)) if len(existing_service_provider) > 1: sys.exit( "Found more than one service provider when looking for {}!".format( args.oldname)) try: api.service_providers(existing_service_provider[0]["id"]).put( {"name": args.newname}) except slumber.exceptions.HttpClientError as error: sys.exit(error.content) print "Renamed service provider {} to {}".format(args.oldname, args.newname)
def get_slumber_api(self, append_slash=True): if self.api is not None: return self.api s = self.get_requests_session() self.api = slumber.API(self.url, session=s, append_slash=append_slash) return self.api
def __init__(self, client_id, client_secret, access_token, user_id=None): auth = OAuth2(client_id, Client(client_id), {'access_token': access_token}) user = user_id if user_id else 'me' s = Serializer(default="json", serializers=[MisfitSerializer()]) self.api = slumber.API('%smove/resource/v1/user/%s/' % (API_URL, user), auth=auth, serializer=s)
def dispatch(self, request, *args, **kwargs): self.course_api_enabled = switch_is_active('enable_course_api') if self.course_api_enabled and request.user.is_authenticated(): self.access_token = request.user.access_token self.course_api = slumber.API(settings.COURSE_API_URL, auth=BearerAuth(self.access_token)).courses return super(CourseAPIMixin, self).dispatch(request, *args, **kwargs)
def test_extra_header(self): extra_headers = {"Accept-Language": "en-GB"} client = slumber.API(base_url="http://httpbin.org/", append_slash=False, extra_headers=extra_headers) resp = client.headers.get() self.assertDictContainsSubset(extra_headers, resp["headers"])
def __init__(self, email=DEFAULT_EMAIL, password=DEFAULT_PASSWD, url=DEFAULT_URL): self.url = url self.auth = GenAuth(email, password, url) self.api = slumber.API(urlparse.urljoin(url, 'api/v1/'), self.auth) self.cache = {'objects': {}, 'projects': None, 'project_objects': {}}
def test_connect_timeout(self): client = slumber.API(base_url='http://httpbin.org/', append_slash=False, timeout=(0.00000000001, None)) with self.assertRaises(requests.exceptions.ConnectTimeout): client.delay(10).get() assert False, "The connect() request should time out."
def __init__(self, *args, **kwargs): self._query_cache = {} self.order_group_id = 0 self.instrument = None self.timestamp = None self.metrics = [] self._earnings_announcements_cache = [] self._query_cache = {} self.api = slumber.API(consts.API_URL)
def test_read_timeout(self): client = slumber.API(base_url='http://httpbin.org/', append_slash=False, timeout=(None, 0.01)) with self.assertRaises(requests.exceptions.ReadTimeout): client.delay(10).get() assert False, "The recv() request should time out."
def main(): init() base_url = "%s/api/v3/" % settings.scrumdo_host api = slumber.API(base_url, auth=(settings.scrumdo_username, settings.scrumdo_password)) for project in api.organizations( settings.organization_slug).projects.get(): exportProject(project, api)
def login(request): """ Loguje uzytkownika. """ global api user, password = request.POST.get('user'), request.POST.get('password') # GET 127.0.0.1:8000 -a user:password api = slumber.API("http://127.0.0.1:8000/", auth=(user, password)) return redirect('/')
def __init__(self, api_url, model_type, api_auth): """ api_url - the base url for the api (settings.FULL_API_START) model_type - the type of model to encapsulate (ie 'organization') api_auth - the api auth dict for a given user (see UserProfile.get_api_auth) """ self.api = slumber.API(api_url) self.api_url = api_url self.model_type = model_type self.api_auth = api_auth self.objects = []
def dispatch(self, request, *args, **kwargs): self.course_api_enabled = switch_is_active('enable_course_api') if self.course_api_enabled: logger.debug('Instantiating Course API with URL: %s', settings.COURSE_API_URL) self.course_api = slumber.API( settings.COURSE_API_URL, auth=TokenAuth(settings.COURSE_API_KEY)).v0.courses return super(CourseAPIMixin, self).dispatch(request, *args, **kwargs)
def test_api(self): r = mock.Mock(spec=requests.Response) r.status_code = 200 r.headers = {"content-type": "application/json"} r.content = '{"result": ["a", "b", "c"]}' client = slumber.API(base_url="http://example/api/v1", session=mock.Mock(spec=requests.Session)) client.test._store["session"].request.return_value = r resp = client.test.get() self.assertEqual(resp['result'], ['a', 'b', 'c'])