Beispiel #1
0
from datetime import datetime
import pandas as pd
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import traceback, os, logging

import logging.config
logging.config.fileConfig(fname='log.conf', disable_existing_loggers=False)
logger = logging.getLogger()

from dotenv import load_dotenv
load_dotenv(dotenv_path='stock.env')


def getCurrentTime():
    now = datetime.now()
    return str(now.strftime("%H:%M"))


def getStocks(stockFile):
    return list(pd.read_csv(stockFile, header=None)[0])


def sendEmail(subject, text):
    now = datetime.now()
    current_time = now.strftime("%Y-%m-%d %H-%M")
    try:
        subject = "{} - {}".format(subject, current_time)
Beispiel #2
0
import os
from dotenv import load_dotenv

basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))

class DevConfig(object):
	DEBUG = True
	ENV = "development"

	SECRET_KEY = os.environ.get('SECRET_KEY')
	TEMPLATES_AUTO_RELOAD = True
	REDIS_QUEUE_NAME = 'bookish-tasks'
	REDIS_URL = os.environ.get('REDIS_URL') or 'redis://'
	TASK_RESULT_PATH = os.environ.get('TASK_RESULT_PATH') or 'rq_results/'

	DB_URL = os.environ.get('DB_URL')
	DB_PORT = int(os.environ.get('DB_PORT'))
	DB_NAME = os.environ.get('DB_NAME')
	DB_USER = os.environ.get('DB_USER')
	DB_PASSWORD = os.environ.get('DB_PASSWORD')

	SESSION_LENGTH = 7

	NUM_CORES = 2

class ProdConfig(object):
	DEBUG = False
	ENV = "production"

	SECRET_KEY = os.environ.get('SECRET_KEY')
import PIL.ImageGrab
import os
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

send_button_x = int(os.environ["SEND_BUTTON_X"])
send_button_y = int(os.environ["SEND_BUTTON_Y"])
 
def get_pixel_colour(i_x, i_y):	
	return PIL.ImageGrab.grab().load()[i_x, i_y]
 
print (get_pixel_colour(send_button_x, send_button_y))
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage, ImageSendMessage
)
import os
from os.path import join, dirname
from dotenv import load_dotenv

import random

load_dotenv(join(dirname(__file__), '.env'))

app = Flask(__name__)

#環境変数取得
YOUR_CHANNEL_ACCESS_TOKEN = os.environ.get('LINE_TOKEN')
YOUR_CHANNEL_SECRET = os.environ.get('LINE_SECRET')

line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(YOUR_CHANNEL_SECRET)

@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']
"""
Created on Sat Aug 22 17:16:51 2020

@author: atseewal
"""

#%% Imports
import discord, os#, random, asyncio
from datetime import datetime
import numpy as np
from discord.ext import commands
from SoT_webscraping import daily_bounties
from SoT_date_parse import parse_SoT_date
from dotenv import load_dotenv

load_dotenv('.env')

client=commands.Bot(command_prefix='!')

@client.event
async def on_ready():
    print('Connected to bot: {}'.format(client.user.name))
    print('Bot ID: {}'.format(client.user.id))
    
    await client.change_presence(activity = discord.Game(name='Sea of Thieves'))

@client.command()
async def dailybounty(ctx):
    
    # Load the latest bounty file
    d_bounty = np.load('SoT_output.npy', allow_pickle=True).item()
Beispiel #6
0
# you may not use this file except in compliance with the License.
#
""" Userbot initialization. """

import os

from sys import version_info
from logging import basicConfig, getLogger, INFO, DEBUG
from distutils.util import strtobool as sb

from dotenv import load_dotenv
from requests import get
from telethon import TelegramClient
from telethon.sessions import StringSession

load_dotenv("config.env")

# Logger setup:
CONSOLE_LOGGER_VERBOSE = sb(os.environ.get("CONSOLE_LOGGER_VERBOSE", "False"))


if CONSOLE_LOGGER_VERBOSE:
    basicConfig(
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        level=DEBUG,
    )
