Пример #1
0
    def post(self):
        company_id = self.request.get('company_id') 
        company = Company.get_by_id(int(company_id))

        try:
            name = self.request.get('name') 
            company.name = name
        except:
            pass

        try:
            address = self.request.get('address') 
            company.address = address
        except:
            pass

        try:
            city = self.request.get('city') 
            company.city = city
        except:
            pass

        try:
            country = self.request.get('country') 
            company.country = country
        except:
            pass

        try:
            email = self.request.get('email') 
            company.email = email
        except:
            pass

        try:
            phone_number = int(self.request.get('phone_number'))
            company.phone_number = phone_number
        except:
            pass

        try:
            owner_name = self.request.get('owner_name')
            owner = Owner()
            owner.name = owner_name
            owner.company = company.key()
            owner.put()
        except:
            pass

        try:
            director_name = self.request.get('director_name')
            director = Director()
            director.name = director_name
            director.company = company.key()
            director.put()
        except:
            pass
        
        company.put()   
        self.redirect("company/" + str(company_id))
Пример #2
0
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()
Пример #3
0
 def timerEvent(self, event):
     try:
         user = Owner.get(islog=True)
         self.showMessage(u"%s %s est connecté."
                          % (user.group, user.username), 2000)
     except:
         self.showMessage(u"Vos identifiants", 3000)
Пример #4
0
 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)
Пример #5
0
def initdb_command():
    db.drop_all()
    db.create_all()
    owner = Owner()
    db.session.add(owner)
    db.session.commit()
    print('Initialized the database.')
Пример #6
0
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.')
Пример #7
0
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.')
Пример #8
0
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))
Пример #9
0
 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
Пример #10
0
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"])
Пример #11
0
    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")
Пример #12
0
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)
Пример #13
0
    def get(self,owner_id):
        owner = Owner.get_by_id(int(owner_id))

        if owner.passport:
            self.response.headers['Content-Type']="application/pdf"
            self.response.write(owner.passport)
        else:
            template_values = {
                'owner' : owner 
                }

            template = jinja_environment.get_template('ownerattach.html')
            self.response.out.write(template.render(template_values))
Пример #14
0
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()
Пример #15
0
 def save_b(self):
     ''' add operation '''
     # entete de la facture
     if not self.table_buy.isvalid:
         return False
     owner = Owner.get(Owner.islog == True)
     date = str(self.date.text())
     values_t = self.table_buy.get_table_items()
     buy = Buy()
     # buy.date = datetime_
     buy.provd_or_clt = \
         ProviderOrClient.get_or_create(
             "Fournisseur", 000000, ProviderOrClient.FSEUR)
     buy.owner = owner
     try:
         buy.save()
         err = False
     except:
         raise
         raise_error("Erreur",
                     u"Impossible d'enregistrer l'entête de la facture")
         return False
     for name, qty, cost_buying, selling_price in values_t:
         rep = Report()
         rep.buy = buy
         rep.type_ = Report.E
         rep.store = 1
         rep.date = date_to_datetime(date)
         rep.product = Product.get(name=name)
         rep.qty = int(qty)
         rep.cost_buying = int(cost_buying)
         rep.selling_price = int(selling_price)
         try:
             rep.save()
         except Exception as e:
             print(e)
             err = True
     if err:
         buy.delete_instance()
         raise_error(
             "Erreur", u"Ce mouvement n'a pas pu etre "
             u"enregistré dans les rapports")
         return False
     else:
         self.parent.Notify(u"L'entrée des articles avec succès", "success")
     self.change_main_context(BuyShowViewWidget, buy=buy)
Пример #16
0
    def check_log(self, page, permiss=None):

        if not Config.LOGIN:
            self.parent.active_menu_ad()
            self.change_main_context(page)
            SystemTrayIcon((_(u"Avertissement de Securité"),
                            "({}) Il est vivement souhaité de securiser son \
                            application".format(Config.APP_NAME)),
                           parent=self)
        else:
            try:
                owner = Owner.get(islog=True)
                self.parent.active_menu_ad(
                ) if owner.group in self.root_permission else self.parent.active_menu(
                )
            except OwnerDoesNotExist:
                return False
