def get_user_app(): app = Blueprint("user_app", __name__, template_folder=str(TEMPLATE_FOLDER)) db = get_database("sqlite3") @app.route("/user", methods=["POST", "GET"]) def user(): # handle POST request if request.method == "POST": user_name = request.args.get("user_name") if user_name: result = db.execute( "INSERT INTO users(user_name) VALUES (?)", [user_name], commit=True ) return jsonify(result), 200 # handle GET request if request.method == "GET": user_id = request.args.get("user_id") user_name = request.args.get("user_name") if user_id: user = db.execute("SELECT * FROM users WHERE user_id = ?", [user_id]) elif user_name: user = db.execute("SELECT * FROM users WHERE user_name = ?", [user_name]) else: return "Specify user id or user name", 400 if not user: return "User not found", 400 else: return jsonify(user), 200 return app
def __init__(self, config): super(FingerMusics, self).__init__() self.config = config # initialize db db_cls = get_database(config.get("database_type", None)) self.db = db_cls(**config.get("database", {})) self.db.setup() # if we should limit seconds fingerprinted, # None|-1 means use entire track self.limit = self.config.get("fingerprint_limit", None) if self.limit == -1: # for JSON compatibility self.limit = None # get songs previously indexed self.songs = self.db.get_songs() self.songnames_set = set() # to know which ones we've computed before for song in self.songs: song_name = song[self.db.FIELD_SONGNAME] self.songnames_set.add(song_name) print "Added: %s to the set of fingerprinted songs..." % song_name print self.songnames_set
def test_get_from_database(chat_id, field_name, data): database = get_database() database.update_one({'chat_id': chat_id}, {'$set': { field_name: data }}, upsert=True) result = get_from_database(field_name)[chat_id] assert result == data
def create_db(self): if os.path.isfile(DATABASE_NAME): os.remove(DATABASE_NAME) db = get_database(DATABASE_NAME) if db is None: self.fail("No database created") return db
def create_window(self, journal_id: int, database: str = None): window_id = self.new_window_id() if database in self.connections.keys(): connection = self.connections[database] else: connection = connect(database=get_database(database), detect_types=PARSE_DECLTYPES | PARSE_COLNAMES) self._connections[database] = connection self._windows[window_id] = VirtualWindow(window_id, journal_id, connection) add_id(journal_id, database)
def root_GET(): query = request.args.get('q', '') if query: db = get_database() results = db.search(query) else: results = [] vars = {'query': query, 'results': results} return render_template('index.html', **vars)
def get_url_authentification(scope=""): session["oauth_state"] = "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(30)) db = get_database() payload = { "client_id": db["oauth_client_id"], "scope": scope, "state": session["oauth_state"] } url_authentification = "https://github.com/login/oauth/authorize?" + urlencode(payload) return url_authentification
def get_access_token(): if "code" not in request.args or "state" not in request.args: return None if "oauth_state" not in session or session["oauth_state"] != request.args["state"]: return None db = get_database() payload = { "client_id": db["oauth_client_id"], "client_secret": db["oauth_client_secret"], "code": request.args["code"], "state": request.args["state"] } response = requests.post("https://github.com/login/oauth/access_token", params=payload, headers={'Accept': 'application/json'}).json() if "access_token" in response: return response["access_token"] return None
def callback_hook(): if request.headers.get('X-GitHub-Event') == "ping": return '{"message": "pong"}' if request.headers.get('X-GitHub-Event') == "pull_request": data = request.get_json() repository_name = data["repository"]["full_name"] db = get_database() if repository_name not in db["projects"]: return '{"message": "Project not found"}', 404 project = db["projects"][repository_name] if not verify_hmac_hash(project["secret"], request.data, request.headers.get("X-Hub-Signature")): return '{"message": "Bad signature"}', 403 pr_number = str(data["pull_request"]["number"]) pr_state = data["pull_request"]["state"] pr_title = data["pull_request"]["title"] pr_link = data["pull_request"]["html_url"] pr_statuses_url = data["pull_request"]["statuses_url"] create_status = False with database() as db: projects = db["projects"] if pr_number in projects[repository_name]["pr"]: projects[repository_name]["pr"][pr_number]["state"] = pr_state projects[repository_name]["pr"][pr_number]["title"] = pr_title projects[repository_name]["pr"][pr_number]["link"] = pr_link if projects[repository_name]["pr"][pr_number]["statuses_url"] != pr_statuses_url: projects[repository_name]["pr"][pr_number]["statuses_url"] = pr_statuses_url projects[repository_name]["pr"][pr_number]["validations"] = dict() create_status = True else: create_status = True projects[repository_name]["pr"][pr_number] = { "number": pr_number, "state": pr_state, "title": pr_title, "link": pr_link, "statuses_url": pr_statuses_url, "validations": dict() } project = projects[repository_name] db["projects"] = projects if create_status: if not set_status(db["baseurl"], project, pr_number): return '{"mesasge": "Impossible to set status on GitHub"}', 400 return '{"message": "Success"}' return '{"message": "Unknown event"}', 400
def get_index_app(): app = Blueprint("pages", __name__, template_folder=str(TEMPLATE_FOLDER)) db = get_database("sqlite3") @app.route("/", defaults={"page": "index"}) @app.route("/<page>") def show(page): if page == "index": template_kwargs = {"pages": PAGES} elif page == "users": template_kwargs = {"users": db.execute("SELECT * FROM users")} try: return render_template("%s.html" % page, **template_kwargs) except TemplateNotFound: abort(404) return app
def __init__(self, config): super(Dejavu, self).__init__() self.config = config # initialize db db_cls = get_database(config.get("database_type", None)) self.db = db_cls(**config.get("database", {})) self.db.setup() # if we should limit seconds fingerprinted, # None|-1 means use entire track self.limit = self.config.get("fingerprint_limit", None) if self.limit == -1: # for JSON compatibility self.limit = None self.get_fingerprinted_songs()
def __init__(self, config={}): config.setdefault('database', { "host": "127.0.0.1", "user": "******", "passwd": "pass", "db": "dejavu" }) config.setdefault('database_type', 'mysql') config.setdefault('analyze_span', 5) config.setdefault('analyze_skip', 15) config.setdefault('confidence_thresh', 100) self.config = config # initialize db db_cls = get_database(config.get("database_type", 'None')) self.db = db_cls(**config.get("database", {})) self.db.setup()
def get_general_variables(title): db = get_database() login = session["login"] if "login" in session else None is_admin = login in db["admins"] or len(db["admins"]) == 0 my_projects = list() for project in db["projects"]: if is_admin or login in db["projects"][project]["administrators"]: my_projects.append({ "link": "/?" + urlencode({"project": project}), "name": project, "administrators_list": ", ".join(db["projects"][project]["administrators"]) }) view = { "title": title, "login": login, "is_admin": is_admin, "my_projects": my_projects, "baseurl": db["baseurl"] } return db, view
def test_get_database(self, MongoClient): client_mock = MagicMock() database_mock = MagicMock() def client_side_effect(key): return database_mock if key == MONGODB_DATABASE_NAME else None client_mock.__getitem__.side_effect = client_side_effect MongoClient.return_value = client_mock returned_database = get_database() MongoClient.assert_called_once_with( MONGODB_HOST, MONGODB_PORT, username=MONGODB_USERNAME, password=MONGODB_PASSWORD, ) assert returned_database is database_mock
def save(self): db = get_database() data = self.to_json() db.lunni_run.insert({'hash': self.hash, 'data': data})
def test_set_to_database(chat_id, field_name, data): set_to_database(chat_id, field_name, data) database = get_database() result = database.find_one({'chat_id': chat_id}, ['chat_id', field_name]) assert result[field_name] == data
def test_get_database(): db1 = get_database() db2 = get_database() assert db1 is not None assert db1 == db2
async def close_mongo_connection(): database.get_database().close()
import json</br>from collections import defaultdict\nfrom http import HTTPStatus\nimport pymongo as pymongo\nimport urllib.parse\nimport logging\nimport requests\nfrom pymongo import database, MongoClient\n\nerror_codes = {\n\n 1003: \"Connection Not Established\",\n 1006: \"id required\",\n 1007: \"No record exists with this id\",\n\n}\n\ndef error_response(error_code, http_status):\n return {\n \"body\": {\n \"code\": error_code,\n \"message\": error_codes.get(error_code),\n \"data\": {}\n },\n \"statusCode\": http_status,\n \"headers\": {'Content-Type': 'application/json'}\n }\n\ndef connectToMongo(args,collection):\n doc = args.get(\"__ow_headers\")\n mongo = doc.get(\"mongo\")\n mongo = mongo.split(\"=\")\n mongo = mongo.__getitem__(1)\n mongo_connect_url = mongo.split(\",\")\n mongo_connect_url = mongo_connect_url.__getitem__(0)\n try:\n database = pymongo.MongoClient(mongo_connect_url)\n except:\n return error_response(500, \"cannot connnect to mongodb\")\n database=database.get_database()\n connect=database[collection]\n return connect\n\ndef success_response(data, status_code):\n return {\n \"body\": {\n \"code\": 0,\n \"message\": \"Request Completed Successfully\",\n \"data\": data\n },\n \"statusCode\": status_code,\n \"headers\": {'Content-Type': 'application/json'}\n }\n\ndef main(args):\n collection=connectToMongo(args,\"ETL_analytics_farmSimulation\")\n data={}\n farm_id=str(args.get(\"FarmId\"))\n availableAttributes=[\"SoilMoisture\"]\n data[\"availableAttributes\"]=availableAttributes\n data[\"units\"]=[\"C\"]\n chartData=[]\n data[\"chartData\"]=chartData\n print(\"farmid=====\"+farm_id)\n time=collection.find({\"FarmId\":farm_id}).distinct(\"TimeStamp\")\n time.sort(reverse = True)\n time=time[0:120]\n time.sort()\n print(time)\n for i in time:\n for j in collection.find({\"FarmId\":farm_id,\"TimeStamp\":i}).limit(1):\n dic={}\n dic[\"SoilMoisture\"]=j.get(\"SoilMoisture\")\n dic[\"timestamp\"]=j.get(\"TimeStamp\")\n chartData.append(dic)\n return success_response(data, 200)
# except IOError as err: # print("Cannot open configuration: %s. Exiting" % (str(err))) # sys.exit(1) config = json.loads(""" { "database": { "host": "contextubot.cao16ctra0vs.us-east-1.rds.amazonaws.com", "user": "******", "passwd": "Ieleewoughahg6nabee9ahDeghooqu6D", "db": "ebdb" } } """) db_cls = get_database(config.get("database_type", None)) db = db_cls(**config.get("database", {})) # db.setup() def queryHash(hash, prefix = None): hash_ = '{:x}'.format(hash) # int(str(hash)) # print(hash_) r = np.array(list(db.query(hash_, prefix))) # print(r) if len(r) == 0: return r.astype(np.int32) else: return r.astype(np.int32)
def get_user(name): connection=get_database() record=connection.query('SELECT * FROM ${userstable} WHERE name = %s',name) A=record.fetchone() return User(*A)
from flask_cors import cross_origin from flask import current_app as app from flask import request, jsonify, Blueprint, send_file from multiprocessing import Queue from database import get_database import os import threading import shutil import util.helper_function as helper # Initialise blueprint for flask app bp = Blueprint("play2vec", __name__) # Create an instance of chosen database db = get_database(app.config["DATABASE"], app.config["SAVE_PATH"]) # Initialise queues for flask app build_queue = Queue() build_file_queue = Queue() build_prev_queue = Queue() train_queue = Queue() train_file_queue = Queue() train_prev_queue = Queue() gif_gen_queue = Queue() gif_file_queue = Queue() gif_gen_prev_queue = Queue()
def __init__(self, target, read_only=False, cache_size=None, profile_space=False): target = lfs.get_absolute_path(target) self.target = target self.read_only = read_only # Set timestamp self.timestamp = str(int(time() / 2)) # Load the config config = get_config(target) self.config = config load_modules(config) self.modules = config.get_value('modules') # Contact Email self.smtp_from = config.get_value('smtp-from') # Full-text indexing self.index_text = config.get_value('index-text', type=Boolean, default=True) # Accept cors self.accept_cors = config.get_value( 'accept-cors', type=Boolean, default=False) # Profile Memory if profile_space is True: import guppy.heapy.RM # The database if cache_size is None: cache_size = config.get_value('database-size') if ':' in cache_size: size_min, size_max = cache_size.split(':') else: size_min = size_max = cache_size size_min, size_max = int(size_min), int(size_max) read_only = read_only or config.get_value('database-readonly') database = get_database(target, size_min, size_max, read_only) self.database = database # Find out the root class root = get_root(database) # Load environment file root_file_path = inspect.getfile(root.__class__) environement_path = str(get_reference(root_file_path).resolve('environment.json')) if vfs.exists(environement_path): with open(environement_path, 'r') as f: data = f.read() self.environment = json.loads(data) # Init fake context context = get_fake_context(database, root.context_cls) context.server = self # Initialize access_log = '%s/log/access' % target super(Server, self).__init__(root, access_log=access_log) # Email service self.spool = lfs.resolve2(self.target, 'spool') spool_failed = '%s/failed' % self.spool if not lfs.exists(spool_failed): lfs.make_folder(spool_failed) # Configuration variables get_value = config.get_value self.smtp_host = get_value('smtp-host') self.smtp_login = get_value('smtp-login', default='').strip() self.smtp_password = get_value('smtp-password', default='').strip() # Email is sent asynchronously self.flush_spool() # Logging log_file = '%s/log/events' % target log_level = config.get_value('log-level') if log_level not in log_levels: msg = 'configuraion error, unexpected "%s" value for log-level' raise ValueError, msg % log_level log_level = log_levels[log_level] logger = Logger(log_file, log_level, rotate=timedelta(weeks=3)) register_logger(logger, None) logger = WebLogger(log_file, log_level) register_logger(logger, 'itools.web') # Session timeout self.session_timeout = get_value('session-timeout') # Register routes self.register_dispatch_routes()
''' Requires ipv4scan: https://github.com/wybiral/ipv4scan To use you'll need to pipe the scan results from ipv4scan into this script: ipv4scan -n 500 | python3 collect.py This script will read the output from stdin and copy them into the dex sqlite3 database to show up in search results. ''' from json import loads from sys import stdin from database import get_database db = get_database() for line in stdin: x = loads(line) host = x['ip'] port = x['port'] lines = x['headers'].split('\r\n') print('{}:{}'.format(host, port)) db.insert(host, port, lines)
size_of_array = len(array) - 1 rand = random.randint(0, size_of_array) return array[rand] def remove_user(person_ID, origianl_list): list = [] for member in origianl_list: if member[1] is not person_ID: list.append(member) return list db = database.get_database('database.db') santas = user.get_from_family(db, 3) santas = santas + user.get_from_family(db, 2) shuffle(santas) recipients = santas shuffle(recipients) for santa in santas: pair_found = False i = 0 while not pair_found: i += 1 possible_pair = select_random_user(recipients) if possible_pair[3] != santa[3] or (i > 250
import sys from rooms import room_menu from customers import customer_menu from myprint import print_center, input_center from database import get_database if __name__ == '__main__': database, cursor = get_database() if database is None: print("The Database does not exist or not accessible.") sys.exit(1) while True: print() print_center("==============================") print_center("=====Apka Guruji Hotels=====") print_center("==============================") print_center("1. Manage Rooms") print_center("2. Manage Customers") print_center("0. Exit") print() choice = int(input_center("Enter your choice: ")) if choice == 1: room_menu(database, cursor) elif choice == 2: customer_menu(database, cursor) elif choice == 0: break else: print("Invalid choice (Press 0 to exit)") print_center("GoodBye")
from app_config import set_config from database import get_database from app_helper_functions import vectorElem, readDynamicForm from forms import * from render_primitives.Vector import Vector from render_primitives.Sphere import Sphere from render_primitives.Triangle import Triangle from render_primitives.PointLight import PointLight from render_primitives.Screen2D import Screen2D from render_primitives.RayTracer import RayTracer # create a Flask instance and initialize the flask application app = Flask(__name__) socketio, celery = set_config(app) db, Users, UserImage = get_database(app) Bootstrap(app) class Anonymous(AnonymousUserMixin): """ Anonymous class inherits from AnonymousUserMixin. When no user is logged_in, the current user will be an instance of Ananymous class which has a username property with the value 'Guest'. """ def __init__(self): self.username = '******' #LoginManager contains the code which lets the application and Flask-Login work together(like how #to load a user from an ID) login_manager = LoginManager()
def _collect(self, queue): db = get_database() while True: host, lines = queue.get() if lines: db.insert(host, lines)
import os import sys from flask import Flask, render_template, request from werkzeug import secure_filename import jinja2 import json import database from secret_constants import PASSWORD, ADMIN_PASSWORD THIS_DIR = os.path.dirname(os.path.abspath(__file__)) PHOTOS_DIR = 'static/uploads/photos' ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'bmp']) app = Flask(__name__) db = database.get_database() def file_ext(filename): return filename.rsplit('.', 1)[1] def allowed_file(filename): return '.' in filename and \ file_ext(filename) in ALLOWED_EXTENSIONS def next_counter(): filenames = os.listdir(os.path.join(THIS_DIR, PHOTOS_DIR)) biggest = max([int(x.split('.')[0]) for x in filenames]) return biggest + 1 @app.route('/') def home():
def create_server(target, email, password, root, backend='git', modules=None, listen_port='8080', smtp_host='localhost', log_email=None, website_languages=None): modules = modules or [] # Get modules for module in modules: exec('import %s' % module) # Load the root class if root is None: root_class = Root else: modules.insert(0, root) exec('import %s' % root) exec('root_class = %s.Root' % root) # Make folder try: mkdir(target) except OSError: raise ValueError('can not create the instance (check permissions)') # The configuration file config = template.format( modules=" ".join(modules), listen_port=listen_port or '8080', smtp_host=smtp_host or 'localhost', smtp_from=email, log_email=log_email) open('%s/config.conf' % target, 'w').write(config) # Create database size_min, size_max = 19500, 20500 database = make_database(target, size_min, size_max, backend=backend) database.close() database = get_database(target, size_min, size_max, backend=backend) # Create the folder structure mkdir('%s/log' % target) mkdir('%s/spool' % target) # Make the root with database.init_context() as context: metadata = Metadata(cls=root_class) database.set_handler('.metadata', metadata) root = root_class(abspath=Path('/'), database=database, metadata=metadata) # Language language_field = root_class.get_field('website_languages') website_languages = website_languages or language_field.default root.set_value('website_languages', website_languages) context.database.save_changes() # Re-init context with context cls with database.init_context() as context: # Init root resource root.init_resource(email, password) # Set mtime root.set_property('mtime', context.timestamp) # Save changes database.save_changes('Initial commit') database.close() # Empty context set_context(None)
import jsonfrom collections \n import defaultdictfrom http import HTTPStatusimport pymongo as pymongofrom elasticsearch import Elasticsearchimport paho.mqtt.client as mqttClientimport urllib.parseimport loggingimport requestsfrom pymongo import database, MongoClienterror_codes = { 1003: "Connection Not Established", 1006: "id required", 1007: "No record exists with this id",}def error_response(http_status, message_code): data=[] data.append(error_codes.get(message_code)) return { "body": { "code": http_status, "message": "exception", "data": data }, "statusCode": http_status, "headers": {'Content-Type': 'application/json'} }def success_response(data, status_code): return { "body": { "code": 0, "message": "Request Completed Successfully", "data": data }, "statusCode": status_code, "headers": {'Content-Type': 'application/json'} }def connectToElastic(args): headers=args.get("__ow_headers") url=headers.get("elastic_url") try: es = Elasticsearch(url) logging.info("Connection Established") except Exception as ex: logging.info("Cannot connect to Elastic Search" ex) return esdef connectToMqtt(args): mqtt = args.get("__ow_headers").get("mqtt") mqtt=mqtt.split(",") user=mqtt.__getitem__(0) password=mqtt.__getitem__(1) broker=mqtt.__getitem__(2) port=int(mqtt.__getitem__(3)) mqtt_client = mqttClient.Client() mqtt_client.username_pw_set(user, password=password) mqtt_client.connect(broker, port=port) mqtt_client.loop_start() return mqtt_clientdef connectToMongo(args,collection): doc = args.get("__ow_headers") mongo = doc.get("mongo") mongo = mongo.split("=") mongo = mongo.__getitem__(1) mongo_connect_url = mongo.split(",") mongo_connect_url = mongo_connect_url.__getitem__(0) try: database = pymongo.MongoClient(mongo_connect_url) except: return error_response(500, "cannot connnect to mongodb") database=database.get_database() connect=database[collection] return connectdef main(args): data= [ { "category": "Floor 1", "value": 320 }, { "category": "Floor 2", "value": 220 }, { "category": "Floor 3", "value": 300 }, { "category": "Floor 4", "value": 150 }, { "category": "Floor 5", "value": 275 } ] return success_response(data, 200)
def __init__(self, content=None, user=None): self.connection = get_database() self.content = content self.user = user
import uuid import flask import time from flask import request, redirect, render_template, Flask from validate_email import validate_email import database import interest import santa import session import user app = Flask(__name__) # FIXME db = database.get_database("database.db") @app.route('/') def home(): cookie_secret = request.cookies.get('user_secret') user_id = session.get_session(cookie_secret, db) if user_id is not None: email = user.get_email(user_id, db).strip() first_name = user.get_name(email, db) if first_name is not None: recipient_email = santa.get_recipient(email, db) recipient_name = user.get_name(recipient_email, db) recipient_last_name = user.get_last_name(recipient_email, db) if recipient_name is not None and recipient_last_name is not None: recipient_name = recipient_name + " " + recipient_last_name
parser = ArgumentParser( description='Web server for mushroom gathering data collection', epilog='Easy config setup advice: copy and modify existing .json to config.json') parser.add_argument('-c', '--config', help='Load configuration from alternate file', default='config.json') parser.add_argument('-r','--reload', help='Reload db from schema and exit', action='store_true') args = parser.parse_args() # Read config import json with open(args.config) as config_file: config = json.loads(config_file.read()) # Database initialization from database import get_database app.db = get_database(config) if args.reload: app.db.reinitialize() quit() # Run server app.secret_key = 'development key' params = { 'debug': config.get('debug', False), 'port': config.get('port', 5000) } app.run(**params)