else:
    basicConfig(
        format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        level=INFO
    )
Beispiel #7
0
##########################################################################
## Imports
##########################################################################

import os
import sys
import dotenv

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

##########################################################################
## Main Method
##########################################################################

if __name__ == "__main__":
    # load .env file
    dotenv.load_dotenv(dotenv.find_dotenv())

    # set default environment variables
    os.environ.setdefault("DJANGO_SETTINGS_MODULE",
                          "ledger.settings.development")

    # execute the django admin script
    execute_from_command_line(sys.argv)
Beispiel #8
0
def main(window_length, future_length, n_output_features, batch_size, learning_rate):
    # try to load mlflow tracking and artifact uri from environment variables
    tracking_uri = os.environ.get('MLFLOW_TRACKING_URI')
    artifact_uri = os.environ.get('MLFLOW_ARTIFACT_URI')
    print(tracking_uri, artifact_uri)

    # if env variables are not set, load .env file
    if (tracking_uri is None) | (artifact_uri is None):
        load_dotenv()
        print(os.path.expandvars('${MLFLOW_TRACKING_URI}'))
        print(os.path.expandvars('${MLFLOW_ARTIFACT_URI}'))
        tracking_uri = os.path.expandvars('${MLFLOW_TRACKING_URI}'.strip('"\''))
        artifact_uri = os.path.expandvars('${MLFLOW_ARTIFACT_URI}'.strip('"\''))

    mlflow.tracking.set_registry_uri(tracking_uri)
    mlflow.tracking.set_tracking_uri(artifact_uri)

    # The data includes 'nan' and '?' as a string, both will be imported as numpy nan
    # Note that I will only use the first 2000 rows for the example
    df = pd.read_csv('./household_power_consumption.txt', sep=';',
                     parse_dates={'dt': ['Date', 'Time']}, infer_datetime_format=True,
                     low_memory=False, na_values=['nan', '?'], index_col='dt')

    # filling nan with mean in any columns
    for j in range(0, 7):
        df.iloc[:, j] = df.iloc[:, j].fillna(df.iloc[:, j].mean())

    # Standardization
    mean = df.mean(axis=0)
    std = df.std(axis=0)
    standardized = (df - mean) / std

    # Grid Search Hyperparameter
    # Dictionary with different hyperparameters to train on.
    # MLflow will track those in a database.
    grid_search_dic = {'hidden_layer_size': [20, 40],
                       'batch_size': [batch_size],
                       'future_length': [future_length],
                       'window_length': [window_length],
                       'dropout_fc': [0.0, 0.2],
                       'n_output_features': [n_output_features]}

    # Cartesian product
    grid_search_param = [dict(zip(grid_search_dic, v)) for v in product(*grid_search_dic.values())]

    # Training

    # enable gpu growth if gpu is available
    gpu_devices = tf.config.experimental.list_physical_devices('GPU')
    for device in gpu_devices: tf.config.experimental.set_memory_growth(device, True)

    with mlflow.start_run() as parent_run:
        for params in grid_search_param:
            batch_size = params['batch_size']
            window_length = params['window_length']
            future_length = params['future_length']
            dropout_fc = params['dropout_fc']
            hidden_layer_size = params['hidden_layer_size']
            n_output_features = params['n_output_features']

            with mlflow.start_run(nested=True) as child_run:
                # log parameter
                mlflow.log_param('batch_size', batch_size)
                mlflow.log_param('window_length', window_length)
                mlflow.log_param('hidden_layer_size', hidden_layer_size)
                mlflow.log_param('dropout_fc_layer', dropout_fc)
                mlflow.log_param('future_length', future_length)
                mlflow.log_param('n_output_features', n_output_features)

                model = build_lstm_2_layer_model(window_length=window_length,
                                                 future_length=future_length,
                                                 n_output_features=n_output_features,
                                                 units_lstm_layer=hidden_layer_size,
                                                 dropout_rate=dropout_fc)

                data_sliding_window = apply_sliding_window_tf_data_api(standardized.values,
                                                                       batch_size=batch_size,
                                                                       window_length=window_length,
                                                                       future_length=future_length,
                                                                       n_output_features=n_output_features)

                model.compile(loss='mse', optimizer=keras.optimizers.Nadam(learning_rate=learning_rate),
                              metrics=['mse', 'mae'])

                model.fit(data_sliding_window, shuffle=True, initial_epoch=0, epochs=10,
                          callbacks=[MlflowLogging()])

                model.save("./tmp")

                mlflow.tensorflow.log_model(tf_saved_model_dir='./tmp',
                                            tf_meta_graph_tags='serve',
                                            tf_signature_def_key='serving_default',
                                            artifact_path='saved_model',
                                            registered_model_name='Electric Power Consumption Forecasting')

                shutil.rmtree("./tmp")
