Exemplo n.º 1
0
def test_dotenv_nonempty_selfreferential_interpolation():
    stream = StringIO(u'some_path="${some_path}:a/b/c"\n')
    stream.seek(0)
    assert u'some_path' not in os.environ
    with restore_os_environ():
        os.environ[u'some_path'] = u'x/y/z'
        parsed_dict = dotenv_values(stream=stream)
    assert {u'some_path': u'x/y/z:a/b/c'} == parsed_dict
Exemplo n.º 2
0
from time import sleep
from typing import Dict, Generator, List
import luigi
from luigi.contrib.mongodb import MongoTarget
from pymongo import MongoClient
import pandas as pd
from dotenv import dotenv_values
import os
import json
import hashlib
import sys
from app.utils.factorutils import op, intersectCode

config = dotenv_values('.env')


class MongoCollectionTarget(MongoTarget):
    """ Target for existing collection """
    def __init__(self, mongo_client: MongoClient, index: str,
                 collection: str) -> None:
        super(MongoCollectionTarget, self).__init__(mongo_client, index,
                                                    collection)

    def exists(self) -> bool:
        """
        Test if target has been run
        Target is considered run if the targeted collection exists in the database
        """
        return self.read()

    def read(self) -> bool:
Exemplo n.º 3
0
import requests
from bs4 import BeautifulSoup
import logging
import dotenv
import datetime
import json
import time

logging.basicConfig(filename='Zalandolog.log',
                    filemode='a',
                    format='%(asctime)s - %(name)s - %(message)s',
                    level=logging.DEBUG)
CONFIG = dotenv.dotenv_values(dotenv_path='.env')