Пример #17
0
 def save_b(self):
     ''' add operation '''
     # entete de la facture
     if not self.table_buy.isvalid:
         return False
     owner = Owner.get(Owner.islog == True)
     date = str(self.date.text())
     values_t = self.table_buy.get_table_items()
     buy = Buy()
     # buy.date = datetime_
     buy.provd_or_clt = \
         ProviderOrClient.get_or_create(
             "Fournisseur", 000000, ProviderOrClient.FSEUR)
     buy.owner = owner
     try:
         buy.save()
         err = False
     except:
         raise
         raise_error(
             "Erreur", u"Impossible d'enregistrer l'entête de la facture")
         return False
     for name, qty, cost_buying, selling_price in values_t:
         rep = Report()
         rep.buy = buy
         rep.type_ = Report.E
         rep.store = 1
         rep.date = date_to_datetime(date)
         rep.product = Product.get(name=name)
         rep.qty = int(qty)
         rep.cost_buying = int(cost_buying)
         rep.selling_price = int(selling_price)
         try:
             rep.save()
         except Exception as e:
             print(e)
             err = True
     if err:
         buy.delete_instance()
         raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
                     u"enregistré dans les rapports")
         return False
     else:
         self.parent.Notify(u"L'entrée des articles avec succès", "success")
     self.change_main_context(BuyShowViewWidget, buy=buy)
Пример #18
0
    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')
Пример #19
0
    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')
Пример #20
0
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)
Пример #21
0
    def check_log(self, page, permiss=None):

        if not Config.LOGIN:
            self.parent.active_menu_ad()
            self.change_main_context(page)
            SystemTrayIcon(
                (
                    _("Avertissement de Securité"),
                    "({}) Il est vivement souhaité de securiser son \
                            application".format(
                        Config.APP_NAME
                    ),
                ),
                parent=self,
            )
        else:
            try:
                owner = Owner.get(islog=True)
                self.parent.active_menu_ad() if owner.group in self.root_permission else self.parent.active_menu()
            except OwnerDoesNotExist:
                return False
Пример #22
0
    def timerEvent(self, event):
        if self.compt == 0:
            self.showMessage(u"Bienvenue! sur {}. Un outil rapide et facile à "
                             u"utiliser qui vous permet de faire le suivi de "
                             u"stock".format(Config.APP_NAME), 14000)
        if self.compt == 1:
            try:
                user = Owner.get(islog=True)
                mss = u"Votez connecté en tant que {user}" \
                      u" et les droits de {group}.".format(user=user.username,
                                                           group=user.group)
            except:
                mss = u"Vos identifiants"
            self.showMessage(mss, 15000)

        if self.compt == 2:
            self.showMessage(u"Seul l'organisation {} est autorisée ce logiciel".format(
                Config.NAME_ORGA), 15000)

        if self.compt > 4:
            self.compt = 0
        self.compt += 1
Пример #23
0
    def timerEvent(self, event):
        if self.compt == 0:
            self.showMessage(
                u"Bienvenue! sur {}. Un outil rapide et facile à "
                u"utiliser qui vous permet de faire le suivi de "
                u"stock".format(Config.APP_NAME), 14000)
        if self.compt == 1:
            try:
                user = Owner.get(islog=True)
                mss = u"Votez connecté en tant que {user}" \
                      u" et les droits de {group}.".format(user=user.username,
                                                           group=user.group)
            except:
                mss = u"Vos identifiants"
            self.showMessage(mss, 15000)

        if self.compt == 2:
            self.showMessage(
                u"Seul l'organisation {} est autorisée ce logiciel".format(
                    Config.NAME_ORGA), 15000)

        if self.compt > 4:
            self.compt = 0
        self.compt += 1
Пример #24
0
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())
Пример #25
0
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()
Пример #26
0
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())
Пример #27
0
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()
Пример #28
0
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()
Пример #29
0
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()
Пример #30
0
 def post(self,owner_id):
     owner = Owner.get_by_id(int(owner_id))
     p = self.request.get('passport') 
     owner.passport = p
     owner.put()
     self.redirect("/owner/" + str(owner_id))
