def createRoutes(self): airports = session.query(Airport).all() routes = [] while (len(airports) != 0): origin = airports[0] airports.remove(airports[0]) for dest in airports: dist = calcDistanceKm(origin.geom, dest.geom) try: session.query(Route).filter_by( origin=origin.iata, destination=dest.iata).one() except NoResultFound: r1 = Route(origin=origin.iata, destination=dest.iata, distance=dist) session.add(r1) routes.append(r1) try: session.query(Route).filter_by( origin=dest.iata, destination=origin.iata).one() except NoResultFound: r2 = Route(origin=dest.iata, destination=origin.iata, distance=dist) session.add(r2) routes.append(r2) session.commit() return routes
def put(self, id): data = request.json try: user = session.query(User).get(id) if "username" in data: user.username = data["username"] if "first_name" in data: user.first_name = data["first_name"] if "last_name" in data: user.last_name = data["last_name"] if "email" in data: user.email = data["email"] if "password" in data: user.password = data["password"] if "groups" in data: session.query(Invited).filter( Invited.user_id == user.id).delete() for group in data["groups"]: invited = Invited(user.id, group) session.add(invited) session.commit() return Response(response=json.dumps({"message": "Success"}), status=200, mimetype="application/json") except Exception as e: return Response(response=json.dumps({"message": "Invalid input"}), status=405, mimetype="application/json")
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session[ 'email'], picture=login_session['picture']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def import_targets(): from app.models.target import Target with open('nutritionTablesReformatted.csv', 'rU') as csvfile: reader = csv.reader(csvfile, delimiter=',') #to skip the first row in the csv file containing headings reader.next() for row in reader: #create a new line in the database using sqlalchemy #instantiate in instance of the model, add it and commit target = Target() target.group = row[0] target.lower_age = float(row[1]) target.upper_age = float(row[2]) target.nutrient_no = row[3] if row[4] == "": target.value = None else: target.value = row[4] if row[5] == "": target.upper_limit = None else: target.upper_limit = row[5] session.add(target) session.commit()
def createPricelist(): if 'username' not in login_session: return redirect('/oauth/login') else: pass if request.method == 'POST': ### begin custom logic for form ### if request.form['communicated'] == '': communicated = datetime.datetime.now() else: communicated = datetime.datetime.strptime(request.form['communicated'], '%Y-%m-%d') if request.form['vigente'] == 'True': vigente = True else: vigente = False ### end custom logic for form ### user_id = getUserID(login_session['email']) newItem = PriceList(name= request.form['name'], communicated= communicated, user_id= user_id, vigente= vigente, moneda= request.form['moneda'], incoterm= request.form['incoterm']) session.add(newItem) session.commit() flash("new price list created!") return redirect(url_for('pxlst.readPricelists')) else: return render_template('pxlst/createPricelist.html')
def login(): form = RequestForm() if form.validate_on_submit(): user = session.query(User).filter_by(email=form.email.data).first() if user: return render_template( 'auth.html', result='User with email {} already exist'.format( form.email.data) ) user = User(email=form.email.data) session.add(user) invoice = SignInRequest( email=form.email.data, token=str(uuid.uuid4()), ip=request.remote_addr, expired=datetime.now() + timedelta(days=30) ) session.add(invoice) sender = Email() sender.send( EMAIL_FROM, invoice.email, 'ACTIVATION', '<a>http://127.0.0.1:5000/invoice/{}</a>'.format(invoice.token) ) session.commit() return render_template( 'auth.html', result='Get auth link on {}'.format(form.email.data) ) return render_template('index.html', form=form)
def createSku(price_list_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass if request.method == 'POST': price = int(request.form.get('price')) if request.form.get('price2'): price2 = int(request.form.get('price2')) pxlist = price_list_id user_id = getUserID(login_session['email']) newSku = Sku(name = request.form['name'], varietal = request.form['varietal'], price = price, price2 = price2, price_list_id=pxlist, user_id=user_id) session.add(newSku) session.commit() flash('new sku item created!') return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) pxlist = session.query(PriceList).filter_by(id=price_list_id).one() #protection from non creator if login_session['username'] != pxlist.user.name: flash("Debes ser el creador de la lista para crear un nuevo Sku.") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) else: return render_template('pxlst/createSku.html', price_list_id=price_list_id)
def upload_csv(f): result = check_csv(f) if not isinstance(f, FileStorage): f = open(f) if result != "OK": return result ctr = 0 lines = f.readlines() lines = [l.decode('utf-8') for l in lines] print(lines) for line in lines: line = line.strip() if line == "": pass data = line.split(";") if data[0].strip() not in users: ctr += 1 users[data[0]] = ctr user = User(data[0]) session.add(user) try: ts = datetime.strptime(data[3] + " " + data[4], "%d/%m/%Y %H:%M:%S") print("Timestamp is :", ts) except ValueError: continue user_id = users[data[0]] location = Location(data[1], data[2], ts, user_id) print(location) session.add(location) session.flush() f.close() return "OK"
def fill_gender(): try: session.add(Gender(name="Male")) session.add(Gender(name="Female")) session.commit() except: session.rollback()
def adicionar_pedido_pj(): cliente_pj = session.query(tbl_pessoa_juridica).order_by( tbl_pessoa_juridica.razao_social).all() status_list = session.query(tbl_status_pedido).order_by( tbl_status_pedido.id_status).all() if request.method == 'POST': # tbl_pedido cod_cliente = request.form['cod_cliente'] mod_pgto = request.form['mod_pgto'] cod_status = request.form['cod_status'] desconto = 0 pedido = tbl_pedido(data_pedido=datetime.now(), cod_cliente=cod_cliente, desconto=desconto, cod_status=cod_status, mod_pgto=mod_pgto) session.add(pedido) session.commit() session.close() return redirect(url_for('admin_pedido')) session.close() return render_template('adicionar_pedido_pj.html', cliente_pj=cliente_pj, status_list=status_list)
def fill_db(): form = LocationForm() print(form.user_id.data) if form.validate_on_submit(): location = Location(lat=form.lat.data, lan=form.lan.data, timestamp=form.timestamp.data, user_id=form.user_id.data) session.add(location) session.flush() return redirect("/") # if request.method == 'POST': # lat = request.form['lat'] # lan = request.form['lan'] # timestamp = request.form['timestamp'] # user_id = request.form['user_id'] # print(timestamp) # ts = datetime.strptime(timestamp, "%Y-%m-%d") # location = Location(lat, lan, ts, user_id) # session.add(location) # session.flush() # return redirect("/") else: users = session.query(User).all() return render_template('add_location.html', users=users, form=form)
def adicionar_item_pedido(): produto_list = session.query(tbl_produto).order_by( tbl_produto.nome_produto).all() tb_ped = session.query(tbl_pedido).order_by(tbl_pedido.id_pedido).all() id = request.form.get('cod_produto') tb_prod = session.get(tbl_produto, id) print(id) if request.method == 'POST': # tbl_item quantidade_venda = request.form['quantidade_venda'] quantidade_venda = int(quantidade_venda) valor_unitario = request.form['id_valor_unitario'] valor_unitario = float(valor_unitario) cod_produto = request.form['id_cod_produto'] cod_pedido = request.form['id_pedido'] itens = tbl_item(quantidade_venda=quantidade_venda, valor_unitario=valor_unitario, cod_produto=cod_produto, cod_pedido=cod_pedido) session.add(itens) session.commit() session.close() return redirect(url_for('admin_pedido')) session.close() return render_template('adicionar_item_pedido.html', tb_ped=tb_ped, tb_prod=tb_prod, produto_list=produto_list)
def register(): form = RegistrationForm(request.form) print form.validate() print form.errors if request.method == 'POST' and form.validate(): user = User(form.username.data, form.email.data, form.password.data) session.add(user) try: session.commit() except IntegrityError as error: flash("Registration is unsucessful. A user with the same username or email address is already in use.") print error session.rollback() return render_template( 'register.html', title="Register", form=form ) flash("Registration is successful.") return redirect(url_for('login')) return render_template( 'register.html', title="Register", form=form )
def grabarArticulos(fichero, almacen): with open(fichero, 'r') as f: datos_json = json.load(f) i = 0 for json_item in datos_json: #articulo = Articulo() articulo = Articulo( codigo=json_item["codigo"], nombre=json_item["nombre"], familia=json_item["familia"], formato=json_item["formato"], fechaFabricacion=json_item["fechaFabricacion"], fechaCaducidad=json_item["fechaCaducidad"], loteProveedor=json_item["loteProveedor"], udm=json_item["udm"], stock=json_item["stock"], cantidadFabricada=json_item["cantidadFabricada"], fechaPrimeraVenta=json_item["fechaPrimeraVenta"], fechaUltimaVenta=json_item["fechaUltimaVenta"]) articulo.almacen = almacen #for k, v in json_item.items(): #print(k) #print(v) #articulo.k = v i += 1 print(i) session.add(articulo) session.commit()
def updateSku(price_list_id, sku_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass sku = session.query(Sku).filter_by(id=sku_id).one() if request.method == 'POST': if request.form.get('name'): sku.name = request.form['name'] if request.form.get('varietal'): sku.varietal = request.form['varietal'] if request.form.get('price'): sku.price = int(request.form['price']) if request.form.get('price2'): sku.price2 = int(request.form['price2']) session.add(sku) session.commit() print 'sku commited' flash("sku editado!") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) #protection from non creator if login_session['username'] != sku.user.name: flash("Debes ser el creador de la lista para editar este Sku.") return redirect(url_for('pxlst.readSkus', price_list_id=price_list_id)) else: return render_template('pxlst/updateSku.html', price_list_id=price_list_id, sku_id=sku_id, sku=sku)
def updatePricelist(price_list_id): if 'username' not in login_session: return redirect('/oauth/login') else: pass item = session.query(PriceList).filter_by(id=price_list_id).one() if request.method == 'POST': if request.form.get('name'): item.name = request.form['name'] if request.form.get('communicated'): item.communicated = datetime.datetime.strptime(request.form['communicated'], '%Y-%m-%d') if request.form['vigente'] == 'True': item.vigente = True else: item.vigente = False session.add(item) session.commit() flash("lista de precios editada!") return redirect(url_for('pxlst.readPricelists')) #protection from non creator if login_session['username'] != item.user.name: flash("Debes ser el creador de la lista para editarla.") return redirect(url_for('pxlst.readPricelists')) else: return render_template('pxlst/updatePricelist.html', price_list_id=price_list_id, item=item)
def create(name='Void', commit=True): plane = Plane(name=name) plane.create_origin() session.add(plane) if commit: session.commit() return plane
def add_host(): if not request.json: abort(400) else: data = request.json old_nodes = session.query( models.Node).filter_by(management_ip=data.get('management_ip')).all() if len(old_nodes) != 0: return {"status": "Node da ton tai"} node = models.Node(created_at=datetime.now(), updated_at=datetime.now(), deleted_at=None, management_ip=data.get('management_ip', ""), ssh_user=data.get('ssh_user', ""), ssh_password=data.get('ssh_password', ""), status="set_ip", node_display_name=data.get('node_display_name', '')) session.add(node) session.commit() new_node = session.query(models.Node).filter_by( node_display_name=str(data.get('node_display_name', ''))).all() #print(models.to_json(new_node, 'Node',True)) return jsonify(models.to_json(new_node, 'Node', True)), 201
def apostile_create_post(): count = session.query(Apostile).filter(Apostile.number == int(request.form['number'])).count() if count: return render_template('message.html', title='Помилка', msg=f'Апостиль з номером {request.form["number"]} уже існує', **user_config()) doc = Document( country=request.form['country'], date=request.form['doc_date'], author_name=request.form['person_name'], author_info=request.form['person_position'], stamp_info=request.form['stamp_info'] if request.form['stamp_info'] else '-/-/-' ) session.add(doc) session.flush() tr_id, tr_type = find_trusted_by_str(request.form['ap_author']) ap = Apostile( number=int(request.form['number']), date=request.form['ap_date'], is_archived=False, trusted_id=tr_id, trusted_type=tr_type, document_id=doc.id ) session.add(ap) session.flush() session.commit() return redirect(f'/apostile/{ap.id}')
def test_code_create_service_setup(): with open('static/role_service.json') as role_data_file: role_data = json.load(role_data_file) nodes = session.query(models.Node).all() for node in nodes: deployment = node.deployment if deployment is not None: roles = [role.role_name for role in node.node_roles] for role in roles: list_services = role_data[role]['list_service'] for service in list_services: service_setup = models.Service_setup( service_type=role, service_name=service['service_name'], enable="ENABLE", service_lib=None, service_config_folder=None, setup_index=service['index'], is_validated_success=None, validated_status=None) deployment.service_setups.append(service_setup) session.add(node) session.commit() session.close() return {"respone": "Done Add Service Setup to Database"}, 202
def storeStationsDB(self): stations_list = [] stations = pd.read_csv(PATH_STATIONS_FILE, sep=';') for i in range(0, len(stations)): lat = stations.iloc[i]['Latitude'].split(':')[1].strip() lon = stations.iloc[i]['Longitude'].split(':')[1].strip() coord = 'SRID=4674;POINT({lon} {lat})'.format(lat=lat, lon=lon) omm = stations.iloc[i]['Estacao'].split('OMM:')[1].replace( ')', '').strip() name = stations.iloc[i]['Estacao'].split(' : ')[1].split( '-')[0].strip() estate = stations.iloc[i]['Estacao'].split('-')[1].split( '(')[0].strip() altitude = stations.iloc[i]['Altitude'].split(':')[1].strip() station = Station(omm=omm, name=name, geom=coord, estate=estate, altitude=altitude) stations_list.append(station) session.add(station) session.commit()
def get_or_create_car_make(make_name): make = Make.query.filter_by(name=make_name).first() if not make: make = Make(name=make_name) session.add(make) session.commit() return make
def get_or_create_enginetype(engine_type_str): enginetype = EngineType.query.filter_by(name=engine_type_str).first() if not enginetype: enginetype = EngineType(name=engine_type_str) session.add(enginetype) session.commit() return enginetype
def food_log_post(): user = current_user quantity = request.form.get('quantity') unit = request.form.get('unit') unit = json.loads(unit) food_log = get_food_log(user) association = FoodLogFoodAssociation( food_NDB_No=unit["NDB_No"], unit_Seq=unit["Seq"], quantity=float(quantity) ) food_log.foods.append(association) #build the query favorite_query = session.query(FavoriteAssociation) favorite_query = favorite_query.filter_by(NDB_No=unit["NDB_No"], user_id=user.id) #executing the query favorite = favorite_query.first() if favorite == None: favorite = FavoriteAssociation( NDB_No=unit["NDB_No"], user_id=user.id, popularity=1 ) session.add(favorite) else: favorite.popularity += 1 session.commit() return redirect(url_for('food_log_get'))
def save(self): try: session.add(self) session.commit() except Exception: session.rollback() raise
def _save_instance(model, data): data_to_db = model(**data) session.add(data_to_db) session.flush() session.commit() return data_to_db
def book_ticket(**kwargs): user_id = get_jwt_identity() now_time = datetime.now() train_dep_time = session.query(Schedule).get( kwargs.get('schedule_id')).departure_time late_booking_limit = train_dep_time - timedelta(days=4) # late_booking_limit = train_dep_time - timedelta(days=4) if (late_booking_limit < now_time): print(train_dep_time) print(now_time) return make_response( {'msg': 'can no longer book tickets for this train.'}, 409) early_booking_limit = now_time + timedelta(days=30) book_end_date = min(early_booking_limit, late_booking_limit) print(book_end_date) print(kwargs.get('place')) ticket = Ticket(user_id=user_id, book_end_date=book_end_date, **kwargs) try: session.add(ticket) session.commit() except Exception as e: session.rollback() logger.warning(f'ticket booking failed with errors: {e}') return {'message': str(e)}, 400 return make_response({'msg': 'ticket succesfully booked'}, 200)
def add_text(): if 'text' not in request.json: return {'Error': 'No text provided to add'} news = News(text=request.json['text'], title=request.json['title']) session.add(news) session.commit() return {'Result': 'Success'}
def createUser(login_session): newUser = User(name=login_session['username'], email=login_session['email'], google_id=login_session['gplus_id']) session.add(newUser) session.commit() user = session.query(User).filter_by(email=login_session['email']).one() return user.id
def create_project(): """Create a project and return its ID""" projectData = request.get_json() # Remove placeholder ID projectData.pop('id') newProject = Project(**projectData) session.add(newProject) session.commit() return jsonify(ProjectJson(newProject)())
def get_food_log(user): food_log = session.query(FoodLog).filter_by(user=user).first() if food_log is None: food_log = FoodLog() food_log.user = user session.add(food_log) session.commit() return food_log
def add_user(): if request.method == 'POST': username = request.form['username'] user = User(username) session.add(user) session.flush() return redirect("/") else: return render_template("add_user.html")
def addthebot(subreddit, username, datestamp): imsged = WhoMSg( datestamp=datestamp, subreddit=subreddit, username=username, ) session.add(imsged) session.commit()
def addtodatabase(username): try: new_person = EbaySellers(username=username) session.add(new_person) session.commit() print("successfully committed") except Exception as e: print(str(e)) session.rollback()
def saved_meal_post(): #don't use the reequest.args.get('user') to avoid malicious user. user = current_user #request.args.get('meal_name') gets the value associated #with the query string 'meal_name' #ex: /add_saved_meal_post?meal_name=breakfast selected_foods = request.args.get('selected_foods') meal_name = request.args.get('meal_name') #think about keys and values. look at the flask documentation for requesting #keys and values. #do not use 'if not selected_foods' because the id of 0 evaluates to False. if selected_foods == None or selected_foods == "": return "" #need to first strip leading and trailing commas to create a clean and valid list #of strings separated by commas. selected_foods = selected_foods.strip(",").split(',') #create an instance of the Meal model #creating a Meal object by calling the Meal constructor. #can set any column values as identified in the models, in this case models/meal.py #creating a name for the saved_meal saved_meal = Meal(name=meal_name) #loop through the food_ids to save the selected foods as a meal. #selected_foods is a list. for food_id in selected_foods: #making an instance of the Class MealFoodAssociation meal_food_association = MealFoodAssociation() #query the FoodLogFoodAssociation table to get the row (the matching association) that has the specific #food_id. food_log_food_association = session.query(FoodLogFoodAssociation).get(int(food_id)) #access the attribute of the variable which is an instance of the class #copy the attributes from the food_log_food_association to the #attribute mealfoodassociation #integer primary keys are automatically filled in. meal_food_association.food_NDB_No = food_log_food_association.food_NDB_No meal_food_association.unit_Seq = food_log_food_association.unit_Seq meal_food_association.quantity = food_log_food_association.quantity #add the saved food to the Meal saved_meal.foods.append(meal_food_association) #append the saved _meal to the list user.meals #save it once. Take it out of the for loop. user.meals.append(saved_meal) #save the meal session.add(saved_meal) session.commit() #returning an empty string is saying that the code works. return ""
def parse_response(res): for item in res: updated_at = datetime.strptime(item.get('updated_at'), '%Y-%m-%dT%H:%M:%SZ') repo = Repo(item.get('name'), item.get('html_url'), item.get('description'), updated_at, item.get('stargazers_count'), item.get('watchers_count')) session.add(repo) session.commit() session.close()
def get_food_log(user, date=None): if date is None: date = datetime.date.today() food_log = session.query(FoodLog).filter_by(user=user, date=date).first() if food_log is None: food_log = FoodLog() food_log.user = user session.add(food_log) session.commit() return food_log
def grabarClientesSinComprobar(): with open('clientes.json', 'r') as f: clientes_json = json.load(f) for json_item in clientes_json: cliente = Cliente(codigo=json_item["codigo"], nombre=json_item["nombre"], agente=json_item["agente"]) session.add(cliente) ssession.commit()
def registration(): try: body: dict = request.json new_user: object = User(**body) session.add(new_user) session.commit() except Exception as e: logger.warning(f'users: - add user action failed with error: {e}') return {'message': str(e)}, 400 return new_user
def categoryCheck(form): ''' Checks if parsed category name exists, if not it creates one ''' category = session.query(Category).filter_by(name=form.category.data).first() if category == None: newCategory = Category(name=form.category.data, user_id=login_session['user_id']) session.add(newCategory) session.commit() category = session.query(Category).filter_by(name=form.category.data).first() return category
def test_db(): # INSERT if not session.query(exists().where(User.email == '*****@*****.**')).scalar(): u1 = User() u1.name = "Test user" u1.email = "*****@*****.**" a1 = Address() a1.street = "Str 123" a1.city = "City WTF" u1.address = a1 session.add(a1) session.add(u1) session.commit() # check if record exists in db: # print session.query(Address).filter_by(city='City WTF').count() # print bool( session.query(Address).filter_by(city='City WTF').count() ) # SELECT if session.query(exists().where(Address.city == 'City WTF')).scalar(): a2 = session.query(Address).filter_by(city='City WTF').first() print a2.city if bool(session.query(Address).filter_by(city='City WTF').count()): a2 = session.query(Address).filter_by(city='City WTF').first() print a2.city # UPDATE if session.query(exists().where(User.email == '*****@*****.**')).scalar(): session.query(User).filter_by(email='*****@*****.**').update({"nick": "a"}) session.commit() if session.query(exists().where(User.email == '*****@*****.**')).scalar(): u = session.query(User).filter_by(email='*****@*****.**').first() u.nick = "b" session.commit() # DELETE if session.query(exists().where(User.email == '*****@*****.**')).scalar(): session.query(User).filter_by(email='*****@*****.**').delete() session.commit() if session.query(exists().where(Address.city == 'City WTF')).scalar(): session.query(Address).filter_by(city='City WTF').delete() session.commit()
def get(self, user_name): user = session.query(User).filter(User.name == user_name).first() if user is None: logger.error('GET User "{}" not found in DB'.format(user_name)) return {'error': 'Specified user does not exist'}, 404 if user != g.user: logger.error('GET Auth user {} does not match specified user {}'.format(user, g.user)) return {'error': 'Authenticated user does not match specified user'}, 403 assert isinstance(user, User) logger.info('GET User {}; username {}'.format(user, user_name)) # Update when User last seen user.last_seen = datetime.utcnow() session.add(user) session.commit() return UserAPI.user_info(user)
def newCategory(): if 'username' not in login_session: return redirect(url_for('auth.showLogin')) if request.method == 'POST': if request.form['name']: newCategory = Category(name=request.form['name'], user_id=login_session['user_id']) session.add(newCategory) flash('New Category %s Successfully Created' % newCategory.name) session.commit() return redirect(url_for('catalog.showCatalog')) else: flash('Name is mandatory') return render_template('catalog/newcategory.html') else: return render_template('catalog/newcategory.html')
def saved_meal_post(): user = current_user selected_foods = request.args.get('selected_foods') #think about keys and values. look at the flask documentation for requesting #keys and values. snacks = request.args.get('snacks') if selected_foods == None: return "" #need to first strip leading and trailing commas to create a clean and valid list #of strings separated by commas. selected_foods = selected_foods.strip(",").split(',') #create an instance of the Meal model saved_meal = Meal() #loop through the food_ids to save the selected foods as a meal. #selected_foods is a list. for food_id in selected_foods: #making an instance of the Class MealFoodAssociation meal_food_association = MealFoodAssociation() #query the FoodLogFoodAssociation table to get the row (the matching association) that has the specific #food_id. food_log_food_association = session.query(FoodLogFoodAssociation).get(int(food_id)) #access the attribute of the variable which is an instance of the class #copy the attributes from the food_log_food_association to the #attribute mealfoodassociation #integer primary keys are automatically filled in. meal_food_association.food_NDB_No = food_log_food_association.food_NDB_No meal_food_association.unit_Seq = food_log_food_association.unit_Seq meal_food_association.quantity = food_log_food_association.quantity #add the saved food to the Meal saved_meal.foods.append(meal_food_association) #append the saved _meal to the list user.meals #save it once. Take it out of the for loop. user.meals.append(saved_meal) #save the meal session.add(saved_meal) session.commit() print "save_meal" print request.args.get('selected_foods') return ""
def on_post(self, req, resp): today = datetime.date.today() absent = req.get_param_as_list("absent") # req.log_error(" ".join(absent)) present = req.get_param_as_list("present") # req.log_error(" ".join(present)) for stid in absent: if sess.query(ms.Absence).get((stid, today)) is None: sess.add(ms.Absence(stid, today)) for stid in present: temp = sess.query(ms.Absence).get((stid, today)) if temp is not None: sess.delete(temp) sess.commit() resp.status = falcon.HTTP_200 resp.body = "Attendance Successfully Taken"
def on_post(self, req, resp): teacher_id = req.get_param("id") if sess.query(ms.Teacher).get(teacher_id) is None: resp.status = falcon.HTTP_409 resp.body = "That id is already taken" return first_name, last_name, room_id =\ req.get_param("first_name"), req.get_param("last_name"), req.get_param("room_id") if first_name is None or last_name is None or room_id is None: resp.status = falcon.HTTP_500 resp.body = "A first_name, last_name, and room_id are required." return teach = ms.Teacher(teacher_id, first_name, last_name, room_id) sess.add(teach) sess.commit() resp.status = falcon.HTTP_200 resp.body = json.dumps(teach.to_dict())
def newItem(): if 'username' not in login_session: return redirect(url_for('auth.showLogin')) categories = session.query(Category).order_by(asc(Category.name)) if request.method == 'POST': if request.form['name'] and request.form['description'] and request.form['category_id']: newItem = Item(name=request.form['name'], description=request.form['description'], category_id=request.form['category_id'], user_id=login_session['user_id']) session.add(newItem) session.commit() flash('New Item %s Successfully Created' % (newItem.name)) return redirect(url_for('catalog.showCatalog')) else: flash('All fields are mandatory') return render_template('items/newitem.html', categories=categories) else: return render_template('items/newitem.html', categories=categories)
def generate_mileage(): """Generate fixed mileage entries to be nullified in SQL if false""" description = 'IDC-Google 53 miles x 2 @ $.54/mile (2017)' contract = session.query(models.Contract).get(1664) employee = session.query(models.Employee).get(1479) mileage_cat = session.query(models.ExpenseCategory).get(2) startdate = dt.datetime(year=contract.startdate.year, month=contract.startdate.month, day=contract.startdate.day) delta = dt.datetime.now() - startdate for i in range(delta.days + 1): day = startdate + dt.timedelta(days=i) if day.weekday() in range(0, 5): exp_count = session.query(models.Expense).filter(models.Expense.category == mileage_cat, models.Expense.description == description, models.Expense.date == day).count() if exp_count == 0: exp = models.Expense(category=mileage_cat, description=description, amount=53 * 2 * .54, date=day, employee=employee) session.add(exp) session.commit()
def on_post(self, req, resp): stid = req.get_param("student_id") if stid is None: resp.status = falcon.HTTP_500 # May need to change this resp.body = "A valid student_id must be supplied." return tid = req.get_param("teacher_id") if tid is None: resp.status = falcon.HTTP_500 # May need to change this resp.body = "A valid teacher_id must be supplied." return date = req.get_param("date") date = datetime.datetime.strptime(date, "%Y-%m-%d").date() if sess.query(ms.Schedule).filter(student_id=stid, date=date).first() is None: resp.status = falcon.HTTP_409 resp.body = "A schedule already exists on this date." return sess.add(ms.Schedule(stid, tid, date)) sess.commit() resp.status = falcon.HTTP_200 resp.body = "Successfully Schedule Student"
def generate(self): """""" description = 'IDC-Google 53 miles x 2 @ $.54/mile (2017)' contract = session.query(models.Contract).get(1664) employee = session.query(models.Employee).get(1479) mileage_cat = session.query(models.ExpenseCategory).get(2) startdate = dt(year=contract.startdate.year, month=contract.startdate.month, day=contract.startdate.day) delta = dt.now() - startdate for i in range(delta.days + 1): day = startdate + td(days=i) if day.weekday() in range(0, 5): exp_count = session.query(models.Expense).filter(models.Expense.category == mileage_cat, models.Expense.description == description, models.Expense.date == day).count() if exp_count == 0: exp = models.Expense(category=mileage_cat, description=description, amount=53 * 2 * .54, date=day, employee=employee) session.add(exp) session.commit() self.root.iconify()
def editItem(item_name): if 'username' not in login_session: return redirect(url_for('auth.showLogin')) categories = session.query(Category).order_by(asc(Category.name)) editedItem = session.query(Item).filter_by(name=item_name).one() if editedItem.user_id != login_session['user_id']: return "<script>function myFunction() {alert('You are not authorized to edit this item. Please create your own item in order to edit.');}</script><body onload='myFunction()''>" if request.method == 'POST': if request.form['name'] and request.form['description'] and request.form['category_id']: editedItem.name = request.form['name'] editedItem.description = request.form['description'] editedItem.category_id = request.form['category_id'] session.add(editedItem) session.commit() flash('Item Successfully Edited') return redirect(url_for('catalog.showCatalog')) else: flash('All fields are mandatory') return render_template('items/edititem.html', item=editedItem, categories=categories) else: return render_template('items/edititem.html', item=editedItem, categories=categories)
def on_post(self, req, resp): stid = req.get_param("student_id") tid = req.get_param("teacher_id") comment = req.get_param("comment") date = req.get_param("date") if len(comment) > 256: resp.status = falcon.HTTP_500 resp.body = "That comment is too long." return date = datetime.datetime.strptime(date, "%Y-%m-%d").date() today = datetime.date.today() if (date-today).days < 2: resp.status = falcon.HTTP_409 resp.body = "You have to schedule your students two days in advance." return if sess.query(ms.Schedule).filter(student_id=stid, date=date).first() is None: resp.status = falcon.HTTP_409 resp.body = "A schedule already exists on this date." return sess.add(ms.Schedule(stid, tid, date, comment)) sess.commit() resp.status = falcon.HTTP_200 resp.body = "Successfully Schedule Student"
} session.commit() Base.metadata.drop_all(engine) Base.metadata.create_all(engine) store = Store( name='Cigarreria Don Pedro', place='Calle 160 #14 07', stars=10, lat=10.4392, lon=10.4392, rad=1, user_id='566ea44082e57abe7d84b99c', created_at=datetime.now() ) session.add(store) session.commit() print '' print '#' * 70 print '#' * 25 + ' INITIALIZING TESTS ' + '#' * 25 print '#' * 70 print '' print 'GET /' url = BASE_URL + '/' r = requests.get(url, headers=headers('user')) print r.status_code print r.text print '\n'
from app import session from app.catalog.models import Category from app.items.models import Item from app.auth.models import User # Create dummy user User1 = User(name="Nico Ianosi", email="*****@*****.**", picture='https://pixabay.com/static/uploads/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png') session.add(User1) session.commit() # Items for Soccer category1 = Category(user_id=1, name="Soccer", description="Soccer description") session.add(category1) session.commit() item1 = Item(user_id=1, name="Two shinguards", description="Two shinguards description", category=category1) session.add(item1) session.commit() item2 = Item(user_id=1, name="Jersey", description="Jersey description", category=category1) session.add(item2) session.commit() item3 = Item(user_id=1, name="Soccer Cleats", description="Soccer Cleats description", category=category1)
def createItem(form): category = categoryCheck(form) newItem = Item(name=form.name.data, description=form.description.data, \ category_id=category.id, user_id=login_session['user_id']) session.add(newItem) session.commit()