class ZalandoMonitor:
    def __init__(self, webhook, proxy):
        self.webhook = webhook
        if proxy is None:
            self.proxy = {}
        else:
            self.proxy = {'https': f'https://{proxy}'}
        self.headers = {
            'user-agent':
            'ozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 ('
            'KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,'
            'image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'accept-language':
            'en-GB,en-US;q=0.9,en;q=0.8'
Exemplo n.º 4
0
import json
from bs4 import BeautifulSoup
import urllib3
import time
import logging
import dotenv
from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, HardwareType
from fp.fp import FreeProxy

logging.basicConfig(filename='Footlockerlog.log', filemode='a', format='%(asctime)s - %(name)s - %(message)s', level=logging.DEBUG)

software_names = [SoftwareName.CHROME.value]
hardware_type = [HardwareType.MOBILE__PHONE]
user_agent_rotator = UserAgent(software_names=software_names, hardware_type=hardware_type)
CONFIG = dotenv.dotenv_values()

proxyObject = FreeProxy(country_id=['CA'], rand=True)

INSTOCK = []


def discord_webhook(product_item):
    """
    Sends a Discord webhook notification to the specified webhook URL
    :param product_item: An array of the product's details
    :return: None
    """
    data = {}
    data["username"] = CONFIG['USERNAME']
    data["avatar_url"] = CONFIG['AVATAR_URL']
Exemplo n.º 5
0
from dotenv import dotenv_values
import logging

from devman_bot import bot_start

if __name__ == '__main__':
    dotenv_dict = dotenv_values()

    token_telegram_bot = dotenv_dict['token_telegram_bot']
    chat_id_telegram = dotenv_dict['chat_id_telegram']
    token_devman = dotenv_dict['token_devman']

    logger = logging.getLogger('Bot-logger')
    logger.setLevel(logging.INFO)

    bot_start(token_telegram_bot, chat_id_telegram, token_devman, logger)
Exemplo n.º 6
0
 def __init__(self):
     self.config = dotenv_values(".env")
     self.xml_path = self.config["XML_PATH"]
     self.tree = etree.parse(self.xml_path)
     self.forms = self.build_forms()
Exemplo n.º 7
0
# std:
import os
import sys

# pip-ext:
import waitress
import dotenv

# pip-int:
# n/a

# loc:
# DELAYED

assert len(sys.argv) == 2
envFilename = sys.argv[1]
for (key, value) in dotenv.dotenv_values(envFilename).items():
    if key not in os.environ:
        os.environ[key] = value

# loc:
from constants import K
import utils
from mongo import db
import userMod

# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Exemplo n.º 8
0
import tweepy
from tqdm import tqdm

# dataset can be downloaded from https://data.mendeley.com/datasets/rxwfb3tysd/2
# download the subtask1.zip file to get the correct files.

# todo: create .env file with your credentials with format
# consumer_key=XXXX
# consumer_key_secret=XXXX
# access_token=XXXX
# access_token_secret=XXXX

# or just copy paste them into the variables

# Get credentials from .env file
env = dotenv.dotenv_values(os.path.join('..', '.env'))

consumer_key = env.get('consumer_key')
consumer_key_secret = env.get('consumer_key_secret')
access_token = env.get('access_token')
access_token_secret = env.get('access_token_secret')

# initialize Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)


def create_data_file(input_filepath, output_filepath):
    input_file = open(input_filepath, encoding='utf8')
    output_file = open(output_filepath, 'a', encoding='utf8')
Exemplo n.º 9
0
 def current_dotenv_values(self):
     "Values currently stored in the dotenv as a dict"
     return dotenv.dotenv_values(self.dotenv)
Exemplo n.º 10
0
import random

import dotenv
import aiogram
import tinydb
from aiogram import types
from aiogram.utils import executor
from loguru import logger
from tinydb import Query
from tinydb.operations import set as set_
import parse

env = dotenv.dotenv_values()

db = tinydb.TinyDB("botdb.json")

bot = aiogram.Bot(env["BOT_TOKEN"], proxy=env["PROXY"])
dp = aiogram.Dispatcher(bot)

HELP_TEXT = """Мои комманды:

`/add <имя>` - добавляет ученика в список
`/list` - показывает список учеников
`/edit "<старое_имя>" "<новое_имя>"` - изменяет имя ученика
`/delete <имя>` - удаляет ученика из списка
`/choose` - выдает случайный список учеников
"""


@dp.message_handler(commands=["help", "start"])
async def help_(message: types.Message):
Exemplo n.º 11
0
"""
Given the CouchDB Docker container, still some settings need to be made manually
after starting the Docker container. This helps to reduce the amount of logged
messages of the CouchDB Docker container.
"""

import warnings
import requests
import dotenv

warnings.filterwarnings('once', message='Unverified HTTPS request')

config = dotenv.dotenv_values("couchdb_credentials.env")
username = config["COUCHDB_USER"]
password = config["COUCHDB_PASSWORD"]
server_url = config["COUCHDB_URL"]  # Assume Docker host to be localhost

# Create CouchDB system database '_users'
# See https://github.com/apache/couchdb-docker#no-system-databases-until-the-installation-is-finalized
# for details.
response = requests.put(f"https://{server_url}/_users",
                        auth=requests.auth.HTTPBasicAuth(username, password),
                        verify=False)
assert response.status_code in (201, 202), \
    f"Creation of database '_users' failed with status code {response.status_code}, maybe it already exists?"
Exemplo n.º 12
0
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from io import StringIO
from dotenv import dotenv_values
filelike = StringIO('SPAM=EGGS\n')
filelike.seek(0)
parsed = dotenv_values(stream=filelike)


def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookmarks.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?") from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
Exemplo n.º 13
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import dotenv

TELEGRAM_TOKEN="TELEGRAM_TOKEN"
TELEGRAM_CONTROL_GROUP_ID="TELEGRAM_CONTROL_GROUP_ID"

STORAGE_DIR="STORAGE_DIR"

MQTT_HOST="MQTT_HOST"
MQTT_PORT="MQTT_PORT"
MQTT_TOPIC_CONTROL="MQTT_TOPIC_CONTROL"
MQTT_TOPIC_REQUEST="MQTT_TOPIC_REQUEST"
MQTT_TOPIC_RESPONSE="MQTT_TOPIC_RESPONSE"

ACCUWEATHER_API_KEY='ACCUWEATHER_API_KEY'
ACCUWEATHER_LOCATION_KEY='ACCUWEATHER_LOCATION_KEY'


scriptDir = sys.path[0] #os.path.dirname(os.path.realpath(__file__))
envPath = scriptDir + '/../.env'
env = dotenv.dotenv_values(dotenv_path=envPath)

outputDir = env[STORAGE_DIR]
outputDir = outputDir if outputDir.startswith('/') else (scriptDir + '/' + outputDir)
fontsDir = scriptDir + '/../resources/fonts/'
iconsDir = scriptDir + '/../resources/icons/'
Exemplo n.º 14
0
    def get_variables_from_dotenv_file(self):

        DJANGO_ENVIRONMENT = os.getenv(self.django_environment_var_name) \
            if os.getenv(self.django_environment_var_name) is not None else ''
        env_path = Path('EnvVars/%s.env' % (DJANGO_ENVIRONMENT))
        return dotenv_values(dotenv_path=env_path, verbose=True)
Exemplo n.º 15
0
import time
from datetime import datetime
from dotenv import dotenv_values
from sqlalchemy import create_engine, text, MetaData, Table, ForeignKey, func, or_, and_
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker, relationship
import pandas as pd
from tabulate import tabulate

# docs
# https://docs.sqlalchemy.org/en/14/orm/tutorial.html#querying

# Performance: https://docs.sqlalchemy.org/en/14/faq/performance.html

try:
    ENV_CONFIG = dotenv_values(
        ".env")  # config = {"USER": "******", "EMAIL": "*****@*****.**"}
except ImportError as e:
    raise ImportError(
        'python-dotenv is not installed, run `pip install python-dotenv`')


def output_table(titles=[], rows=[]):
    """
    output_tables(['names', 'weights', 'costs', 'unit_costs'], [[xx, xx], [xx, xx]])
    """
    data = [titles] + list(zip(*rows))

    for i, d in enumerate(data):
        line = '|'.join(str(x).ljust(12) for x in d)
        print(line)
        if i == 0:
Exemplo n.º 16
0
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from json import loads
from api.models import Text, Sentiment, Entity
import requests
from dotenv import dotenv_values

# Configuration variables to make request to text API
URL = 'https://aylien-text.p.rapidapi.com/'
ENV = dotenv_values('.env')
HEADERS = {
    'x-rapidapi-key': ENV.get('RAPID_API_KEY'),
    'x-rapidapi-host': "aylien-text.p.rapidapi.com"
}


def json_body(body=b''):
    '''This method parses the body content to json content like'''
    try:
        body = body.decode('utf-8')
        json_body = loads(body)
    except Exception as err:
        return {
            'err': err
        }
    return json_body


@csrf_exempt
Exemplo n.º 17
0
def test_dotenv_empty_selfreferential_interpolation():
    stream = StringIO(u'some_path="${some_path}:a/b/c"\n')
    stream.seek(0)
    assert u'some_path' not in os.environ
    parsed_dict = dotenv_values(stream=stream)
    assert {u'some_path': u':a/b/c'} == parsed_dict
Exemplo n.º 18
0
 def __init__(self):
     self.SECRETS = dict(dotenv_values())
Exemplo n.º 19
0
 def __init__(self):
     for k, v in dotenv_values(".settings").items():
         setattr(self, k, v)
Exemplo n.º 20
0
from urllib.request import urlopen
import json
import cloudinary.api
import cloudinary.uploader
import time
import traceback
from dotenv import dotenv_values

config = dotenv_values(".env.local")

IG_ACCESS_TOKEN = config['IG_ACCESS_TOKEN']
IG_USER_ID = config['IG_USER_ID']

CLOUDINARY_CLOUD_NAME = config['CLOUDINARY_CLOUD_NAME']
CLOUDINARY_API_KEY = config['CLOUDINARY_API_KEY']
CLOUDINARY_API_SECRET = config['CLOUDINARY_API_SECRET']

try:
  cloudinary.config(
      cloud_name=CLOUDINARY_CLOUD_NAME,
      api_key=CLOUDINARY_API_KEY,
      api_secret=CLOUDINARY_API_SECRET
  )

  print('cloudinary configured..')

  result = cloudinary.Search()\
      .expression('folder:instagram/*')\
      .with_field('context')\
      .execute()
Exemplo n.º 21
0
from dotenv import load_dotenv, dotenv_values
import jesse.helpers as jh
import os
import sys

# fix directory issue
sys.path.insert(0, os.getcwd())

ENV_VALUES = {}

if jh.is_jesse_project():
    # load env
    load_dotenv()

    # create and expose ENV_VALUES
    ENV_VALUES = dotenv_values('.env')

    if jh.is_unit_testing():
        ENV_VALUES['POSTGRES_HOST'] = '127.0.0.1'
        ENV_VALUES['POSTGRES_NAME'] = 'jesse_db'
        ENV_VALUES['POSTGRES_PORT'] = '5432'
        ENV_VALUES['POSTGRES_USERNAME'] = '******'
        ENV_VALUES['POSTGRES_PASSWORD'] = '******'
        ENV_VALUES['REDIS_HOST'] = 'localhost'
        ENV_VALUES['REDIS_PORT'] = '6379'
        ENV_VALUES['REDIS_DB'] = 0
        ENV_VALUES['REDIS_PASSWORD'] = ''

    # validation for existence of .env file
    if len(list(ENV_VALUES.keys())) == 0:
        jh.error(
Exemplo n.º 22
0
        '-o',
        '--override',
        help=
        'Pin files from scratch, do not ignore files that have already been pinned',
        default=False,
        required=False,
        action='store_true')
    parser.add_argument('-r',
                        '--reverse',
                        help='Pin files in verse',
                        default=False,
                        required=False,
                        action='store_true')
    args = vars(parser.parse_args())

    credentials = dotenv_values(args['env'])

    logger.info(f'Loading .env file from {args["env"]}')

    results_fp = f'{args["input"]}/results.json'

    files_to_upload = sorted(get_files(args['input']), reverse=args['reverse'])

    if os.path.exists(results_fp) and not args['override']:
        with open(results_fp, 'r') as f:
            info = json.load(f)
            f.close()
    else:
        info = {}

    for idx, fp in enumerate(files_to_upload):
from collections import defaultdict
import numpy as np
from datetime import datetime
import SteamMarket
from time import sleep
from dotenv import dotenv_values

# COOKIE = {"steamLoginSecure": environ["STEAM_LOGIN_SECURE"]}
GAME_ID_1 = dotenv_values('.env')['GAME_ID_1']
SteamMarket.set_cookies(dotenv_values('.env')["STEAM_LOGIN_SECURE"])
SteamMarket.iniate_cookies()

all_items_names = [
    "Sticker | FaZe Clan | Berlin 2019",
    "Sticker | CR4ZY | Berlin 2019",
    "Sticker | mousesports (Holo) | Berlin 2019",
    "Sticker | FaZe Clan (Holo) | Berlin 2019",
    "Sticker | Natus Vincere (Holo) | Berlin 2019",
    "Sticker | compLexity Gaming | Berlin 2019",
    "Sticker | mousesports (Foil) | Berlin 2019",
    "Sticker | Team Liquid (Holo) | Berlin 2019",
    "Sticker | Natus Vincere | Berlin 2019",
    "Sticker | Team Liquid | Berlin 2019",
    "Sticker | FaZe Clan (Foil) | Berlin 2019",
    "Lt. Commander Ricksaw | NSWC SEAL",
    "Sticker | ropz (Foil) | London 2018",
    "Operation Phoenix Weapon Case",
    "Shattered Web Case",
    "Galil AR | Akoben (Field-Tested)",
    "SSG 08 | Bloodshot (Field-Tested)",
    "SG 553 | Colony IV (Field-Tested)",
Exemplo n.º 24
0
import os
import sys
from pathlib import Path

from dotenv import dotenv_values

from client_config import get_client

# Load environment variables from .env file
env_path = Path(os.path.dirname(__file__)).absolute() / '.env'
if not env_path.exists():
    print("Could not find '.env' file. Verify if you have in your directory.")
    exit()

# Constants
ENV = dotenv_values(dotenv_path=env_path)
PWD = Path(os.path.dirname(__file__))

# --------Configuration--------
config = {
    "cogs_path": PWD.joinpath('packages', 'cogs'),
    "cogs_module_name": 'packages.cogs'
}

client = get_client(config)

# The token is necessary to connect the client with the API
# on discord and use the bot.
client.run(ENV['BOT_TOKEN'])
Exemplo n.º 25
0
import mysql.connector
from dotenv import dotenv_values, find_dotenv

env_values = dotenv_values(find_dotenv())

mydb = mysql.connector.connect(host=env_values.get('SQL_HOST'),
                               user=env_values.get('SQL_USER'),
                               password=env_values.get('SQL_PASSWORD'),
                               database=env_values.get('SQL_DB'))


def findMovieFile(id):
    mycursor = mydb.cursor()
    mycursor.execute(f"SELECT file_path FROM Movies where movie_id={id}")
    movies = mycursor.fetchall()
    if (len(movies) == 0):
        raise Exception('Invalid id provided')
    else:
        return movies[0]
Exemplo n.º 26
0
from biosimulators_utils.sedml.data_model import Report, Plot2D, Plot3D
from biosimulators_utils.sedml.exec import get_report_for_plot2d, get_report_for_plot3d
from biosimulators_utils.sedml.io import SedmlSimulationReader
from biosimulators_utils.viz.data_model import VizFormat
from dotenv import dotenv_values
from unittest import mock
import connexion
import flask
import os.path
import requests
import requests.exceptions
import werkzeug.wrappers.response  # noqa: F401
import zipfile

config = {
    **dotenv_values("secret/secret.env"),
    **dotenv_values("config/config.env"),
    **dotenv_values("shared/shared.env"),
}

TIMEOUT = float(config.get('RUN_COMBINE_ARCHIVE_TIMEOUT', 30.))

IGNORED_ENV_VARS = [
    'H5_REPORTS_PATH',
    'REPORTS_PATH',
    'PLOTS_PATH',
    'BUNDLE_OUTPUTS',
    'KEEP_INDIVIDUAL_OUTPUTS',
    'LOG_PATH',
]
Exemplo n.º 27
0
from faunadb import query as q
from faunadb.objects import Ref
from faunadb.client import FaunaClient
from dotenv import dotenv_values
from munch import AutoMunch
from pprint import pprint

cfg = AutoMunch(dotenv_values())

# pprint(cfg)
# exit()

fdb = FaunaClient(secret=cfg.FAUNASECRET)

if __name__ == "__main__":
    indexes = fdb.query(q.paginate(q.collections()))
    pprint(indexes)
Exemplo n.º 28
0
         "tests/test-files/decoded_test_b.PNG"),
    ],
)
def test_base64_to_file(base64_path, save_path):
    assert (base64_to_content(
        base64_path, is_path=True,
        save_path=save_path) == "Successfully saved to `%s`" % save_path)


