def setUp(self): self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.app_id = env('COGNITO_APP_ID') self.username = env('COGNITO_TEST_USERNAME') self.password = env('COGNITO_TEST_PASSWORD') self.user = Cognito(self.cognito_user_pool_id,self.app_id, username=self.username)
def setUp(self): if env('USE_CLIENT_SECRET', 'False') == 'True': self.app_id = env('COGNITO_APP_WITH_SECRET_ID') else: self.app_id = env('COGNITO_APP_ID') self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID', 'us-east-1_123456789') self.username = env('COGNITO_TEST_USERNAME') self.user = Cognito(user_pool_id=self.cognito_user_pool_id, client_id=self.app_id, username=self.username) self.user_metadata = { 'user_status': 'CONFIRMED', 'username': '******', } self.user_info = [{ 'Name': 'name', 'Value': 'Brian Jones' }, { 'Name': 'given_name', 'Value': 'Brian' }, { 'Name': 'birthdate', 'Value': '12/7/1980' }]
def get_db_kwargs(): kwargs = { 'dynamodb': { 'connection': { 'table': 'loadlambddb' }, 'documents': [ 'loadlamb.chalicelib.contrib.db.models.Run', 'loadlamb.chalicelib.contrib.db.models.LoadTestResponse' ], 'table_config': { 'write_capacity': 2, 'read_capacity': 2 } }, } if env('DYNAMODB_ENDPOINT_URL'): kwargs['dynamodb']['config'] = { 'endpoint_url': env('DYNAMODB_ENDPOINT_URL') } kwargs['dynamodb']['table_config'] = { 'write_capacity': 100, 'read_capacity': 100, 'secondary_write_capacity': 100, 'secondary_read_capacity': 100 } return kwargs
def setUp(self): if env("USE_CLIENT_SECRET", "False") == "True": self.app_id = env("COGNITO_APP_WITH_SECRET_ID") else: self.app_id = env("COGNITO_APP_ID") self.cognito_user_pool_id = env("COGNITO_USER_POOL_ID", "us-east-1_123456789") self.username = env("COGNITO_TEST_USERNAME") self.user = Cognito( user_pool_id=self.cognito_user_pool_id, client_id=self.app_id, username=self.username, ) self.user_metadata = { "user_status": "CONFIRMED", "username": "******", } self.user_info = [ { "Name": "name", "Value": "Brian Jones" }, { "Name": "given_name", "Value": "Brian" }, { "Name": "birthdate", "Value": "12/7/1980" }, ]
def setUp(self): if env('USE_CLIENT_SECRET') == 'True': self.app_id = env('COGNITO_APP_WITH_SECRET_ID') else: self.app_id = env('COGNITO_APP_ID') self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.group_data = {'GroupName': 'test_group', 'Precedence': 1} self.cognito_obj = Cognito(self.cognito_user_pool_id, self.app_id)
def setUp(self): self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.app_id = env('COGNITO_APP_ID') self.username = env('COGNITO_TEST_USERNAME') self.password = env('COGNITO_TEST_PASSWORD') self.aws = AWSSRP(username=self.username, password=self.password, pool_id=self.cognito_user_pool_id, client_id=self.app_id)
def test_s3_restore(self): self.doc_class().backup('s3://{}/kev/test-backup.json'.format( env('S3_BUCKET_TEST'))) self.doc_class().flush_db() self.assertEqual(len(list(self.doc_class.all())), 0) self.doc_class().restore('s3://{}/kev/test-backup.json'.format( env('S3_BUCKET_TEST'))) self.assertEqual(len(list(self.doc_class.all())), 3)
def setUp(self): if env('USE_CLIENT_SECRET', 'False') == 'True': self.app_id = env('COGNITO_APP_WITH_SECRET_ID') else: self.app_id = env('COGNITO_APP_ID') self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID', 'us-east-1_123456789') self.group_data = {'GroupName': 'test_group', 'Precedence': 1} self.cognito_obj = Cognito(user_pool_id=self.cognito_user_pool_id, client_id=self.app_id)
def test_s3_backup(self): self.doc_class().backup('s3://{}/kev/test-backup.json'.format( env('S3_BUCKET_TEST'))) dc = self.doc_class() self.assertEqual( 3, len( dc.get_restore_json( *dc.get_path_type('s3://{}/kev/test-backup.json'.format( env('S3_BUCKET_TEST'))))))
def setUp(self): if env("USE_CLIENT_SECRET", "False") == "True": self.app_id = env("COGNITO_APP_WITH_SECRET_ID") else: self.app_id = env("COGNITO_APP_ID") self.cognito_user_pool_id = env("COGNITO_USER_POOL_ID", "us-east-1_123456789") self.group_data = {"GroupName": "test_group", "Precedence": 1} self.cognito_obj = Cognito( user_pool_id=self.cognito_user_pool_id, client_id=self.app_id )
def translate(q, lang_from=LANG_AUTO, lang_to=LANG_ZH, appkey='', appsecret=''): """调用有道智云翻译API Parameters ---------- q : str 请求翻译 query. UTF-8编码 lang_from : str 翻译源语言(default=auto). 可设置为auto,见 `语言列表 <http://ai.youdao.com/docs/doc-trans-api.s>`_ lang_to : str 译文语言(default=zh). **不** 可设置为auto,见 `语言列表 <http://ai.youdao.com/docs/doc-trans-api.s>`_ appkey : str APP ID (默认:环境变量 YOUDAO_FANYI_APP_KEY) appsecret : str APP Secret (默认:环境变量 YOUDAO_FANYI_APP_SECRET) Raises ------ TranslateError 服务器返回的翻译错误。相见有道翻译API错误说明文档 Returns ------- str 翻译结果 """ load_dotenv() if not appkey: appkey = env('YOUDAO_FANYI_APP_KEY').strip() if not appsecret: appsecret = env('YOUDAO_FANYI_APP_SECRET').strip() q = q.strip() salt = '{0}'.format(randint(10000, 99999)) s = '{0}{1}{2}{3}'.format(appkey, q, salt, appsecret) sign = md5(s.encode()).hexdigest().upper() r = requests.get( URL, params={ 'q': q, 'from': lang_from.strip(), 'to': lang_to.strip(), 'appKey': appkey.strip(), 'salt': salt, 'sign': sign, } ) r.raise_for_status() ret_obj = r.json() error_code = int(ret_obj.get('errorCode', 0)) if error_code: raise TranslateError(error_code) return ret_obj['translation'][0]
def test_defaults(self): self.assertEqual(env('HELLO', 5, var_type='integer'), 5) self.assertEqual(env('HELLO', 5.0, var_type='float'), 5.0) self.assertEqual(env('HELLO', [], var_type='list'), []) self.assertEqual(env('HELLO', {}, var_type='dict'), {}) self.assertEqual(env('HELLO', (), var_type='tuple'), ()) self.assertEqual(env('HELLO', 'world'), 'world') self.assertEqual(env('HELLO', False, var_type='boolean'), False) self.assertEqual(env('HELLO', 'False', var_type='boolean'), False) self.assertEqual(env('HELLO', 'true', var_type='boolean'), True) self.assertEqual(env('HELLO', Decimal('3.14'), var_type='decimal'), Decimal('3.14'))
def upload_files(path): session = boto3.Session( aws_access_key_id= env('aws_access_key_id'), #pass this varibale in your .bashrc file. aws_secret_access_key= env('aws_secret_access_key'), #pass this varibale in your .bashrc file. region_name= 'your_region_name' #ex:-ap-south-1 ) s3 = session.resource('s3') bucket = s3.Bucket('your_bucket_name') for subdir, dirs, files in os.walk(path): for file in files: full_path = os.path.join(subdir, file) with open(full_path, 'rb') as data: # rb will empty your s3 bucket folder before upload check aws documentation. bucket.put_object(Key=full_path[len(path)+1:], Body=data)
def echo(update: Update, context: CallbackContext) -> None: """Echo the user message.""" try: POSTGRES_PASSWORD = env('POSTGRES_PASSWORD') dbHost = env('dbHost') except KeyError: print("No env variables set.") sys.exit(1) # Login with redis Cache r = redis.Redis(host=dbHost, port=6379, db=0, password=POSTGRES_PASSWORD) redisReply = ("openTrades: " + r.get("openTrades").decode('utf-8') + "\n" + "simulatedSum: " + r.get("simulatedSum").decode('utf-8') + "\n" + "sumResult: " + r.get("sumResult").decode('utf-8')) update.message.reply_text(redisReply)
def setUp(self): self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.app_id = env('COGNITO_APP_ID') self.username = env('COGNITO_TEST_USERNAME') self.user = Cognito(self.cognito_user_pool_id, self.app_id, self.username) self.user_metadata = { 'user_status': 'CONFIRMED', 'username': '******', } self.user_info = [ {'Name': 'name', 'Value': 'Brian Jones'}, {'Name': 'given_name', 'Value': 'Brian'}, {'Name': 'birthdate', 'Value': '12/7/1980'} ]
class StorageObject(base.BaseStorageBunny): endpoint_url = env('BUNNYCDN_STORAGE_API_ENDPOINT', 'https://storage.bunnycdn.com') Guid = base.SlugProperty(required=True) StorageZoneName = base.CharProperty(required=True) Path = base.CharProperty(required=True) ObjectName = base.CharProperty(required=True) Length = base.IntegerProperty() LastChanged = base.DateTimeProperty() ServerId = base.IntegerProperty() IsDirectory = base.BooleanProperty() UserId = base.SlugProperty(required=True) ContentType = base.CharProperty() DateCreated = base.DateTimeProperty() StorageZoneId = base.IntegerProperty(required=True) Checksum = base.CharProperty() ReplicatedZones = base.ListProperty() def __init__(self, api_key, storage_zone, endpoint_url=None, **kwargs ): self.storage_zone = storage_zone super().__init__(api_key, endpoint_url=endpoint_url, **kwargs) def __str__(self): return f"{self.Path}{self.ObjectName}" def get_region(self): return self.storage_zone.Region.lower() def delete(self): return self.call_storage_api(f"/{self.storage_zone.Name}/{self.Path}/{self.ObjectName}", "DELETE")
class BaseStorageBunny(BaseBunny): storage_endpoint_url = env('BUNNYCDN_STORAGE_API_ENDPOINT', 'storage.bunnycdn.com') def get_storage_header(self): return { 'Content-Type': 'application/json', 'Accept': 'application/json', 'AccessKey': self.api_key } def get_storage_endpoint(self, region): return f"https://{region}.{self.storage_endpoint_url}" def get_region(self): return self.Region.lower() def call_storage_api(self, api_url, api_method, header=None, params={}, data={}, json_data={}, files=None, endpoint_url=None): if not header: header = self.get_storage_header() if not endpoint_url: endpoint_url = self.get_storage_endpoint(self.get_region()) if files: return requests.put(self.get_url(api_url, endpoint_url), headers=header, files=files) return self.call_api(api_url, api_method, header=header, params={}, data=data, json_data=json_data, endpoint_url=endpoint_url)
def __init__(self, secret=None, domain="db.fauna.com", scheme="https", port=None, timeout=60, observer=None, pool_connections=10, pool_maxsize=10, **kwargs): self.secret = secret or env('FAUNA_SECRET') if not self.secret: raise ValueError( 'When creating a FaunaClient instance you must supply the secret argument or set the ' 'FAUNA_SECRET environment variable.') super(FaunaClient, self).__init__(secret, domain=domain, scheme=scheme, port=port, timeout=timeout, observer=observer, pool_connections=pool_connections, pool_maxsize=pool_maxsize, **kwargs)
def main() -> None: """Start the bot.""" # Create the Updater and pass it your bot's token. try: botToken = env('botToken') except KeyError: print("No env variables set.") sys.exit(1) # Login to Bot updater = Updater(botToken) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # on different commands - answer in Telegram dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help_command)) # on non command i.e message - echo the message on Telegram dispatcher.add_handler( MessageHandler(Filters.text & ~Filters.command, echo)) # Start the Bot updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle()
def test_without_defaults_disallow_none(self): with self.assertRaises(EnvsValueException): env('HELLO', allow_none=False) with self.assertRaises(EnvsValueException): env('HELLO', var_type='integer', allow_none=False) with self.assertRaises(EnvsValueException): env('HELLO', var_type='float', allow_none=False) with self.assertRaises(EnvsValueException): env('HELLO', var_type='list', allow_none=False)
class Config(object): """Flask config variables""" DEBUG = env('DEBUG') SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}:{}/{}'.format( env('POSTGRES_USER'), env('POSTGRES_PASSWORD'), env('POSTGRES_HOST'), env('POSTGRES_PORT'), env('POSTGRES_DB')) SQLALCHEMY_TRACK_MODIFICATIONS = ('SQLALCHEMY_TRACK_MODIFICATIONS') SECRET_KEY = env('APP_SECRET_KEY') SESSION_COOKIE_SECURE = env('SESSION_COOKIE_SECURE') SESSION_COOKIE_NAME = env('SESSION_COOKIE_NAME') WTF_CSRF_TIME_LIMIT = env('CSRF_TIME_LIMIT')
def reverse_url_list(name): url_list = filter((lambda x: x.name == name), import_util(env('URL_PATTERNS'))) if len(url_list) == 1: return url_list[0] if len(url_list) == 0: raise ValueError('URL Not Found') if len(url_list) > 1: raise ValueError('Multiple URLs found for name given')
def publish(self, override: bool = False): gql_io = BytesIO(self.render().encode()) mode = 'update' if override: mode = 'override' resp = requests.post('https://graphql.fauna.com/import', params={'mode': mode}, auth=BearerAuth(env('FAUNA_SECRET')), data=gql_io) return resp.content
def download_packages(func, bucket, req_key, *args, **kwargs): LOCAL_ENV = env('LOCAL_ENV', True, var_type='boolean') if LOCAL_ENV != True: tmp_folder = '/tmp/s3reqs/' tmp_file = '/tmp/{}'.format(req_key) file_exists = os.path.isfile(tmp_file) if not file_exists: s3.download_file(bucket, req_key, tmp_file) with zipfile.ZipFile(tmp_file, 'r') as zip_ref: zip_ref.extractall(tmp_folder) sys.path.insert(0, tmp_folder) return func(*args, **kwargs)
def __init__(self): #read env vars try: dbName = env("dbName") dbUser = env("dbUser") POSTGRES_PASSWORD = env("POSTGRES_PASSWORD") dbHost = env("dbHost") dbPort = env("dbPort") self.dbTable = env("dbTable") except KeyError: print("No env variables set.") sys.exit(1) #try connect to database try: # Connect to an existing database self.connection = psycopg2.connect(user=dbUser, password=POSTGRES_PASSWORD, host=dbHost, port=dbPort, database=dbName) #set connection to autocommit self.connection.rollback() self.connection.autocommit = True # Create a cursor to perform database operations self.cur = self.connection.cursor() except (Exception, Error) as error: print("Error while connecting to Postgres", error) sys.exit(1)
def get_keys(self): if self.pool_jwk: return self.pool_jwk # Check for the dictionary in environment variables. pool_jwk_env = env("COGNITO_JWKS", {}, var_type="dict") if pool_jwk_env: self.pool_jwk = pool_jwk_env # If it is not there use the requests library to get it else: self.pool_jwk = requests.get( f"{self.user_pool_url}/.well-known/jwks.json").json() return self.pool_jwk
def get_keys(self): if self.pool_jwk: return self.pool_jwk # Check for the dictionary in environment variables. pool_jwk_env = env("COGNITO_JWKS", {}, var_type="dict") if pool_jwk_env: self.pool_jwk = pool_jwk_env # If it is not there use the requests library to get it else: self.pool_jwk = requests.get( "https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json" .format(self.user_pool_region, self.user_pool_id)).json() return self.pool_jwk
class Settings(object): INSTALLED_APPS = env('INSTALLED_APPS',[],var_type='list') DATABASES = env('DATABASES',{},var_type='dict') DEBUG = env('DEBUG',False,var_type='boolean') AUTH_BACKENDS = env('AUTH_BACKENDS', ['cappy.auth.backends.CognitoUserPoolAuth'],var_type='list') def __init__(self): self.settings_mod = importlib.import_module( env('CAPPY_SETTINGS_MODULE')) self.parse_settings_mod() def list_commands(self): pass def parse_settings_mod(self): for k, v in self.settings_mod.__dict__.items(): if k not in ('__builtins__', '__file__', '__package__', '__name__', '__doc__'): setattr(self,k,v)
def setUp(self): if env('USE_CLIENT_SECRET') == 'True': self.client_secret = env('COGNITO_CLIENT_SECRET') self.app_id = env('COGNITO_APP_WITH_SECRET_ID') else: self.app_id = env('COGNITO_APP_ID') self.client_secret = None self.cognito_user_pool_id = env('COGNITO_USER_POOL_ID') self.username = env('COGNITO_TEST_USERNAME') self.password = env('COGNITO_TEST_PASSWORD') self.wl = WarrantLite(username=self.username, password=self.password, pool_id=self.cognito_user_pool_id, client_id=self.app_id, client_secret=self.client_secret)
def get_keys(self): try: return self.pool_jwk except AttributeError: #Check for the dictionary in environment variables. pool_jwk_env = env('COGNITO_JWKS', {}, var_type='dict') if len(pool_jwk_env.keys()) > 0: self.pool_jwk = pool_jwk_env return self.pool_jwk #If it is not there use the requests library to get it self.pool_jwk = requests.get( 'https://cognito-idp.{}.amazonaws.com/{}/.well-known/jwks.json' .format(self.user_pool_region, self.user_pool_id)).json() return self.pool_jwk
def test_wrong_var_type(self): with self.assertRaises(ValueError) as vm: env('INVALID_INTEGER', var_type='set')
def test_string_valid(self): self.assertEqual('seven', env('VALID_STRING'))
def test_boolean_valid(self): self.assertEqual(True, env('VALID_BOOLEAN', var_type='boolean'))
def test_boolean_valid_false(self): self.assertEqual(False, env('VALID_BOOLEAN_FALSE', var_type='boolean'))
def test_boolean_invalid(self): with self.assertRaises(ValueError) as vm: env('INVALID_BOOLEAN', var_type='boolean')
def test_float_valid(self): self.assertEqual(5.0, env('VALID_FLOAT', var_type='float'))
def test_list_invalid(self): with self.assertRaises(TypeError) as vm: env('INVALID_LIST', var_type='list')
def test_tuple_valid(self): self.assertEqual(('True', 'FALSE'), env('VALID_TUPLE', var_type='tuple'))
def test_tuple_invalid(self): with self.assertRaises(TypeError) as vm: env('INVALID_TUPLE', var_type='tuple')
def test_dict_valid(self): self.assertEqual({'first_name': 'Suge'}, env('VALID_DICT', var_type='dict'))
def test_dict_invalid(self): with self.assertRaises(SyntaxError) as vm: env('INVALID_DICT', var_type='dict')
def test_integer_invalid(self): with self.assertRaises(TypeError) as vm: env('INVALID_INTEGER', var_type='integer')
def test_decimal_valid(self): self.assertEqual(Decimal('2.39'), env('VALID_DECIMAL', var_type='decimal'))
def test_integer_valid(self): self.assertEqual(1, env('VALID_INTEGER', var_type='integer'))
def test_list_valid(self): self.assertEqual(['1', '2', '3'], env('VALID_LIST', var_type='list'))
def test_decimal_invalid(self): with self.assertRaises(ArithmeticError) as vm: env('INVALID_DECIMAL', var_type='decimal')
def test_float_invalid(self): with self.assertRaises(TypeError) as vm: env('INVALID_FLOAT', var_type='float')