Beispiel #9
0
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@file: __init__.py
@time: 2020/5/18
@name: application
@desc: 管理项目的基础配置信息
"""
import os

from dotenv import load_dotenv

from .app_settings import AppSettings, AppDebugSettings

# 加载配置文件
load_dotenv(dotenv_path=os.path.join(os.getcwd(), ".flask.env"))
# 获取环境部署信息
flask_config = os.getenv('FLASK_CONFIG')
Settings = {
    "App": AppSettings(),
    "AppDebug": AppDebugSettings()
}.get(flask_config)
Beispiel #10
0
from dotenv import load_dotenv
from github import Github
import os


load_dotenv() # Important to do before accessing env vars.


GITHUB_ORGANIZATION_NAME = os.getenv('GITHUB_ORGANIZATION_NAME')
GITHUB_PERSONAL_ACCESS_TOKEN = os.getenv('GITHUB_PERSONAL_ACCESS_TOKEN')


github_session = Github(GITHUB_PERSONAL_ACCESS_TOKEN)
Beispiel #11
0
import os
from dotenv import load_dotenv

load_dotenv(verbose=True)

DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY")

db = {
    "user": DB_USER,
    "password": DB_PASSWORD,
    "host": "localhost",
    "port": 3306,
    "database": "flask_miniter",
}

DB_URL = f"mysql+mysqlconnector://{db['user']}:{db['password']}@{db['host']}:{db['port']}/{db['database']}?charset=utf8"
Beispiel #12
0
#!/usr/bin/env python
import sqlite3
import os
import dotenv


def createSchema(conn):
	c = conn.cursor()
	c.execute('''CREATE TABLE models (id integer PRIMARY KEY, name text, error real)''')
	c.execute('''CREATE TABLE layers (id integer PRIMARY KEY, layer_index integer, model_id integer)''')
	c.execute(
		'''CREATE TABLE neurons (id integer PRIMARY KEY, neuron_index integer, layer_id integer, sum json, value json)'''
	)
	c.execute('''CREATE TABLE weights (id integer PRIMARY KEY, neuron_from integer, neuron_to integer, weight json)''')
	conn.commit()


if __name__ == "__main__":
	dotenv.load_dotenv('.env')
	conn = sqlite3.connect('data/' + os.environ['DB_NAME'])
	createSchema(conn)
	conn.close()
Beispiel #13
0
import os
from os import getenv
from os.path import join, dirname
from dotenv import load_dotenv
from app.settings.base import BaseSettings
from app.settings.local import LocalSettings
from app.settings.production import ProductionSettings

# GET PARAMS FROM ENV FILE
env_file = join(dirname(__file__), '.env')
load_dotenv(env_file)

# get environ
env = os.environ.get('env', None)

# get configs by environ
if env is None:
    config = BaseSettings()
elif env == 'production':
    config = ProductionSettings()
elif env == 'local':
    config = LocalSettings()
else:
    raise ValueError("Environment name isn't specified")

# overide from env
DB_PASSWORD = getenv('DB_PASSWORD', None)
if DB_PASSWORD is not None:
    config.DATABASE['PASSWORD'] = DB_PASSWORD

DB_NAME = getenv('DB_NAME', None)
Beispiel #14
0
    Keyword,
    Limitation,
    License,
    Specification,
    IsogeoTranslator,
    Contact,
    ApiKeyword,
)

sys.path.append(str(Path(__file__).parents[2]))
from isogeotoxlsx import IsogeoFromxlsx, dict_inspire_fr, dict_inspire_en

checker = IsogeoChecker()

# ##################### SETTINGS #####################
load_dotenv("dev.env")
# logs
logger = logging.getLogger()
# ------------ Log & debug ----------------
logging.captureWarnings(True)
logger.setLevel(logging.DEBUG)
# logger.setLevel(logging.INFO)

log_format = logging.Formatter(
    "%(asctime)s || %(levelname)s "
    "|| %(module)s - %(lineno)d ||"
    " %(funcName)s || %(message)s"
)

# debug to the file
log_file_handler = RotatingFileHandler(
        textToSpeechCreds = vcap['text_to_speech'][0]['credentials']
        textToSpeechUser = textToSpeechCreds['username']
        textToSpeechPassword = textToSpeechCreds['password']
    if 'speech_to_text' in vcap:
        speechToTextCreds = vcap['speech_to_text'][0]['credentials']
        speechToTextUser = speechToTextCreds['username']
        speechToTextPassword = speechToTextCreds['password']
    if "WORKSPACE_ID" in os.environ:
        workspace_id = os.getenv('WORKSPACE_ID')

    if "ASSISTANT_IAM_APIKEY" in os.environ:
        assistantIAMKey = os.getenv('ASSISTANT_IAM_APIKEY')

else:
    print('Found local VCAP_SERVICES')
    load_dotenv(os.path.join(os.path.dirname(__file__), ".env"))
    assistantUsername = os.environ.get('ASSISTANT_USERNAME')
    assistantPassword = os.environ.get('ASSISTANT_PASSWORD')
    assistantIAMKey = os.environ.get('ASSISTANT_IAM_APIKEY')
    assistantUrl = os.environ.get('ASSISTANT_URL')
    TTSAPIKey = os.environ.get('TTS_API_KEY')
    STTAPIKey = os.environ.get('STT_API_KEY')

    textToSpeechUser = os.environ.get('TEXTTOSPEECH_USER')
    textToSpeechPassword = os.environ.get('TEXTTOSPEECH_PASSWORD')
    workspace_id = os.environ.get('WORKSPACE_ID')

    print(assistantUsername, assistantPassword, assistantIAMKey, assistantUrl,
          textToSpeechUser, workspace_id, textToSpeechPassword)

    # speechToTextUser = os.environ.get('SPEECHTOTEXT_USER')
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import uuid
import shutil
import types
import pandas as pd
import argparse
import ibm_boto3
from botocore.client import Config
from dotenv import load_dotenv
load_dotenv('.Credentials')

parser = argparse.ArgumentParser()
parser.add_argument('--bucket', type=str)
args = parser.parse_args()


def __iter__(self):
    return 0


def pandas_support(csv):
    # add missing __iter__ method, so pandas accepts body as file-like object
    if not hasattr(csv, "__iter__"):
        csv.__iter__ = types.MethodType(__iter__, csv)
    return csv

Beispiel #17
0
from . import log

log.start('dashboard')
from dotenv import load_dotenv
from .definitions import ROOT_DIR
import os

load_dotenv(os.path.join(ROOT_DIR, '.env'))
from .dash.web import dash_app as app
from .dash.web import db
from .dash.web.models import User, Notice
from sqlalchemy.exc import OperationalError

try:
    __users = User.query.all()
    if len(__users) == 0:
        # noinspection PyArgumentList
        superuser = User(username='******',
                         permission='Administrator',
                         reset_pass=True)
        superuser.set_password('edftadmin')
        db.session.add(superuser)
        db.session.commit()
except OperationalError:
    pass

if __name__ == '__main__':
    app.run(host='0.0.0.0')


@app.shell_context_processor
Beispiel #18
0
"""
WSGI config for myPortfolio project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from dotenv import load_dotenv

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myPortfolio.settings')