"""
UTILS TESTS
"""
from misty2py.utils.utils import *
from dotenv import dotenv_values

values = dotenv_values(".env")


@pytest.mark.parametrize(
    "in_val, query_str, fallback, query_type, out_val",
    [
        ({
            "test": "testing"
        }, "test", 0, str, "testing"),
        ({
            "test": "testing"
        }, "test", 0, int, 0),
        ({
            "tost": "testing"
        }, "test", 0, int, 0),
    ],
Exemplo n.º 29
0
import numpy as np
import matplotlib.pyplot as plt
import sys

import jsonpickle.ext.numpy as jsonpickle_numpy
jsonpickle_numpy.register_handlers()
import jsonpickle

from qctrlvisualizer import get_qctrl_style, plot_controls
from qctrl import Qctrl

#configure environment
from dotenv import dotenv_values
config = dotenv_values(".env")
import real_q

#open file and decode it
if (len(sys.argv) < 2):
    print("Enter a json pickle path as first arg!")
    exit(0)

path = sys.argv[1]
print(path)
circuit = "H"
if ("not" in path):
    circuit = "NOT"

json_encode = None
with open(path, 'r') as file:
    json_encode = file.read()
Exemplo n.º 30
0
 def load_env_files() -> Generator[Dict[str, str], None, None]:
     for env_file in env_files():
         d = dotenv_values(env_file, interpolate=False)
         yield {k: v for k, v in d.items() if v is not None}
Exemplo n.º 31
0
Import("env")
import sys

env.Execute("$PYTHONEXE -m pip install python-dotenv")

from dotenv import dotenv_values

config = {
    **dotenv_values(".env"),
    **dotenv_values(".env." + env["PIOENV"]),
}

env.Append(CPPDEFINES=config.items())
env.Append(OTA_PASSWORD=config["DEVICE_SECRET"])
Exemplo n.º 32
0
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
from dotenv import dotenv_values
from os import path as os_path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

dot_env_variables = dotenv_values()

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = dot_env_variables['DJANGO_SECRET_KEY']

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True if dot_env_variables['APP_ENV'] == 'development' else False

ALLOWED_HOSTS = dot_env_variables['ALLOWED_HOSTS'].split(
    ',') if 'ALLOWED_HOSTS' in dot_env_variables else ['*']

# Application definition
Exemplo n.º 33
0
                        'debug', 'trace'
                    ],
                    default='info')
args = parser.parse_args()

BASE_PATH = args.kvm_path

logger.remove()
logger.add(sys.stdout, level=args.log_level.upper())


def get_path(file_path: str) -> PurePath:
    return PurePath(BASE_PATH).joinpath(file_path)


default_config = dotenv_values(str(get_path('.env')))
customized_config = {'DB_NAME': 'kartevonmorgen.sqlite'}
if Path(get_path('.env.production')).exists():
    customized_config = dotenv_values(str(get_path('.env.production')))

if args.dev:
    customized_config = dotenv_values(str(get_path('.env.development')))

config = {**default_config, **customized_config, **os.environ}

# log configurations
logger.debug(f'base path: {BASE_PATH}')
logger.debug(f'default config: {default_config}')
logger.debug(f'customized config: {customized_config}')

DB_PATH = get_path(str(PurePath('db').joinpath(config['DB_NAME'])))
Exemplo n.º 34
0
def test_dotenv_values_stream():
    stream = StringIO(u'hello="it works!😃"\nDOTENV=${hello}\n')
    stream.seek(0)
    parsed_dict = dotenv_values(stream=stream)
    assert 'DOTENV' in parsed_dict
    assert parsed_dict['DOTENV'] == u'it works!😃'