Пример #31
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        print("save")
        if not self.is_valide():
            return
        invoice_date = unicode(self.invoice_date.text())
        num_invoice = int(self.num_invoice.text())
        invoice_type = self.liste_type_invoice[
            self.box_type_inv.currentIndex()]
        lis_error = []
        invoice = Invoice()
        try:
            self.owner = Owner.get(Owner.islog == True)
        except:
            lis_error.append("Aucun utilisateur est connecté <br/>")
        paid_amount = int(self.table_invoice.paid_amount_field.text())
        try:
            clt = ProviderOrClient.get_or_create(
                self.name_client, int(self.phone.replace(" ", "")), ProviderOrClient.CLT)
        except ValueError:
            field_error(
                self.name_client_field, "Nom, numéro de téléphone du client")
        invoice.number = num_invoice
        invoice.owner = self.owner
        invoice.client = clt
        invoice.location = "Bamako"
        invoice.type_ = invoice_type
        invoice.subject = ""
        invoice.paid_amount = paid_amount
        invoice.tax = False
        try:
            invoice.save()
            if int(paid_amount) != 0 or invoice_type == Invoice.TYPE_BON:
                Refund(type_=Refund.DT, owner=self.owner, amount=paid_amount,
                       date=date_to_datetime(invoice_date), provider_client=clt,
                       invoice=Invoice.get(number=num_invoice)).save()
        except Exception as e:
            invoice.deletes_data()
            lis_error.append(
                "Erreur sur l'enregistrement d'entête de facture<br/>")
            return False
        # Save invoiceitems
        invoice = Invoice.get(Invoice.number == num_invoice)
        for name, qty, price in self.table_invoice.get_table_items():
            rep = Report()
            product = Product.get(Product.name == name)
            rep.store = 1
            rep.product = product
            rep.invoice = invoice
            rep.type_ = Report.S
            rep.cost_buying = int(product.last_report.cost_buying)
            rep.date = date_to_datetime(invoice_date)
            rep.qty = int(qty)
            rep.selling_price = int(price)
            try:
                rep.save()
            except Exception as e:
                lis_error.append(e)
        if lis_error != []:
            invoice.delete_instance()
            self.parent.Notify(lis_error, "error")
            return False
        else:
            self.parent.Notify("Facture Enregistrée avec succès", "success")

            self.change_main_context(ShowInvoiceViewWidget,
                                     invoice_num=invoice.number)
Пример #32
0
# 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())
Пример #33
0
# 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)
Пример #34
0
#  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()
Пример #35
0
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
Пример #36
0
# 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()
Пример #37
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        if not self.table_invoice.isvalid:
            return False
        try:
            num_invoice = int(self.num_invoice.text())
            self.num_invoice_error.setText(u"")
        except:
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="warning.png"))
            self.num_invoice.setStyleSheet("background-color:  rgb(255, 235, 235);")
            self.num_invoice_error.setToolTip(u"Le numero de facture est obligatoire.")
            self.num_invoice_error.setPixmap(self.pixmap)
        invoice_date = str(self.invoice_date.text())
        name_client = str(self.name_client.text())
        datetime_ = date_to_datetime(invoice_date)

        values_t = self.table_invoice.get_table_items()
        if name_client == "":
            self.name_client.setStyleSheet("background-color: rgb(255, 235, 235);")
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="decline.png"))
            self.name_client_error.setToolTip(u"Nom du client est obligatoire.")
            self.name_client_error.setPixmap(self.pixmap)
            return False
        # if num_invoice > Config.credit:
        #     raise_error(("Avertisement"), u"<h2>Veuillez payer la reste de la licence</h2>")
        #     return False
        invoice = Invoice()
        try:
            invoice.owner = Owner.get(islog=True)
        except:
            if Config.DEBUG:
                invoice.owner = Owner.get(username='******')
            else:
                return False

        invoice.number = num_invoice
        invoice.date_ord = datetime_
        invoice.client = name_client.capitalize()
        invoice.location = "Bamako"
        invoice.type_ = "Facture"
        invoice.subject = ""
        invoice.tax = False
        invoice.otax_rate = 18
        try:
            invoice.save()
        except:
            raise_error("Erreur", u"Impossible d'enregistrer l'entête de la facture")
            return False

        # Save orderitems
        try:
            order = Invoice.get(number=num_invoice)
        except:
            return False
        for i in values_t:
            qty, name, price = i
            description = Product.filter(name=name).get()
            item = InvoiceItem()
            item.invoices = invoice.id
            item.quantity = int(i[0])
            item.description = description
            item.price = int(i[2])
            try:
                item.save()
                self.name_client.clear()
                self.num_invoice.clear()
            except Exception as e:
                print(e)
                invoice.delete_instance()
                raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
                                      u"enregistré dans les rapports")
                return False

        self.change_main_context(ShowInvoiceViewWidget,
                                        invoice=invoice)
Пример #38
0
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()
Пример #39
0
#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())