application = get_wsgi_application()

project_folder = os.path.expanduser('~/myPortfolio')  # adjust as appropriate
load_dotenv(os.path.join(project_folder, '.env'))
Beispiel #19
0
import os
from dotenv import load_dotenv
from kombu import Exchange, Queue
from celery.schedules import crontab

load_dotenv(dotenv_path='.env')
basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
    SECRET_KEY = os.environ.get('FLASK_SECRET_KEY', '123456')
    SQLALCHEMY_DATABASE_URI = os.environ.get(
        'FLASK_SQLALCHEMY_DATABASE_URI',
        'mysql+cymysql://root:[email protected]:3306/atfield')
    CELERY_BROKEN_URL = os.environ.get(
        'FLASK_CELERY_BROKER_URL', 'amqp://*****:*****@127.0.0.1:5672/atfield')
    CELERY_RESULT_BACKEND = os.environ.get('FLASK_CELERY_BROKER_URL',
                                           'redis://:@127.0.0.1:6379/0')
    ES_HOST = os.environ.get('FLASK_ES_HOST', '127.0.0.1')
    ES_PORT = os.environ.get('FLASK_ES_PORT', 9500)
    ES_USERNAME = os.environ.get('FLASK_ES_USERNAME', 'username')
    ES_PASSWORD = os.environ.get('FLASK_ES_PASSWORD', 'password')
    SQLALCHEMY_RECORD_QUERIES = True
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    TOKEN_EXPIRATION = 30 * 24 * 3600

    CELERY_INCLUDES = ('scanner', )
    CELERY_IMPORTS = ('scanner', )

    CELERY_QUEUES = (
Beispiel #20
0
#!/usr/bin/env python3
# bot.py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import hashlib
from pathlib import Path

load_dotenv(dotenv_path=".env")
TOKEN = os.getenv('DISCORD_TOKEN_SITESWAP')
bot = commands.Bot(command_prefix='+')

exec_path = Path("./JugglingLab/jlab")
dir_img = Path("./Siteswap/")

fail_gif_path = Path("./Siteswap/juggler.gif")

@bot.command(name='siteswap', help="""Send a message with a siteswap and the bot will send you te gif if it exist\n
some example :\n
+siteswap 333
+siteswap (4,2x)(2x,4)
+siteswap [333]33
+siteswap <3p|3p><3|3><3|3><3|3>""")
async def siteswap(ctx, *,f_siteswap="333"):

    #### IF not in the good channel #####TODO not generic function for now
    #if ctx.channel.id not in [702470629198266388]:
    #    await ctx.message.delete(delay=1.0)
    #    print("pas le droit d'ecrire")
    #    return
#INFO INPUTS 
import datetime
import json
import csv
from dotenv import load_dotenv
import os
import requests 
from twilio.rest import Client

load_dotenv() #> loads contents of the .env file into the script's environment

symbol = "99"
correct = 0

print("WELCOME TO THE ROBO ADVISOR PROGRAM! WE ADVISE ON STOCK SYMBOLS")


while(correct == 0):
    symbol = input("PLEASE INPUT A STOCK YOU ARE LOOKING TO BUY: ")
    if(symbol.isalpha() == 1):
        correct = 1
        if(len(symbol) > 5):
            print("OOPS! Sorry you inputed the wrong information. You inputed more than 5 letters! Please try again! A ticker is only between 1-5 letters, expecting ticker symbol like 'MSFT'.")
            correct = 0
    else:
        print("OOPS! Sorry you inputed the wrong information. You inputed numbers instead of letters! Please try again! A ticker is only letters and is between 1-5 letters, expecting ticker symbol like 'MSFT'.")


api_key = os.environ.get("ALPHAVANTAGE_API_KEY")
request_url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey={api_key}"
response = requests.get(request_url)
Beispiel #22
0
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

from telethon import TelegramClient
from telethon.sessions import StringSession
from telethon.tl.types import ChatBannedRights

from distutils.util import strtobool as sb
import os
from dotenv import load_dotenv

from pylast import LastFMNetwork, md5

ENV = os.environ.get("ENV", False)
if not bool(ENV):
    load_dotenv(dotenv_path='config.env')
else:
    STRING_SESSION = os.environ.get("STRING_SESSION", None)

API_ID = os.environ.get("API_ID", None)
API_HASH = os.environ.get("API_HASH", None)


class Var(object):
    DB_URI = os.environ.get("DATABASE_URL", None)
    TEMP_DOWNLOAD_DIRECTORY = os.environ.get("TEMP_DOWNLOAD_DIRECTORY", None)
    PRIVATE_GROUP_ID = os.environ.get("PRIVATE_GROUP_ID", None)
    if PRIVATE_GROUP_ID != None:
        try:
            PRIVATE_GROUP_ID = int(PRIVATE_GROUP_ID)
        except ValueError:
Beispiel #23
0
import os

import dotenv
from stellar_sdk import Asset, Keypair, Server

dotenv.load_dotenv(verbose=True)

STELLAR_HORIZON_TESTNET = os.getenv("STELLAR_HORIZON_TESTNET")
server = Server(STELLAR_HORIZON_TESTNET)

issuing_public = os.getenv("ISSUING_PUBLIC")
inr_asset = Asset("INRx", issuing_public)


def get_public_key(private_key):

    keypair = Keypair.from_secret(private_key)
    return keypair.public_key


def get_balance(account_public_key: str) -> str:

    account_details = server.accounts().account_id(account_public_key).call()
    return account_details["balances"][0]["balance"]


def create_keypair():

    keypair = Keypair.random()
    print('Public key: ', keypair.public_key)
    print('Private key: ', keypair.secret, '\n')
Beispiel #24
0
import pymssql
from openpyxl import Workbook
from openpyxl.styles import Font, Fill, PatternFill, Alignment
from openpyxl.formatting.rule import ColorScaleRule, CellIsRule, FormulaRule
from collections import OrderedDict
from dotenv import load_dotenv

# set python environment
if getattr(sys, 'frozen', False):
    bundle_dir = sys._MEIPASS
else:
    # we are running in a normal Python environment
    bundle_dir = os.path.dirname(os.path.abspath(__file__))

# load environmental variables
load_dotenv(bundle_dir + "/.env")

# Holidays Off  from https://www.timeanddate.com/holidays/us/2021
holidays = [(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d").date())(x)
            for x in [
                "2020-01-01",
                "2020-05-25",
                "2020-07-03",
                "2020-09-07",
                "2020-11-26",
                "2020-11-27",
                "2020-12-25",
                "2020-12-31",
                "2021-05-31",
                "2021-07-05",
                "2021-09-06",
Beispiel #25
0
#
# This software is Copyright ©️ 2020 The University of Southern California. All Rights Reserved.
# Permission to use, copy, modify, and distribute this software and its documentation for educational, research and non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and subject to the full license file found in the root of this software deliverable. Permission to make commercial use of this software may be obtained by contacting:  USC Stevens Center for Innovation University of Southern California 1150 S. Olive Street, Suite 2300, Los Angeles, CA 90115, USA Email: [email protected]
#
# The full terms of this copyright and license should always be found in the root directory of this software deliverable as "license.txt" and if these terms are not found with this software, please contact the USC Stevens Center for the full license.
#
from dotenv import load_dotenv

load_dotenv()  # take environment variables from .env.

from logging.config import dictConfig  # NOQA

from flask import Flask  # NOQA
from flask_cors import CORS  # NOQA
from .config_default import Config  # NOQA


def create_app():
    dictConfig(
        {
            "version": 1,
            "formatters": {
                "default": {
                    "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"
                }
            },
            "handlers": {
                "wsgi": {
                    "class": "logging.StreamHandler",
                    "stream": "ext://flask.logging.wsgi_errors_stream",
                    "formatter": "default",
Beispiel #26
0
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
from dotenv import load_dotenv

# 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__))))

# загружаем переменные окружения из файла '.env'
load_dotenv(os.path.join(BASE_DIR, '.env'))


# 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 = os.getenv('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# считываем имена разрешенных хостов 'LOCAL_HOST' из .env
ALLOWED_HOSTS = [os.getenv('LOCAL_HOST')]

            cursor = connection.cursor()

            sql = """\
                SELECT id, username
                FROM customers
            """

            cursor.execute(sql)

            results = cursor.fetchall()

            customers = [{'id': c[0], 'username': c[1]} for c in results]

        status = 'success'
    except Oracle.DatabaseError as e:
        print e
    finally:
        if cursor is not None:
            cursor.close()

        print json.dumps({'status': status, 'customers': customers})
    # end finally
# end def main()


if __name__ == '__main__':
    # Load in environment variables
    load_dotenv(find_dotenv())

    main()
Beispiel #28
0
from datetime import datetime, timedelta

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, AsyncEngine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql import select
import jwt

from models import Base, UserInDB, Salt
from hash_password import hash_password, check_password_hash

app = FastAPI(title='User Register Test API')

load_dotenv(dotenv_path=Path('.env'))

USER = '******'  # environ.get('USER')
PASSWORD = '******'  # environ.get('PASSWORD')
HOST = 'ec2-54-75-229-28.eu-west-1.compute.amazonaws.com'  # environ.get('HOST')
PORT = '5432'  # environ.get('PORT')
DATABASE = 'd1p21lku7v294h'  # environ.get('DATABASE')
SECRET_KEY = 'dester123456789dester'  # environ.get('SECRET_KEY')
ALGORITHM = 'HS256'  # environ.get('ALGORITHM')
ALL_GROUPS = ['default', 'vip', 'premium', 'holy', ' admin', 'dev', 'owner']


class UserReg(BaseModel):
    username: str
    password: str
Beispiel #29
0
Django settings for pogomap project.

Generated by 'django-admin startproject' using Django 2.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

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

import os

from dotenv import load_dotenv

load_dotenv()

# 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 = os.getenv("SECRET_KEY", "REPLACE_ME")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "true").lower() in ["yes", "1", "true"]

ALLOWED_HOSTS = []
Beispiel #30
0
from linebot.exceptions import InvalidSignatureError
from linebot.models import (CarouselColumn, CarouselTemplate,
                            URITemplateAction, TemplateSendMessage,
                            MessageEvent, TextMessage, LocationMessage,
                            LocationSendMessage, TextSendMessage,
                            StickerSendMessage, MessageImagemapAction,
                            ImagemapArea, ImagemapSendMessage, BaseSize)
from io import BytesIO, StringIO
from PIL import Image, ImageFile
import requests
import urllib.parse
import math
import sqlalchemy
from dotenv import load_dotenv

load_dotenv(verbose=True)
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

LINE_BOT_CHANNEL_ACCESS_TOKEN = os.environ.get('LINE_BOT_CHANNEL_ACCESS_TOKEN')
LINE_BOT_CHANNEL_SECRET = os.environ.get('LINE_BOT_CHANNEL_SECRET')
GOOGLE_MAPS_STATIC_API_KEY = os.environ.get('GOOGLE_MAPS_STATIC_API_KEY')
MYSQL_CONNECTION_NAME = os.environ.get('MYSQL_CONNECTION_NAME')
MYSQL_USER = os.environ.get('MYSQL_USER')
MYSQL_PASSWORD = os.environ.get('MYSQL_PASSWORD')
MYSQL_DATABASE = os.environ.get('MYSQL_DATABASE')
MAX_WIFI_NUM = os.environ.get('MAX_WIFI_NUM')

app = Flask(__name__)

line_bot_api = LineBotApi(LINE_BOT_CHANNEL_ACCESS_TOKEN)