def test_all_methods(self): """Test all HTTP methods""" url = Url('http://domain.com') self._test_all_methods(url, 'http://domain.com') new_url = url.join('path/a/b') self._test_all_methods(new_url, 'http://domain.com/path/a/b')
def test_requests_raises_error(self): """Test that requests properly raises its own errors >>> requests.get('/kk') requests.exceptions.MissingSchema: Invalid URL u'/kk': No schema supplied. Perhaps you meant http:///kk? """ url = Url('') self.assertRaises(requests.exceptions.MissingSchema, url.get)
def test_non_root_base_url_with_slash(self, r_request): """Test creating non-root base url with slash""" url = Url('http://domain.com/api/') r_request = MagicMock(return_value=None) new_url = url.join('/path/a/b') new_url.get() requests.request.assert_called_with('GET', 'http://domain.com/api/path/a/b')
def test_join_urls(self, r_request): """Test creating new sub-Urls""" url = Url('http://domain.com') r_request = MagicMock(return_value=None) new_url = url.join('/path/a/b') new_url.get() requests.request.assert_called_with('GET', 'http://domain.com/path/a/b')
def test_joined_urls_option_passing(self, r_request): """Test that original options are correctly passed to joined urls""" url = Url('http://domain.com', auth=('user', 'pass')) r_request = MagicMock(return_value=None) new_url = url.join('path') new_url.get() requests.request.assert_called_with('GET', 'http://domain.com/path', auth=('user', 'pass'))
def send_request(req): '''Sends a GET request and returns the JSON response content''' if conf['verbose']: print('Sending request: ' + req) response = Url(req).get().json() if conf['verbose']: print('Got response: ' + json.dumps(response)) return response
def test_join_url_preserves_original_url(self, r_request): """Test that original url is not touched when joining urls.""" url = Url('http://domain.com/') r_request = MagicMock(return_value=None) new_url = url.join('/path') new_url.get() requests.request.assert_called_with('GET', 'http://domain.com/path') new_url = url.join('/path/') new_url.get() requests.request.assert_called_with('GET', 'http://domain.com/path/')
def pull(self, slug, destination, kind, commit=True): """ Get the tarball to install updated PO files @commit arg to effectively install PO files or not """ self.logger.debug("Downloading the tarball") # Get project datas self.get_project(slug) tarball_url = Url(self.project_tarball_url, params={'kind': kind}, auth=self.auth_settings) # Get the tarball response = tarball_url.get(stream=True) # Get a temporary directory tmpdir = tempfile.mkdtemp(suffix='_po-projects-client') self.logger.debug("Opening the tarball") # Write the tarball in memory fp = io.StringIO() for chunk in response.iter_content(1024): fp.write(chunk) fp.seek(0) # Extract the file to the temp directory tar = tarfile.open(fileobj=fp) tar.extractall(path=tmpdir) tar.close() fp.close() if commit: self.logger.debug("Installing the tarball") # Remove the previous locale dir if any if os.path.exists(destination): shutil.rmtree(destination) # Put the new locale dir shutil.move(os.path.join(tmpdir, 'locale'), destination) # Remove the temp dir os.removedirs(tmpdir) if commit: self.logger.info("Succeed to install the tarball to: %s", destination) else: self.logger.info("Succeed to download the tarball") return self.project_id, self.project_slug
def test_url_getter_setter(self): """Test url attribute""" base_url = 'http://domain.com' url = Url(base_url) self.assertEqual(url.url, base_url) # Inline function definition instead of using with keyword to support # python 2.6 unittest module def test_set(url): url.url = 'http://newdomain.com' # url attribute should be read-only self.assertRaises(AttributeError, test_set, url)
def test_default_parameters(self, r_request): """Test default parameter behavior""" url = Url('http://domain.com', auth=('user', 'password')) r_request = MagicMock(return_value=None) # Make sure defaults are passed for each request url.get('resource') requests.request.assert_called_with('GET', 'http://domain.com/resource', auth=('user', 'password')) # Make sure single calls can override defaults url.get('resource', auth=('defaults', 'overriden')) requests.request.assert_called_with('GET', 'http://domain.com/resource', auth=('defaults', 'overriden'))
def getLightingTimes(p_zipcode): # Get all holidays for current year from hebcal.com try: api_hebcal = Url('http://www.hebcal.com/') response_hebcal = api_hebcal.get('hebcal', params={ 'v': '1', 'cfg': 'json', 'nx': 'off', 'year': 'now', 'month': 'x', 'ss': 'off', 'mf': 'off', 'c': 'on', 'zip': p_zipcode, 'm': '0', 's': 'off', 'geo': 'zip', 'maj': 'on', 'min': 'off', 'mod': 'off' }) except requests.exceptions.HTTPError as e: raise RemoteFetchError( "Completely failed to get data from Hebcal. Response was %s" % e) return else: obj_holidays = response_hebcal.json() candle_lighting = [] # Find all nights of Chanukah (by searching holiday titles)... # print 'Candle lighting schedule:' for obj_holiday in obj_holidays['items']: if re.match('^Chanukah[a-zA-Z0-9_: ]*Candle[s]?', obj_holiday['title']): # ...and get sunset times for those nights from the hebcal response # Remove time zone info from datetime string. Python doesn't like time zone info. obj_holiday['date'] = obj_holiday['date'][:-6] # Store candle lighting time candle_lighting.append( datetime.strptime(obj_holiday['date'], '%Y-%m-%dT%H:%M:%S')) # TODO: Add a check here to make sure we actually found candle lighting times. return candle_lighting
def connect(self, dry_run=False): """ Connecting to endpoints """ #self.api_base = JsonApi(self.root_url, auth=self.auth_settings) self.api_base = Url(self.root_url, auth=self.auth_settings) self.api_endpoint_eggs = self.api_base.join(self.endpoint_eggs_path) self.api_endpoint_websites = self.api_base.join(self.endpoint_websites_path) self.api_endpoint_environments = self.api_base.join(self.endpoint_environments_path) # Trying to connect to the base to check if the service is reachable if not dry_run: self.logger.info("Connecting to Gestus service on: %s", self.root_url) response = self.api_base.get() if response.status_code != 200: response.raise_for_status() self.map_websites() self._connected = True
def connect(self, dry_run=False): """ Connecting to endpoints """ self.api_base = Url(self.root_url, auth=self.auth_settings) self.api_endpoint_projects = self.api_base.join( self.endpoint_projects_path) self.api_endpoint_projectcurrent = self.api_base.join( self.endpoint_projectcurrent_path) # Trying to connect to the base to check if the service is reachable if not dry_run: self.logger.info("Connecting to PO-Projects service on: %s", self.root_url) response = self.api_base.get() if response.status_code != 200: response.raise_for_status() #self.map_projects() self._connected = True
def do_all(): while True: value = random.randint(0, 30) sensorList.append(float(value)) currentDate = datetime.now() if ((currentDate - lastDate).minute() > 1) and len(sensorList) > 0: lastDate = currentDate somatorio = 0.0 for x in sensorList: somatorio += x media = somatorio / len(sensorList) api = Url('https://api.github.com') response = gists.post(params={'since': '2014-05-01T00:00:00Z'}) print(response.json())
] class YoutubeDataApi(Url): def after_request(self, response): if response.status_code == 401: # Lost authorization, log out logout() if response.status_code != 200: response.raise_for_status() return response.json() _api = YoutubeDataApi('https://www.googleapis.com/youtube/v3/') _oauth_api = Url('https://accounts.google.com/o/oauth2/') _app_name = "yt-downloader-py" def make_filename(filename: str): """Remove any invalid filename characters from `filename`, and replace them with `_` (underscore) WARNING: DO NOT USE ON FULL PATHS""" return ''.join([ c if make_filename.invalid_chars.find(c) < 0 else '_' for c in filename ]) make_filename.invalid_chars = '/\\:*"?|<>'
from nap.url import Url from blinker import signal pr2hub = Url("https://pr2hub.com/") levels = pr2hub.join("levels/") files = pr2hub.join("files/") emblems = pr2hub.join("emblems/") # will fire when get_servers_info is called and there's an hh on_happy_hour = signal('hh') def __error_check(response): """checks if a pr2hub response is an error""" if response.content.startswith(b"error="): raise PR2HubError(str(response.content)[6:]) elif response.content.startswith(b"{\"error\":\""): raise PR2HubError(response.json()["error"]) def get_player_info(player_name: str): """returns a Player class instance""" resp = pr2hub.get("get_player_info_2.php", params={"name": player_name}) __error_check(resp) return Player(resp.json()) def get_guild_info(guild_name: str, get_members: bool): """returns a Guild class instance""" if get_members: get_members = "yes"