def __init__(self): self.host = "http://www.tvantagens.com.br/" self.login_url = self.host + "autenticar-participante.action" self.promotions_url = config('PROMOTIONS_URL') self.cpf = config('LOGIN') self.password = config('PASSWORD') self.session = requests.Session() self.tickets = []
def save(item): if isinstance(item, dict) and item.get('alias'): dynamodb = boto3.resource('dynamodb', aws_access_key_id=config('aws_access_key_id'), aws_secret_access_key=config('aws_secret_access_key'), region_name=config('region')) table = dynamodb.Table('diegor_me') table.put_item(Item=item) return True
def __init__(self, address): self.client = client.SSHClient() self.client.set_missing_host_key_policy(client.AutoAddPolicy()) self.client.connect( address, username=config('SSHUSER'), password=config('SSHPASSWORD'), look_for_keys=False )
def handle(self, *args, **kwargs): app = SocialApp.objects.create( provider='google', name='GAC', client_id=config('GOOGLE_CLIENT_ID'), secret=config('GOOGLE_CLIENT_SECRET')) app.sites.add(Site.objects.first()) app.save()
def handle(self, **kwargs): u = User.objects.create_superuser( username=config('USER'), email=config('EMAIL'), password=config('PASSWORD', default=1, cast=int), full_name=config('USER')) u.save() print 'SUPERUSER CREATED!'
def __init__(self, db="coopy/"): self.host = "http://www.tvantagens.com.br/" self.login_url = self.host + "autenticar-participante.action" self.promotions_url = config("PROMOTIONS_URL") self.cpf = config("LOGIN") self.password = config("PASSWORD") self.session = requests.Session() self.tickets = [] self.db = db
def _get_client(): global _client try: _client.ping() except (AttributeError, ConnectionError): _client = MPDClient() mpd_host = config('MPD_HOST', default='localhost') mpd_port = config('MPD_PORT', default=6600) _client.connect(mpd_host, mpd_port) function(_client)
def __init__(self): """ Bridge backups to local file system or to FTP server according to env vars set to allow FTP usage (see connect method). """ self.ftp = self.ftp_connect() self.dir = decouple.config('ALCHEMYDUMPS_DIR', default=self.DIR) self.prefix = decouple.config('ALCHEMYDUMPS_PREFIX', default=self.PRE) self.files = None self.target = self.get_target()
def analyze(bot, update): tone_analyzer = ToneAnalyzerV3Beta( username=config('USERNAME'), password=config('PASSWORD'), version='2016-05-19', url='https://gateway.watsonplatform.net/tone-analyzer/api' ) response = tone_analyzer.tone(text=update.message.text) text = create_emotion_text(response) bot.sendMessage(update.message.chat_id, text=text)
def deploy(): AWS_BUCKET_NAME = config('AWS_BUCKET_NAME') AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') local("s3cmd sync {}/ s3://{} --acl-public --delete-removed " "--guess-mime-type --access_key={} --secret_key={}".format( FOLDER, AWS_BUCKET_NAME, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY ) )
def __init__(self): """ Init Google reporting object """ self.year = config('REPO_YEAR', cast=int, default=2017) self.month = config('REPO_MONTH', cast=int, default=4) self.sheet = config('GOOGLE_SHEET') self.report = ReportTemplate() self.builder = ReportBuilder() self.report.template = TEMPLATE self.builder.template = self.report logger.info("Init Google spreadsheet export month: {}={}".format(self.year, self.month))
def get_url_from_alias(alias=''): if alias == '': alias = '/' dynamodb = boto3.resource('dynamodb', aws_access_key_id=config('aws_access_key_id'), aws_secret_access_key=config('aws_secret_access_key'), region_name=config('region')) table = dynamodb.Table('diegor_me') search = {'alias': alias} response = table.get_item(Key=search) item = response.get('Item') if item: return item.get('url')
def send_notification(state): device_tokens = DeviceToken.objects.values_list('token', flat=True) payload = get_payload(state) apns = APNs(cert_file=config('CERT_PEM'), key_file=config('KEY_PEM'), enhanced=True) frame = Frame() for index, token in enumerate(device_tokens): identifier = index + 1 expiry = time.time() + 3600 priority = 10 frame.add_item(token, payload, identifier, expiry, priority) apns.gateway_server.send_notification_multiple(frame)
def update_bug_db(bugs, cf_fields): metadata = MetaData() db = { 'USER': config('DATABASE_USER'), 'PASSWORD': config('DATABASE_PASSWORD', default=''), 'HOST': config('DATABASE_HOST'), 'PORT': config('DATABASE_PORT', default='5432'), 'NAME': config('DATABASE_NAME', default='bugzilla') } bug_table = Table('bug', metadata, Column('id', Integer, primary_key=True), Column('version', String), Column('target_milestone', String), Column('status', String), Column('severity', String), Column('resolution', String), Column('dupe_of', Integer, nullable=True), Column('product', String), Column('platform', String), Column('op_sys', String), Column('keywords', String), Column('is_confirmed', Boolean), Column('creator', String), Column('creation_time', DateTime), Column('whiteboard', String), Column('release_channel', String), Column('release_cycle', String) ) for f in cf_fields: bug_table.append_column(Column(f, String)) engine = create_engine( 'postgresql://%(USER)s:%(PASSWORD)s@%(HOST)s:%(PORT)s/%(NAME)s' % db) if bug_table.exists(engine): bug_table.drop(engine) bug_table.create(engine) conn = engine.connect() conn.execute(bug_table.insert(), bugs) # Add bug_order table conn.execute('DROP TABLE bug_order') conn.execute(''' CREATE TABLE bug_order AS SELECT id, rank() OVER (PARTITION BY creator ORDER BY creation_time ASC) FROM bug''')
def init_db_config(self, config): try: self.db_ip = config('DB_HOST') self.conn = psycopg2.connect( "dbname='{0}'" " user='******' host='{2}' password={3}".format( config('DB_NAME'), config('DB_USER'), self.db_ip, config('DB_PASSWORD') ) ) print ("Conectado no Banco com sucesso!") except: print ("Erro ao conectar a base de dados")
def translate(section, key): try: file_ini = ConfigParser.ConfigParser() file_ini.read( abspath(join(dirname(__file__), '../../../translation/'+config('TRANSLATION',default='default')+'.ini')) ) return file_ini.get(section,key) except: return ''
def __init__(self, app, db=False): """Set the app and the db, init the app, and seed the db""" # some useful vars self.basedir = app.config['BASEDIR'] self.testdir = app.config['BASEDIR'].child('findaconf', 'tests') # default oauth (as in findaconf/forms.py) oauth = {'Google Plus': {'class_': Google, 'consumer_key': True, 'consumer_secret': True}} # config test app app.config['ASSETS_DEBUG'] = False app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['ADMIN'] = ['*****@*****.**', '*****@*****.**', '*****@*****.**'] app.config['OAUTH_CREDENTIALS'] = oauth # config and create db self.db = db if self.db: default = 'sqlite:///{}'.format(self.testdir.child('tests.db')) uri = config('DATABASE_URL_TEST', default=default) app.config['SQLALCHEMY_DATABASE_URI'] = uri self.clear_db() self.db.create_all() # create test app and seed db self.app = app.test_client() self.seed_db()
def new_usuario(self, data): """ Método que cria um usuário com os dados informados. """ data['criado_em'] = r.expr(datetime.now( r.make_timezone(config('TIMEZONE', default='-03:00')))) return self.insert(data)
def set_app(self, app, db=False): # basic testing vars app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False # set db for tests if db: app.config['SQLALCHEMY_DATABASE_URI'] = config( 'DATABASE_URL_TEST', default='sqlite:///' + mkstemp()[1] ) # create test app test_app = app.test_client() # create tables and testing db data if db: db.create_all() db.session.add(self.whisky_1) db.session.add(self.whisky_2) db.session.commit() query_1 = Whisky.query.filter(Whisky.slug == 'isleofarran') query_2 = Whisky.query.filter(Whisky.slug == 'glendeveronmacduff') calc_correlation_1 = self.whisky_1.get_correlation(query_2.first()) calc_correlation_2 = self.whisky_2.get_correlation(query_1.first()) correlation_1 = Correlation(**calc_correlation_1) correlation_2 = Correlation(**calc_correlation_2) db.session.add(correlation_1) db.session.add(correlation_2) db.session.commit() # return the text app return test_app
def init_logging(): log_level = logging.DEBUG if config('DEBUG', cast=bool) else logging.INFO logging.basicConfig(level=log_level, format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", datefmt="%H:%M:%S") if log_level == logging.DEBUG: logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
def gen_pw(password, salt=None): """ Função responsável por gerar uma senha nova senha. Geralmente utilizado na etapa de cadastro. """ return (bcrypt.hashpw(password.encode('utf-8'), salt if salt else bcrypt.gensalt(config('HASH_COMPLEXITY', default=10, cast=int))))
def run(): client = Vivo() client._get_ticket_info() availables = client._save_tickets() if len(availables) > 0: KEY = config('MANDRILL_KEY') template = env.get_template('mail.txt') html_template = env.get_template('mail.html') text = template.render(tickets=availables) html = html_template.render(tickets=availables) mandrill_client = mandrill.Mandrill(KEY) message = { 'from_email': '*****@*****.**', 'from_name': 'Vivo Scrapper', 'subject': 'Tem evento novo!!!!', 'html': html, 'text': text, 'to': [ { 'email': '*****@*****.**', 'type': 'to', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, { 'email': '*****@*****.**', 'type': 'bcc', }, ], } mandrill_client.messages.send(message=message)
def get_daily_data(request): town = [-1.3,36.82] api_key=config('WEATHER_API_KEY') fio = ForecastIO.ForecastIO(api_key, latitude=town[0], longitude=town[1]) current = FIOCurrently.FIOCurrently(fio) data = {'humidity': current.humidity,'temperature': current.temperature, 'pressure':current.pressure,'cloudCover':current.cloudCover,'windSpeed':current.windSpeed} return Response(data)
def setUpClass(cls): super(SeleniumTests, cls).setUpClass() cls.firefox_profile = FirefoxProfile() server_url = config('TEST_PUSH_SERVER_URL', default=False) if server_url: cls.firefox_profile.set_preference('dom.push.serverURL', server_url) cls.selenium = WebDriver(firefox_profile=cls.firefox_profile)
def setup_logging(): """ Setups basic logging logic and format. Special case for sqlalchemy. :return: """ log_level = logging.DEBUG if config('DEBUG', cast=bool) else logging.INFO logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s", datefmt="%H:%M:%S") if log_level == logging.DEBUG: logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
def new_marcador(self, **kwargs): """ Método que adiciona um novo marcador para o usuário fornecido através do ID. """ data = { 'usuario_id': kwargs.pop('usuario_id', None), 'criado_em': r.expr(datetime.now(r.make_timezone( config('TIMEZONE', default='-03:00')))) } data.update(kwargs) return self.insert(data)
def nydus_config(from_env_var): """ Generate a Nydus Redis configuration from an ENV variable of the form "server:port,server:port..." Default to REDIS_HOST:REDIS_PORT if the ENV variable is not provided. """ redis_servers_cast = lambda x: list(r.split(":") for r in x.split(",")) servers = config(from_env_var, default="{0}:{1}".format(REDIS_HOST, REDIS_PORT), cast=redis_servers_cast) _redis_hosts = {} for r_index, r_host_pair in enumerate(servers): _redis_hosts[r_index] = {"host": r_host_pair[0], "port": int(r_host_pair[1])} return {"hosts": _redis_hosts}
def ftp_connect(self): """ Tries to connect to FTP server according to env vars: * `ALCHEMYDUMPS_FTP_SERVER` * `ALCHEMYDUMPS_FTP_USER` * `ALCHEMYDUMPS_FTP_PASSWORD` * `ALCHEMYDUMPS_FTP_PATH` :return: Python FTP class instance or False """ server = decouple.config('ALCHEMYDUMPS_FTP_SERVER', default=None) user = decouple.config('ALCHEMYDUMPS_FTP_USER', default=None) password = decouple.config('ALCHEMYDUMPS_FTP_PASSWORD', default=None) path = decouple.config('ALCHEMYDUMPS_FTP_PATH', default=None) if server and user: try: ftp = ftplib.FTP(server, user, password) return self.ftp_change_path(ftp, path) except ftplib.error_perm: print("==> Couldn't connect to " + server) return False return ftp return False
def _lazy_haystack_setup(): from django.conf import settings es_url = settings.ES_URLS[0] if settings.AWS_ES_SIGN_REQUESTS: from aws_requests_auth import boto_utils from aws_requests_auth.aws_auth import AWSRequestsAuth from elasticsearch import RequestsHttpConnection auth = AWSRequestsAuth( aws_region=config('AWS_ES_REGION', default=''), aws_service='es', **boto_utils.get_credentials() ) haystack_connections = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': es_url, 'INDEX_NAME': config('ES_INDEX_URL', default='mozillians_haystack'), 'KWARGS': { 'http_auth': auth, 'connection_class': RequestsHttpConnection, } } } else: haystack_connections = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': es_url, 'INDEX_NAME': config('ES_INDEX_URL', default='mozillians_haystack') } } return haystack_connections
def init(request): return { 'LINK':settings.STATIC_LINK, 'STATIC_URL':config('STATIC_URL',default='/static/'), 'REDIRECT_LOGIN':config('REDIRECT_LOGIN',default='/'), 'THEME':config('THEME_DEFAULT',default='default'), 'NOME_PROJETO':config('NOME_PROJETO',default='NOME DO PROJETO'), 'VERSAO_PROJETO':config('VERSAO_PROJETO',default='VERSAO DO PROJETO'), 'ANO_PROJETO':config('ANO_PROJETO',default='ANO DO PROJETO') }
import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config("SECRET_KEY") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from pusher import Pusher from django.http import JsonResponse from decouple import config from django.contrib.auth.models import User from .models import * from rest_framework.decorators import api_view import json # instantiate pusher pusher = Pusher(app_id=config('PUSHER_APP_ID'), key=config('PUSHER_KEY'), secret=config('PUSHER_SECRET'), cluster=config('PUSHER_CLUSTER')) @csrf_exempt @api_view(["GET"]) def initialize(request): user = request.user player = user.player player_id = player.id uuid = player.uuid room = player.room() players = room.playerNames(player_id) return JsonResponse( { 'uuid': uuid, 'name': player.user.username, 'title': room.title,
Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import cloudinary import django_heroku import dj_database_url from decouple import config, Csv MODE = config("MODE", default="dev") DEBUG = config('DEBUG', default=False, cast=bool) if config('MODE')=="prod": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': '', } } # production
For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from decouple import config, Csv import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', False) ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
from functools import partial from pathlib import Path import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration # Build paths inside the project like this: BASE_DIR / 'subdir'. import dj_database_url from decouple import config, Csv BASE_DIR = Path(__file__).resolve().parent.parent # 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 = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) AUTH_USER_MODEL = 'base.User' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
""" import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # 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 = config('SECRET_KEY', default='dummy-key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['https://jadenttp.pythonanywhere.com', 'jadenttp.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'portfolio.apps.PortfolioConfig', 'cloudinary', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',
""" import django_heroku from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(',') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',
# Last tested 3/11/2021 14:21 # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException from decouple import config import unittest, time, re # Account Data Email = config("EXISTING_USER_EMAIL", cast=str) Password = config("NEW_USER_PASSWORD", cast=str) NamaAhliWaris = config("NAME_BENEFICIARY", cast=str) TglLahirAhliWaris = config("DAY_OF_BIRTH_BENEFICIARY", cast=str) BlnLahirAhliWaris = config("MONTH_OF_BIRTH_BENEFICIARY", cast=str) ThnLahirAhliWaris = config("YEAR_OF_BIRTH_BENEFICIARY", cast=str) Product = config("PRODUCT", cast=str) PaymentMethod = config("PAYMENT_METHOD", cast=str) CardName = config("CARD_NAME", cast=str) CardNum = config("CARD_NUM", cast=str) CardCVC = config("CARD_CVC", cast=str) class TestCaseSingleProduct(unittest.TestCase): def setUp(self):
import discord from discord.ext import commands import os import random from disputils import BotEmbedPaginator import pyrebase import json from decouple import config links_str = """ [Youtube](https://www.youtube.com/channel/UCq4FMXXgsbsZmw5A-Mr7zSA) , [GitHub](https://GitHub.com/ankushKun) , [Twitter](https://twitter.com/__AnkushSingh__) , [Instagram](https://instagram.com/__weebletkun__) , [Reddit](https://www.reddit.com/u/TECHIE6023) , [Fiverr](https://fiverr.com/atctech) [Vibhi Chan Invite Link](https://discord.com/api/oauth2/authorize?client_id=746984468199374908&permissions=8&scope=bot) """ firebase = pyrebase.initialize_app(json.loads(config("FIREBASE"))) db = firebase.database() class Help(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def help(self, ctx): global help_str rolepl = "" try: rolepl = "" for each in db.child("RP").child("CMD").get().val(): rolepl += ", " + each
https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os from decouple import config import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = ['.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages',
https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import dj_database_url from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ # django 'jet.dashboard', 'jet', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes',
https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config, Csv from authentication.key import get_public_key # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=True, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='.localhost', cast=Csv()) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' MAIL_PORT = 587 # 465 MAIL_USE_TLS = True # MAIL_USE_SSL = True EMAIL_HOST_USER = config('EMAIL') # os.environ.get('EMAIL_PASS') EMAIL_HOST_PASSWORD = config('PASS') SSL_DISABLE = True TLS_DISABLE = False # print(EMAIL_HOST_USER) REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ]
#!/usr/bin/env python3 from decouple import config import keras import numpy as np import pandas as pd from tinydb import TinyDB # Constants NUM_CHANNELS = 3 DATABASE_PATH = config("DATABASE_PATH") # Lambdas LEGROOM = lambda num_lines: print("\n" * num_lines) def load_data(): """Load database""" db = TinyDB(DATABASE_PATH) data = db.all() return pd.DataFrame(data) def process_dataset(df, train_validation_ratio=0.8): """Given a dataset, perform train-validation split and generate minibatches""" x_train, y_train, x_val, y_val = None, None, None, None # image data xS = None # dankness score
https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path import dj_database_url from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # 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 = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(',') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'django_filters', 'drf_yasg', 'account', 'product', 'order' ]
"""Retrieve tweets, embeddings, and save into a database""" import basilica import tweepy from decouple import config from .models import DB, Tweet, User TWITTER_AUTH = tweepy.OAuthHandler(config('TWITTER_CONSUMER_KEY'), config('TWITTER_CONSUMER_SECRET')) TWITTER_AUTH.set_access_token(config('TWITTER_ACCESS_TOKEN'), config('TWITTER_ACCESS_TOKEN_SECRET')) TWITTER = tweepy.API(TWITTER_AUTH) BASILICA = basilica.Connection(config('BASILICA_KEY')) #add more functions here def add_or_update_user(username): """Add or update a user and their tweets, or else error""" try: twitter_user = TWITTER.get_user(username) db_user = (User.query.get(twitter_user.id) or User(id=twitter_user.id, name=username)) DB.session.add(db_user) tweets = twitter_user.timeline(count=200, exclude_replies=True, include_rts=False, tweet_mode='extended', since_id=db_user.newest_tweet_id) if tweets: db_user.newest_tweet_id = tweets[0].id for tweet in tweets:
https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path from decouple import config from dj_database_url import parse as dburl import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # 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 = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['localhost', 'jonathacnb.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
import os from decouple import config LOG_LEVEL = config("LOG_LEVEL", default="INFO") PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
def weather_api(request, *args, **kwargs): api_key = config('API_KEY') today = datetime.date.today() today_dt = int( time.mktime( datetime.datetime.strptime(str(today), "%Y-%m-%d").timetuple())) today_now = datetime.datetime.now() today_now_dt = int( time.mktime( datetime.datetime.strptime(str(today_now), "%Y-%m-%d %H:%M:%S.%f").timetuple())) arr_dt = [] temp_arr = [] temp = '' temp_min = '' temp_min_arr = [] temp_max = '' temp_max_arr = [] hum_arr = [] hum = '' if request.method == 'GET': weathers = WeatherApi.objects.all() serializer = WeatherSerializer(weathers, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': city = '' from_time = '' to_time = '' if len(request.POST) == 0: data = JSONParser().parse(request) serializer = WeatherSerializer(data=data) if serializer.is_valid(): city = data['city'] from_time = data['from_time'] to_time = data['to_time'] else: return JsonResponse( { 'status': 400, 'msg': 'Invalid form inputs data, check your Start and End Time Correctly' }, status=400) else: _i = request.POST inputs = dict(_i.lists()) city = inputs['city'][0] from_time = inputs['from_time'][0] to_time = inputs['to_time'][0] from_time_dt = int( time.mktime( datetime.datetime.strptime((str(today) + ' ' + from_time), "%Y-%m-%d %H:%M").timetuple())) to_time_dt = int( time.mktime( datetime.datetime.strptime((str(today) + ' ' + to_time), "%Y-%m-%d %H:%M").timetuple())) if from_time_dt >= to_time_dt: return JsonResponse( { 'status': 400, 'msg': 'From Time cannot be greather than To Time' }, status=400) elif from_time_dt < today_now_dt: return JsonResponse( { 'status': 400, 'msg': 'API does not provide historical data, Please check your From Time' }, status=400) try: url = f'http://api.openweathermap.org/data/2.5/forecast?q={city}&units=metric&appid={api_key}' r = requests.get(url) r_data = json.loads(r.text) r_list = r_data['list'] for item in r_list: if item['dt'] >= from_time_dt and item['dt'] <= to_time_dt: arr_dt.append(item) if len(arr_dt) == 0: url_1 = f'http://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={api_key}' r1 = requests.get(url_1) r1_data = json.loads(r1.text) lon = r1_data['coord']['lon'] lat = r1_data['coord']['lat'] temp_ar = [temp, temp_max, temp_min] temp_ar.sort() temp_mean = temp_ar[1] current = { 'temp': r1_data['main']['temp'], 'temp_min': r1_data['main']['temp_min'], 'temp_max': r1_data['main']['temp_max'], 'temp_avg': round(((r1_data['main']['temp_min']) + (r1_data['main']['temp_max'])) / 2), 'temp_mean': temp_mean, 'humidity': r1_data['main']['humidity'], 'city': city } return JsonResponse(current, status=200) else: for item in arr_dt: temp_arr.append(item['main']['temp']) temp_min_arr.append(item['main']['temp_min']) temp_max_arr.append(item['main']['temp_max']) hum_arr.append(item['main']['humidity']) temp_min = temp_min_arr[0] if len( temp_min_arr) == 1 else min(*temp_min_arr) temp_max = temp_max_arr[0] if len( temp_min_arr) == 1 else max(*temp_max_arr) temp_avg = temp_arr[0] if len(temp_arr) == 1 else round( sum(temp_arr) / len(temp_arr)) temp, _ = (temp_arr[0], '') if len(temp_arr) == 1 else median(temp_arr) hum, _ = (hum_arr[0], '') if len(hum_arr) == 1 else median(hum_arr) current = { 'temp': temp, 'temp_min': temp_min, 'temp_max': temp_max, 'temp_avg': temp_avg, 'temp_mean': temp, 'humidity': hum, 'city': city } except Exception as ex: return JsonResponse({ 'status': 400, 'msg': 'API Calls Failed' }, status=400) return JsonResponse(current, status=200)
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'courses.apps.CoursesConfig', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions',
For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') AWS_ACCESS_KEY_ID = config('S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'elearning-storage' AWS_DEFAULT_ACL = None AWS_S3_SECURE_URLS = True AWS_QUERYSTRING_EXPIRE = '18000' LIVE_EC2_ID = 'i-0affe9ef2d03a04df' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*']
import django_heroku from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication import os from decouple import config import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECRET_KEY = 'Mez[)yagh/{k*{rD2<}2ZNtMqu3ZwBaj;~S?i_K>61?UhlK$J{HV)8#L|?#a?bL' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) # DEBUG = 'True' ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1', 'csninjas.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
import os from .base import * from decouple import config DEBUG = False ALLOWED_HOSTS = ['ecb.kh.ua', 'www.ecb.kh.ua'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': '5432', } } STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = '/home/paloni/webapps/echb_static/' MEDIA_ROOT = os.path.join(BASE_DIR, '/home/paloni/webapps/echb_static/media/') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = config('SMTP_SERVER') EMAIL_PORT = config('SMTP_PORT') EMAIL_HOST_USER = config('MAIL_USER') EMAIL_HOST_PASSWORD = config('MAIL_PASSWORD')
import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def base(*path): return os.path.normpath(os.path.join(os.path.abspath(BASE_DIR), *path)) def root(*path): return os.path.normpath(os.path.join(os.path.abspath(PROJECT_ROOT), *path)) SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = ['*'] HTTP_X_FORWARDED_FOR = -1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'index', ]
# Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent import os from decouple import config TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR=os.path.join(BASE_DIR,'static') # 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 = +8ab082i^32w(m_pv5u!q4rvmunnn%c7mwg2@nn*-#@p=#q_mf # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'taskapp', 'phonenumber_field',
For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'widget_tweaks', 'rest_framework', 'rest_framework.authtoken', 'JournalApp' ]
import os from pathlib import Path from decouple import config # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS').split(',') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', 'payment', 'product', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',
For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os from decouple import config, Csv # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('DJANGO_SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DJANGO_DEBUG', default=False, cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',
Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import django_heroku import dj_database_url from decouple import config, Csv MODE = config("MODE", default="dev") SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) # development if config('MODE') == "dev": DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': config('DB_HOST'), 'PORT': '', } } # production