def connect_to_db(self): connect_to_db() register_connection(DB_BACKTEST, db=DB_BACKTEST, name=DB_BACKTEST, host=MONGO_HOST, port=MONGO_PORT)
def __init__(self, transaction_tag): connect_to_db(DB_BACKTEST) register_connection(DB_BACKTEST, db=DB_BACKTEST, name=DB_BACKTEST, host=MONGO_HOST, port=MONGO_PORT) self.transaction_tag = transaction_tag self.transactions = Transaction.objects.filter( tag=self.transaction_tag) self.amount = 1000
def run(): try: connect_to_db() except Error: log.error(Error.message) exit(1) api = ApiWorker() api.start() while True: time.sleep(_ONE_DAY_IN_SECONDS)
def post_predict(): database_engine, cursor = connect_to_db(db_user, db_password, db_url, db_schema) file_list = glob.glob('models/*') if len(file_list) != 1: logger.warning('strange number of models') model_file = file_list[0] if '.pkl' in model_file: clf = Model_sklearn() json_data_dict = request.get_json(force=True) # After parsing, access it like any other dictionary features = json_data_dict['features'] start = time.time() predictions = clf.predict(model_file, features).tolist()[0] logger.info(predictions) end = time.time() response_time = round((end - start) * 1000, 2) insert_model_stats( response_time, model_file.split('/')[-1], round(predictions, 3), database_engine, cursor, lambda_name ) database_engine.close() return {'predictions': predictions}
def main(): db = database.connect_to_db() properties = db.properties try: DataPreparationService.clean_data(properties) print('Data has been cleaned successfully') except Exception as e: print('Error to prepare and clean data: ', e)
def add_item_write_to_db(what, val, table, added_item): connection = database.connect_to_db() while True: if what == "Product": try: added_val = float(input(f'Please enter the {val} of the {added_item} you wish to add...')) database.execute_sql_crud(connection, f'INSERT INTO products (product_name, product_price) VALUES ("{added_item}", {added_val})') except ValueError: print("You have not entered a price, please try again...") continue elif what == "Courier": added_number = validate_number('courier') database.execute_sql_crud(connection, f'INSERT INTO couriers (courier_name, courier_number) VALUES ("{added_item}", "{added_number}")') break
def get_application() -> FastAPI: application = FastAPI() application.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]) application.add_event_handler("startup", connect_to_db(application)) application.add_event_handler("shutdown", close_db_connection(application)) application.include_router(authentication.router, prefix="/auth") application.include_router(notes.router, prefix="/notes") return application
def report_4(): # Report to show the customer name, address, for orders cancelled connection = connect_to_db() app_header("Cancelled Orders") results = execute_sql_select(connection, (f'SELECT customer_name, customer_address, order_status from orders where order_status = "Order Cancelled"')) name = [] address = [] order_status = [] for row in results: name.append(row[0]) for row in results: address.append(row[1]) for row in results: order_status.append(row[2]) report_table(name, address, order_status)
def report_2(): # Report to show the customer name, address, for orders not yet delivered connection = connect_to_db() app_header("Orders yet to be delivered...") results = execute_sql_select(connection, (f'SELECT customer_name, customer_address, order_status from orders where order_status = "Order Received" or order_status = "Order Preparing"')) name = [] address = [] order_status = [] for row in results: name.append(row[0]) for row in results: address.append(row[1]) for row in results: order_status.append(row[2]) report_table(name, address, order_status)
def replace_item_write_to_db(connection, what, val, table, item_to_replace): connection = connect_to_db() while True: if what == "Product": new_product = input("Please enter the product you wish to add to the menu...").title() new_product_price = float(input(f"Please enter the price for the {new_product}... £")) execute_sql_crud(connection, (f'UPDATE products SET product_name = "{new_product}" WHERE products_id = {item_to_replace}')) execute_sql_crud(connection, (f'UPDATE products SET product_price = {new_product_price} WHERE products_id = {item_to_replace}')) break elif what == "Courier": new_courier = input("Please enter the name of the courier you wish to add to the roster...") new_courier_number = validate_number('courier') execute_sql_crud(connection, (f'UPDATE {table} SET courier_name = "{new_courier}" WHERE couriers_id = {item_to_replace}')) execute_sql_crud(connection, (f'UPDATE {table} SET courier_number = "{new_courier_number}" WHERE couriers_id = {item_to_replace}')) connection.close() break
def read_from_database(table): connection = connect_to_db() result = [] cursor = connection.cursor() cursor.execute(f"SELECT * FROM {table}") rows = cursor.fetchall() field_names = [i[0] for i in cursor.description] for row in rows: outerdict = {} j = 0 for x in row: outerdict[field_names[j]] = x j += 1 result.append(outerdict) cursor.close() connection.close() return result
def menu(what, val, table): while True: connection = connect_to_db() start_option = input(f"""Please select from the following options: 0) Return to Main Menu 1) Print Out {what} List 2) Create {what} 3) Update {what} {val} 4) Replace {what} 5) Delete {what} 6) Exit App """) if start_option == "0": app_header("Main Screen") start_app() elif start_option == "1": print_from_db_menu(table) return_option(connection, what, val, table) elif start_option == "2": add_item_to_db(connection, what, val, table) return_option(connection, what, val, table) elif start_option == "3": update_item_sub_menu(what, val, table) elif start_option == "4": replace_item_in_db(connection, what, val, table) app_header(what) menu(what, val, table) elif start_option == "5": delete_row(connection, what, val, table) return_option(connection, what, val, table) elif start_option == "6": exit_app() else: app_header(f"{what} Screen") print("You made an incorrect selection, please try again... \n") connection.close
def add_order(connection, what, val, table): while True: connection = connect_to_db() app_header("Create New Order") cust_name = input(f"Please enter the customer's name...\n \nPlease press 0 if you wish to return to the previous menu...") if cust_name == "0": break else: cust_address = input("Please enter the customer's address...").title() cust_num = validate_number('customer') courier = assign_courier_to_order(connection) cour=courier[0] status = 'Order Received' products_to_add = assign_products_to_order(connection) execute_sql_crud(connection, (f' INSERT INTO orders (customer_name, customer_address, phone_number, order_status, courier_assigned) VALUES ("{cust_name}", "{cust_address}", "{cust_num}", "{status}", "{cour}")')) order_id = execute_sql_select_('SELECT MAX(orders_id) from orders')[0][0] for product in products_to_add: execute_sql_crud(connection,(f" INSERT INTO order_product (order_id, product_id) VALUES ('{order_id}', '{product}')")) break
def update_item_write_to_db(what, val, table, update_item): connection = connect_to_db() while True: if what == "Product": try: new_price = float(input(f'Please enter the new price for the product {update_item}... £')) except ValueError: print("You have not entered a price, please try again...") continue else: execute_sql_crud(connection, (f'UPDATE products SET product_price = {new_price} WHERE products_id = {update_item}')) elif what == "Courier": added_number = validate_number('courier') execute_sql_crud(connection, (f'UPDATE {table} SET courier_number = "{added_number}" WHERE couriers_id = {update_item}')) elif what == "Order": updated_status = choose_order_status() execute_sql_crud(connection, (f'UPDATE {table} SET order_status = "{updated_status}" WHERE orders_id ={update_item}')) connection.close() break
def report_5(): connection = connect_to_db() o_status = execute_sql_select(connection, ('SELECT order_status FROM orders')) counts = Counter(x[0] for x in o_status) d = (counts['Order Delivered']) r = (counts['Order R c = (counts['Order Canceleceived'])led']) p = (counts['Order Preparing']) labels = 'Orders Received', 'Orders Preparing', 'Orders Delivered', 'Orders Cancelled' sizes = [r, p, d, c] fig1, ax1 = plt.subplots() ax1.pie(sizes, labels=labels, autopct='%1.0f%%', shadow=False, startangle=90) ax1.axis('equal') plt.title("Pie Chart showing status of all orders (%)") plt.show()
def report_1(table): # Report to show the customer name, address and list of products in an order. connection = connect_to_db() existing_order_ids = [orders_id[0] for orders_id in execute_sql_select(connection, ('SELECT orders_id from orders'))] app_header("Reporting Screen") print_from_db_menu(table) while True: id = input("Please choose an order from the list above...") if int(id) in existing_order_ids: results = execute_sql_select(connection, (f'SELECT o.customer_name, o.customer_address, p.product_name from order_product op join orders o on op.order_id = o.orders_id join products p on op.product_id = p.products_id where o.orders_id = {id}')) name = results[0][0] address = results[0][1] products = [] for row in results: products.append(row[2]) app_header(f"{name}'s Order") print(f''' Customer Name *|---------------------------|* {name} *|---------------------------|* Customer Address *|---------------------------|* {address} *|---------------------------|* Ordered Items *|---------------------------|*''') for x in products: print(" ",x) print(" *|---------------------------|*") print() print() break else: print("Please enter a valid ID from the above list...")
def report_6(): connection = connect_to_db() o_courier_assigned = execute_sql_select(connection, ('SELECT courier_assigned FROM orders')) o_courier_names = execute_sql_select(connection, ('SELECT courier_name FROM couriers')) counts = Counter(x[0] for x in o_courier_assigned) no_of_deliveries = list(counts.values()) name_list = [] for name in o_courier_names: name_list.append(name[0]) plt.bar(name_list, no_of_deliveries, color ='maroon', width = 0.4) yint = range(min(no_of_deliveries), math.ceil(max(no_of_deliveries))+1) plt.yticks(yint) plt.xlabel("COURIER NAMES") plt.ylabel("NO OF DELIVERIES ASSIGNED") plt.title("Number of Deliveries Assigned per Courier") plt.show()
def application(environ, start_response): connection, cursor = database.connect_to_db() query = parse_qs(environ['QUERY_STRING']) url = "" if "url" in query: url = query["url"][0] # assume one url as input # TODO: call database to check if the user of the tweet is already in the database and, # if not, to insert the user. Check also whether the tweet is already in the # database and, if not, insert the tweet into the database. # TODO: Reload list of recently entered users/tweets. response_body = website.startpage(cursor, url).encode('utf-8') status = '200 OK' response_headers = [('Content-Type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, response_headers) return [response_body]
def __init__(self): connect_to_db(alias=DB_BACKTEST)
def __init__(self): connect_to_db()
def create_json(json_data): json_file = json.loads(json.dumps(json_data, indent=4, ensure_ascii=False)) db = database.connect_to_db() database.insert_document(db, json_file)
import utilities import database as db from flask import Flask, request, jsonify app = Flask(__name__) DB_CON = db.connect_to_db() @app.route("/cs/observation", methods=['POST']) def new_data(): point = request.args.get('point', None) place = request.args.get('place', None) data_note = "" observer = request.args.get('observer', 'anon') obs_type = request.args.get('obs_type', 'REST') temp = request.args.get('temp') if not utilities.is_float(temp): return "No valid temperature provided" if point is None and place is not None: point = utilities.coord_from_str(place) data_note = f"point extrapolated from: {place}" if point is None: return "No location information provided" elif isinstance(point, str) and place is None: p = point.split(',')
}).previous_sibling.previous_sibling.previous_sibling description = description.get_text().strip() except AttributeError: description = None return description baseUrl = "https://expanse.fandom.com" soup = get_page("/wiki/Characters_(TV)") tables = soup.find_all("div", attrs={'class': 'floatnone'}) # make connection to db connection = connect_to_db() # loop through each link, retreive the data and add to db for table in tables: if (table.a['href'] == "/wiki/Characters_(TV)" or table.a['href'] == "/wiki/Menacing_Belter_#2"): continue else: html = get_page(table.a['href']) name = get_char_name(html) status = get_char_status(html) gender = get_char_gender(html) desc = get_char_desc(html) if name is not None:
mood_id=mood_id, user_id=session["user_id"]).limit(10).all()) mood = Mood.query.get(mood_id) verbose_mood = mood.verbose_mood activities = [] for entry in entries: for activity in entry.activities: activities.append(activity.verbose_category) return render_template( "show-mood.html", verbose_mood=verbose_mood, activities=set(activities), user=user, ) if __name__ == "__main__": # We have to set debug=True here, since it has to be True at the # point that we invoke the DebugToolbarExtension app.debug = True # make sure templates, etc. are not cached in debug mode app.jinja_env.autoreload = app.debug connect_to_db(app) # Use the DebugToolbar # DebugToolbarExtension(app) app.run(port=5000, host="0.0.0.0")