def initdb_command(): """Creates the database tables.""" db.create_all() print('Initialized the database.') supreme_overlord = Owner("owner", generate_password_hash("pass")) db.session.add(supreme_overlord) db.session.commit()
def test_home_page_returns_correct_html(self): """Test site and contact.html content.""" owner = Owner() request = HttpRequest() response = render(request, 'contact.html', {'owner': owner}) expected_html = render_to_string('contact.html') self.assertEqual(response.content.decode(), expected_html)
def initdb_command(): db.drop_all() db.create_all() owner = Owner() db.session.add(owner) db.session.commit() print('Initialized the database.')
def initdb_command(): """Creates the database tables.""" db.drop_all() db.create_all() own = Owner(username="******", password="******") db.session.add(own) db.session.commit() print('Initialized the database.')
def initdb_command(): """Reinitializes the database""" db.drop_all() db.create_all() # populate users db.session.add(Owner("owner", "pass")) db.session.commit() print('Initialized the database.')
def add_owner(): if request.method == 'POST': name = request.args.get('name') try: owner = Owner(name=name, ) db.session.add(owner) db.session.commit() return "owner added. owner id={}".format(owner.id) except Exception as e: return (str(e))
def signup(): data = request.get_json() owner = Owner(email=data['email'], username=data["username"], hashed=set_password(data['password'])) db.session.add(owner) db.session.commit() model_owner = Owner.query.filter_by(email=data['email']).first() owner = model_owner.to_safe_object() token = create_access_token(identity={"id": owner["id"]}) return jsonify(token=token, id=owner["id"])
def add_owner(): form = AddOwnerForm() if form.validate_on_submit(): owner_name = form.owner_name.data puppy_name = form.puppy_name.data owner = Owner(name=owner_name) db.session.add(owner) db.session.commit() puppy = Puppies.query.filter_by(name=puppy_name).first() puppy.owner = owner db.session.commit() return redirect(url_for("list_puppies")) return render_template('add_owner.html', form=form)
def test_storing_owner_data_to_html_page(self): """Test storing owner data to html.""" owner = Owner() owner.first_name = 'Sergiy' owner.last_name = 'Savarin' owner.save() request = HttpRequest() response = contact(request) self.assertContains(response, 'Sergiy') self.assertContains(response, 'Savarin')
def test_saving_and_retriving_owner_data(self): """Test saving and retriving owner data.""" owner = Owner() owner.first_name = 'Sergiy' owner.last_name = 'Savarin' owner.save() saved_data = Owner.objects.all() self.assertEqual(saved_data.count(), 2) self.assertEqual(saved_data[0].first_name, 'Sergiy') self.assertEqual(saved_data[0].last_name, 'Savarin')
def add_data(scope): from models import Admin,Owner,THistory,HHistory,Equipment # 创建表 db = scope['db'] admin = Admin('sjw','123') db.session.add(admin) db.session.commit() owner = Owner('李强','123') db.session.add(owner) db.session.commit() owner2 = Owner('王建林','123') db.session.add(owner2) db.session.commit() eqp_name = '设备2' eqp_uuid = getUuid() print(eqp_uuid) eqp = Equipment(_id=eqp_uuid,name=eqp_name,max_t=40,min_t=0,max_h=50,min_h=10,owner_id=owner.id,create_date=None) db.session.add(eqp) db.session.commit()
def login(): if g.customer: return redirect(url_for('timeline')) if g.owner: return redirect(url_for('timeline')) if g.staff: return redirect(url_for('timeline')) error = None if request.method == 'POST': #fixed some table issues, and now works if request.form['loginType'] == "customer": user = Customer.query.filter_by(username=request.form['username']).first() #get custmer if user is None: error = 'Invalid username' elif not check_password_hash(user.pw_hash, request.form['password']): error = 'Invalid password' else: session['user_id'] = user.user_id #logged in session['CustomerIndicator'] = 1; return redirect(url_for('timeline')) if request.form['loginType'] == "owner": if request.form["username"] in boss and boss[request.form["username"]] == request.form["password"]: if get_owner_id(request.form['username']) is None: db.session.add(Owner(request.form['username'], generate_password_hash(request.form['password']))) db.session.commit() user = Owner.query.filter_by(username=request.form['username']).first() session['user_id'] = user.user_id session['ownerIndicator'] = 1 return redirect(url_for('timeline')) if request.form['loginType'] == "staff": user = Staff.query.filter_by(username=request.form['username']).first() #the staff log in if user is None: error = 'Invalid username' elif not check_password_hash(user.pw_hash, request.form['password']): error = 'Invalid password' else: session['user_id'] = user.user_id session['staffIndicator'] = 1; return redirect(url_for('timeline')) return render_template('login.html', error=error)
def post(self): request_dict = request.get_json() if not request_dict: resp = {'message': 'No input data provided'} return resp, status.HTTP_400_BAD_REQUEST errors = owner_schema.validate(request_dict) if errors: return errors, status.HTTP_400_BAD_REQUEST try: owner = Owner(request_dict['name']) owner.add(owner) log_event(get_jwt_identity(), 'ADD - ' + owner.__repr__()) query = Owner.query.get(owner.id) result = owner_schema.dump(query) return result, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() resp = jsonify({"error": str(e)}) resp.status_code = status.HTTP_400_BAD_REQUEST return resp
def post(self, request, format=None): if 'username' in request.data: username = request.data['username'] else: data = { 'status': 500, 'msg': 'usernmae must required to create owner.' } return HttpResponse(json.dumps(data), content_type="application/json") if 'first_name' in request.data: first_name = request.data['first_name'] else: first_name = None if 'last_name' in request.data: last_name = request.data['last_name'] else: last_name = None if 'email' in request.data: email = request.data['email'] else: email = None if 'password' in request.data: password = request.data['password'] else: password = None owner_object = Owner(status=False, username=username, first_name=first_name, last_name=last_name, email=email, password=password) owner_object.save() data = {'status': 200, 'msg': 'Owner account created succesfully.'} return HttpResponse(json.dumps(data), content_type="application/json")
def av_by_key(key): requester = request.headers[OWNER_HEADER] try: av = Av.objects.get(key=key) except Av.DoesNotExist: if request.method == 'PUT' and requester==SUPERUSER: # Only the superuser may create new records. logging.info('Creating new av record for %s' % key) av = Av(key=key) else: # XXX Unauthorized access has to return exactly the same response as # an av not existing in the DB. Otherwise people can make requests to # others' urls and use the differing responses to see who has used the # service. logging.info('Av %s does not exist' % key) abort(404) # Ensure that this person is allowed to access this data if not (key == av.key or av.has_owner(requester)): logging.info('%s denied access to %s' % (requester, av.key)) abort(404) if request.method == 'GET': return text(av.to_lsl()) elif request.method == 'PUT': if 'owners' in request.lsldata: # owners string will look like avkey,avname,av2key,av2name etc. # split it on commas, then zip into tuples of (key,name). Iterate # over those tuples and ensure that there's a record for each one # in the DB's owner list. vals = request.lsldata['owners'].split(",") av.owners = [Owner(**{'key':i[0], 'name':i[1]}) for i in zip(vals[::2], vals[1::2])] av.save() return text(av.to_lsl())
fido = Puppy("Fido") # Add puppies to database db.session.add_all([rufus, fido]) db.session.commit() # Check with a query, this prints out all the puppies! print(Puppy.query.all()) # Grab Rufus from database # Grab all puppies with the name "Rufus", returns a list, so index [0] # Alternative is to use .first() instead of .all()[0] rufus = Puppy.query.filter_by(name='Rufus').all()[0] # Create an owner to Rufus jose = Owner("Jose", rufus.id) # Give some Toys to Rufus toy1 = Toy('Chew Toy', rufus.id) toy2 = Toy("Ball", rufus.id) # Commit these changes to the database db.session.add_all([jose, toy1, toy2]) db.session.commit() # Let's now grab rufus again after these additions rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) rufus.report_toys()
db.session.commit() #Check print(Puppy.query.all()) rufus = Puppy.query.filter_by(name='Rufus').first( ) # gives the first entry encountered whose name is rufus print(rufus) #rufus = Puppy.query.filter-by(name='Rufus').all()[0] === Similar to the above line of code #create owner object amruta = Owner('Amruta', rufus.id) # giving rufus toys toy1 = Toy('ChewToy', rufus.id) toy2 = Toy('Ball', rufus.id) db.session.add_all([amruta, toy1, toy2]) db.session.commit() #Grab rufus after those additions rufus = Puppy.query.filter_by(name='Rufus').first()
from models import db, Puppy, Toy, Owner rufus = Puppy('Rufus') fido = Puppy('Fido') #adding puppies to db db.session.add_all([rufus, fido]) db.session.commit() #Check print(Puppy.query.all()) rufus = Puppy.query.filter_by(name='Rufus').all()[0] print(rufus) #Create Owner altmash = Owner('Altmash', rufus.id) #give rufus some toys toy1 = Toy('Teddy', rufus.id) toy2 = Toy('Bell', rufus.id) db.session.add_all([altmash, toy1, toy2]) db.session.commit() #Grab Rufus again after above additions rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) rufus.report_toys()
from models import db, Puppy, Owner, Toy # Creating two puppies rufus = Puppy('Rufus') fido = Puppy('Fido') # Add puppies to database db.session.add_all([rufus, fido]) db.session.commit() # check! print(Puppy.query.all()) # grab an instance of the database rufus = Puppy.query.filter_by(name='Rufus').first() # Create an owner object jeff = Owner('Jeff', rufus.id) # Give Rufus some toys toy1 = Toy('Chew Toy', rufus.id) toy2 = Toy('Ball', rufus.id) db.session.add_all([jeff, toy1, toy2]) db.session.commit() # grab an instance of the database rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) rufus.report_toys()
# Create 2 puppies rufus = Puppy("Rufus") fido = Puppy("Fido") # Add puppies to database db.session.add_all([rufus, fido]) db.session.commit() # Print out all the puppies print(Puppy.query.all()) # Grab Rufus from DB rufus = Puppy.query.filter_by(name="Rufus").all()[0] # Create an owner for Rufus john = Owner("John", rufus.id) # Give Rufus some toys toy1 = Toy("Chew Toy", rufus.id) toy2 = Toy("Ball", rufus.id) # Commit these changes to the database db.session.add_all([john, toy1, toy2]) db.session.commit() # Grab Rufus again rufus = Puppy.query.filter_by(name="Rufus").first() print(rufus) # Show toys rufus.report_toys()
#create entries into the table from models import db, Puppy, Owner, Toy #Creating 2 puppies rufus = Puppy('Rufus') fido = Puppy('Fido') #add puppies to db db.session.add_all([rufus, fido]) db.session.commit() #check print(Puppy.query.all()) rufus = Puppy.query.filter_by( name="Rufus").first() #all()[0] -->for all and index zero #create an owner obj hux = Owner("hux", rufus.id) #Give Rufus some toys toy1 = Toy('chew toy', rufus.id) toy2 = Toy('ball', rufus.id) db.session.add_all([hux, toy1, toy2]) db.session.commit() #Grab rufus after those additions rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) print(rufus.report_toys())
def loadJson(): errors = 0 i = 1 with open('data.json') as file: # Leo JSON data = json.load(file) # Recorro JSON for dbase in data['db_list']: #Contador para ver en consola print("\nREGISTRO NUMERO %s " % i) # ------ COMIENZO LECTURA Y ASIGNACION DATOS DEL JSON ------------- db_name = dbase.get('dn_name') name = dbase.get('owner', None) if name: name = name.get('name') name_ok, lastname_ok = separateName(name) username = dbase.get('owner') if username: username = username.get('uid', None) email = dbase.get('owner', None) if email: email = email.get('email') # Funcion que separa el nombre en : primer nombre y apellido : (Jose luis Perez) --> Jose Perez first_name, lastname = separateName(name) # Creo email con el criterio : [email protected] : jose.luis.perez@mercado.. --> jose.perez@mercado.. email = createEmail(first_name.lower(), lastname.lower()) time_stamp = dbase.get('owner', None) if time_stamp: time_stamp = time_stamp.get('time_stamp') confidentiality = dbase.get('classification', None) if confidentiality: confidentiality = confidentiality.get('confidentiality') integrity = dbase.get('classification', None) if integrity: integrity = integrity.get('integrity') availability = dbase.get('classification', None) if availability: availability = availability.get('availability') #Valido y creo campos (ver en la funcion mas detalle) validateJson(db_name, name, email, username) # Si se cargaron los Managers (.csv) - sigo.. if getManager(): try: # Inserto nuevo Owner en la base de datos inserted_owner_id = insertOwner(name_ok, lastname_ok, username, email, time_stamp) # Creo una instancia de la clase Owner() owner_db = Owner(inserted_owner_id, name_ok, lastname_ok, username, email, time_stamp) # Agrego la instancia al objeto Owner de tipo : clase OwnerList() --> lista que contendra todos los Owners owner_db_list.addOwner(owner_db) # Busco el manager por clave username . Devuelve boolean , id manager y email have_manager, manager_id, manager_email = searchManager( username) # Si la base de datos tiene un Manager asignado - sigo.. if have_manager: # La base de datos debe tener obligatoriamente los valores para clasificarla if confidentiality and integrity and availability: try: # Calculo la clasificacion final de la nueva BD y la inserto en la base de datos final_classification = calculateClassification( confidentiality, integrity, availability) inserted_db_id = insertDatabase( manager_id, inserted_owner_id, confidentiality, integrity, availability, db_name, final_classification) # Creo una instancia de la clase Databases() new_database = Databases( inserted_db_id, manager_id, inserted_owner_id, db_name, confidentiality, integrity, availability, final_classification) # Agrego la instancia al objeto db_list de tipo : clase DBList() --> lista que contendra todas las bases registradas db_list.addDB(new_database) #Obtengo nombre de manager name_manager = separateEmail(manager_email) #Inserto datos a visualizar en tabla de interfaz interface.tree.insert( '', 0, text=" " + db_name, values=(" " + name_manager, " " + name, " " + final_classification)) except Exception as e: messagebox.showwarning( "Atencion!", "No se pudo cargar la Base %s perteneciente a %s %s. Ya existe una base de datos con ese nombre." % (str(db_name.upper()), str(name_ok), str(lastname_ok))) errors += 1 i += 1 else: messagebox.showwarning( "Atencion!", "No se pudo registrar la base de datos %s ya que alguno de sus indicadores para clasificacion: integrity,confidentiality o availability es nulo. Revise los datos y vuelva a ingresarla" % db_name.upper()) errors += 1 i += 1 else: message = messagebox.askquestion( "Atencion!", "No se pudo cargar la Base %s ya que no tiene un Manager asociado. Desea dar aviso al Owner de la BD : %s %s ?" % (str(db_name.upper()), str( name_ok.upper()), str(lastname_ok.upper()))) if message == 'yes': sendEmailInfo(db_name, name_ok, lastname_ok, email) print(email) errors += 1 i += 1 except sqlite3.OperationalError as e: messagebox.showerror( "Error!", "Debe conectar la base de datos primero") break except sqlite3 as e: messagebox.showerror( "Error!", "El owner %s ya fue registrado con la BD %s" % (str(name.upper()), str(db_name.upper()))) errors += 1 i += 1 else: messagebox.showerror( "Error!", "Primero debe ingresar los Managers(.CSV)") break i += 1 if i > 2: messagebox.showinfo( "IMPORT FINALIZADO", "Resgistros procesados %s\nBases ingresadas : %s\nBases con errores : %s" % (str(len(data['db_list'])), (len(data['db_list']) - errors), str(errors)))
from models import db, Puppy, Owner, Toy brigite = Puppy('Brigite') olie = Puppy('Ollie') # ADD db.session.add_all([brigite, olie]) db.session.commit() print(Puppy.query.all()) brigite = Puppy.query.filter_by(name='Brigite').first() mima = Owner('Mima', brigite.id) # Give brigite some toys biter = Toy('Biter', brigite.id) ball = Toy('Ball', brigite.id) db.session.add_all([mima, biter, ball]) db.session.commit() brigite = Puppy.query.filter_by(name='Brigite').first() print(brigite) print(brigite.report_toys())
# CREATING 2 PUPPIES rufus = Puppy('Rufus') fido = Puppy('Fido') #Add Puppies to DB db.session.add_all([rufus, fido]) db.session.commit() # Check! print(Puppy.query.all()) rufus = Puppy.query.filter_by(name='Rufus').first() #or .all() or .all()[0] print(rufus) #CREATE OWNER OBJECT jose = Owner( 'Jose', rufus.id ) #rufus.id is rufus created in line 17 with which is the puppy created in line 7 #GIVE RUFUS SOME TOYS toy1 = Toy('Crew Toy', rufus.id) toy2 = Toy('Ball', rufus.id) #commit changes db.session.add_all([jose, toy1, toy2]) db.session.commit() #GRAB RUFUS AFTER THOSE ADDITIONS rufus = Puppy.query.filter_by(name='Rugus').first() print(rufus) rufus.report_toys()
from models import db, Puppy, Owner, Toy db.create_all() #Create puppies rufus = Puppy('Rufus') fido = Puppy('Fido') #add them to db db.session.add_all([rufus, fido]) db.session.commit() print(Puppy.query.all()) pup1 = Puppy.query.filter_by(name='Rufus').first() print(pup1) #create Owner obj jose = Owner('Jose', pup1.id) #give pup1 some toys toy1 = Toy('chew toy', pup1.id) toy2 = Toy('ball', pup1.id) #add all to db db.session.add_all([jose, toy1, toy2]) db.session.commit() pup1 = Puppy.query.filter_by(name='Rufus').first() print(pup1) pup1.report_toys()
lluvia = Puppy('Lluvia') travieso = Puppy('Travieso') # add puppies to db db.session.add_all([lluvia, travieso]) db.session.commit() # check print(Puppy.query.all()) lluvia = Puppy.query.filter_by(name='Lluvia').first() travieso = Puppy.query.filter_by(name='Travieso').first() #Create owner object alex = Owner('Alex', lluvia.id) ale = Owner('Ale', travieso.id) # give lluvia some toys toy1 = Toy('Chew Toy', lluvia.id) toy2 = Toy('Ball', lluvia.id) # give travieso some toys toy3 = Toy('Chew Toy', travieso.id) toy4 = Toy('Ball', travieso.id) db.session.add_all([alex, ale, toy1, toy2, toy3, toy4]) db.session.commit() # grab lluvia and travieso
from models import db, Puppy, Owner, Toy rufus = Puppy('Rufus') fido = Puppy('Fido') db.session.add_all([rufus, fido]) db.session.commit() print(Puppy.query.all()) rufus = Puppy.query.filter_by(name='Rufus').first() alec = Owner('Alec', rufus.id) toy1 = Toy('Chew Toy', rufus.id) toy2 = Toy('Ball', rufus.id) db.session.add_all([alec, toy1, toy2]) db.session.commit() rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) rufus.report_toys()
# create entries into the tables from models import db, Puppy, Owner, Toy tarzan = Puppy('Tarzan') bobik = Puppy('Bobik') db.session.add_all([tarzan, bobik]) db.session.commit() print(Puppy.query.all()) tarzan = Puppy.query.filter_by(name='Tarzan').first() print(tarzan) peter = Owner('Peter', tarzan.id) toy1 = Toy("chew toy", tarzan.id) toy2 = Toy('Ball', tarzan.id) db.session.add_all([peter, toy1, toy2]) db.session.commit() tarzan = Puppy.query.filter_by(name='Tarzan').first() print(tarzan) print(tarzan.report_toys())
from models import db, Puppy, Toy, Owner rufus = Puppy('Rufus') fido = Puppy('Fido') db.session.add_all([rufus, fido]) db.session.commit() print(Puppy.query.all()) rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) jose = Owner('Jose', rufus.id) toy1 = Toy('Chew toy', rufus.id) toy2 = Toy('Ball', rufus.id) db.session.add_all([jose, toy1, toy2]) db.session.commit() rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) rufus.report_toys()
# create puppy rufus = Puppy('Rufus') kit = Puppy('kity') db.session.add_all([rufus, kit]) db.session.commit() all_pup = Puppy.query.all() print(all_pup) rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) # create owner mejomba = Owner('mojtaba', rufus.id) # create toy ball = Toy('ball', kit.id) pangpang = Toy('pank', kit.id) db.session.add_all([mejomba, ball, pangpang]) db.session.commit() rufus = Puppy.query.filter_by(name='Rufus').first() print(rufus) all_pup = Puppy.query.all() print(all_pup)