Esempio n. 1
0
def create_user():

	typeUser = request.json['user']

	Session = sessionmaker(bind=engine)
	session = Session()

	if(typeUser == "client"):

		new_client = Client(name= request.json["name"],email=request.json["email"],contact=request.json["contact"])
		new_client.hash_password(request.json["password"])
		try:
			session.add(new_client)
			session.commit()
		except IntegrityError:
			return jsonify({'message':'That account already exists'})

		return jsonify({'message':'successful insertion of a client'})

	elif(typeUser == "owner"):	

		new_owner = Owner(name= request.json["name"],email=request.json["email"],contact=request.json["contact"])
		new_owner.hash_password(request.json["password"])
		try:	
			session.add(new_owner)
			session.commit()
		except IntegrityError:
			return jsonify({'message':'That account already exists'})

		return jsonify({'message':'successful insertion of a owner'})

	else:
		return jsonify({'message':'You didnt choose a user type'})
Esempio n. 2
0
def main():
    client = Client(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    max_id = Post.get_max_id()
    for post in client.get_posts(max_id):
        post = post_factory(post)
        if post:
            post.save()
Esempio n. 3
0
 def test_delete_client(self):
     number = self.get_last_number() + 1
     Client.add_client(number, 'A', 'B', '2000-01-01')
     count = self.check_count()
     Client.delete_client(number)
     self.assertEqual(self.check_count(), count - 1)
     for client in Client.get_clients():
         if client.number == number:
             self.assertFalse('Client was not deleted')
Esempio n. 4
0
 def test_show_clients(self):
     number = self.get_last_number() + 1
     Client.add_client(number, 'Testing', 'Controller', '2003-11-11')
     f = io.StringIO()
     with redirect_stdout(f):
         Controller().show_clients()
     s = f.getvalue()
     self.assertIn('Testing', s)
     self.assertIn('Controller', s)
     self.assertIn('2003-11-11', s)
Esempio n. 5
0
 def test_add_client(self):
     count = self.check_count()
     number = self.get_last_number() + 1
     Client.add_client(number, 'First', 'Last', '2020-02-02')
     self.assertEqual(self.check_count(), count + 1)
     for client in Client.get_clients():
         if client.number == number:
             self.assertEqual(client.firstname, 'First')
             self.assertEqual(client.lastname, 'Last')
             self.assertEqual(client.birthday, date.fromisoformat('2020-02-02'))
Esempio n. 6
0
def create_or_update_client(client_mac_int, base_station, timestamp):
    client = get_client_with_mac(client_mac_int)
    if client is None:
        client = Client(mac=client_mac_int, first_seen=timestamp, last_seen=timestamp,
                        base_stations=[base_station.key()])
    else:
        client.last_seen = timestamp
        if base_station.key() not in client.base_stations:
            client.base_stations.append(base_station.key())
    client.put()
    return client
Esempio n. 7
0
 def test_update_client(self):
     number = self.get_last_number() + 1
     Client.add_client(number, 'Abc', 'Def', '2000-01-01')
     count = self.check_count()
     Client.update_client(number, 'Abb', 'Dee', '2001-02-03')
     self.assertEqual(self.check_count(), count)
     for client in Client.get_clients():
         if client.number == number:
             self.assertEqual(client.firstname, 'Abb')
             self.assertEqual(client.lastname, 'Dee')
             self.assertEqual(client.birthday, date.fromisoformat('2001-02-03'))
Esempio n. 8
0
def send(text):
    (phones, info) = alg.parse(line)
    phones = set(phones)
    clients = Client.select_by_phone(list(phones))
    for client in clients:
        client.dump()

    insert_objs = []
    for phone in phones:
        insert_objs.append(Client(phone, info))
    success = Client.insert(insert_objs)

    if success:
        print('New info saved')
Esempio n. 9
0
def declare(host, covid):
    client = None
    if not db_client_queries.has(host):
        client = Client(host)
        db_client.insert(client)

    if client is None:
        client = db_client_queries.find(host)

    declared = client.declare_covid(covid)
    # Mettre à jour le status du client
    db_client.insert(client)

    return {"declared": declared}
Esempio n. 10
0
def get_client_with_mac(mac_int):
    query = Client.all().filter("mac_address = ", mac_int)
    results = query.fetch(1)
    if len(results) > 0:
        return results[0]
    else:
        return None
Esempio n. 11
0
def hear(host):
    message = Message.fromDict(request.json | {'host': host})

    if not db_client_queries.has(host):
        db_client.insert(Client(host))

    return db_message.insert(message)
Esempio n. 12
0
def render_request():
    if request.method == 'POST':
        form = RequestForm()

        goal = form.goals.data
        hour = form.hours.data
        name = form.name.data
        phone = form.phone.data

        with app.app_context():
            new_client = Client(name=name, phone=phone)
            db.session.add(new_client)

            new_request = Request(
                client=new_client,
                hour=Hour.query.filter(Hour.code == hour).first(),
                goal=Goal.query.filter(Goal.code == goal).first())
            db.session.add(new_request)

            db.session.commit()

        return render_template('request_done.html',
                               goal=goals[goal],
                               hours=hours[hour],
                               name=name,
                               phone=phone)
    else:
        form = RequestForm()

        return render_template('request.html', form=form)
Esempio n. 13
0
 def get(self):
     clients = Client.objects().all()
     return res(
         "Returned list of clients",
         "success",
         clients=convert_query(clients, list=True),
     )
Esempio n. 14
0
 def get(self):
     #clear maps
     utils.delete_all_in_index(maps.MAP_INDEX)
     db.delete(BaseStation.all())
     db.delete(Location.all())
     db.delete(Client.all())
     db.delete(Scan.all())
     self.response.out.write("Fake database cleared")
Esempio n. 15
0
 def get(self):
     #clear maps
     utils.delete_all_in_index(maps.MAP_INDEX)
     db.delete(BaseStation.all())
     db.delete(Location.all())
     db.delete(Client.all())
     db.delete(Scan.all())
     self.response.out.write("Fake database cleared")
Esempio n. 16
0
 def __init__(self):
     self.args = []
     self.parser = ArgumentParser(
         description="Task Manager app",
         formatter_class=RawTextHelpFormatter
     )
     self.create_argument_parser()
     self.dbclient = Client()
Esempio n. 17
0
 def test_show_clients(self):
     client1 = Client(123, 'Aaaaa', 'Bbbbb', '2001-01-01')
     client2 = Client(456, 'Ccccc', 'Ddddd', '2002-02-02')
     clients = [client1, client2]
     f = io.StringIO()
     with redirect_stdout(f):
         View.show_clients(clients)
     s = f.getvalue()
     self.assertIn('2 client', s)
     self.assertIn('123', s)
     self.assertIn('456', s)
     self.assertIn('Aaaaa', s)
     self.assertIn('Bbbbb', s)
     self.assertIn('Ccccc', s)
     self.assertIn('Ddddd', s)
     self.assertIn('2001-01-01', s)
     self.assertIn('2002-02-02', s)
Esempio n. 18
0
    def get(self, id):

        try:
            client = Client.objects(id=id)[0]
            return res("Returned client",
                       "success",
                       client=convert_query(client))
        except:
            return res("Client doesn't exist", "error"), 400
Esempio n. 19
0
    def __uiUpdateClient(self, params):
        if len(params) != 3:
            print("nr params invalid!")
            return

        id = int(params[0])
        nume = params[1]
        cnp = params[2]
        client = Client(id, nume, cnp)
        self.__servClient.updateClient(client)
Esempio n. 20
0
    def post(self):
        caller = get_caller(request)
        if caller["role"] != "admin":
            return res("⛔️ Must be an admin to add a new client", "error"), 400

        req = parse(request)
        errors = ClientListSchema().validate(req)
        if errors:
            return res("Errors in request", "alert", errors=errors), 400

        client = Client(name=req["name"])

        if "email" in req:
            client["email"] = req["email"].lower()

        client.save()

        return res("Added a new client",
                   "success",
                   client=convert_query(client))
Esempio n. 21
0
class ClientRepository:
    lista_de_clienti = [
        Client(1, 500, "Chisinau-Grenoble", "Marcel", "Tri"),
        Client(2, 1000, "Chisinau-Banulescu Bodonii", "Anton", "Solomon"),
        Client(3, 0, "Soroca-Strada Sorocii", "Roman", "Canibal"),
        Client(4, 1000, "Briceni-Strada victoriei 1/2", "Ion", "Batan"),
        Client(5, 50000, "Chisinau-Grenoble", "Simion", "Caprosu")
    ]

    def GetClientById(self, id):
        for client in self.lista_de_clienti:
            if client.id == id:
                return client

    def addClient(self, clienttoadd):
        for client in self.lista_de_clienti:
            if client.id == clienttoadd.id:
                print("client esti")
        else:
            self.lista_de_clienti.append(clienttoadd)
Esempio n. 22
0
def read_messages(host):

    if not db_client_queries.has(host):
        client = Client(host)
        db_client.insert(client)

    if host is not None:
        message: Query = Query()
        return db_message.search(message.host == host)

    return db_message.all()
Esempio n. 23
0
    def delete(self, id):
        caller = get_bearer(request)
        if caller["role"] != "admin":
            return res("⛔️ Must be an admin to delete a client", "error"), 400
        try:
            client = Client.objects(id=id)
        except:
            return res("Client doesn't exist", "error"), 400

        client.delete()

        return res("Deleted client", "success")
Esempio n. 24
0
 def post(self):
     user = current_user.user()
     item = Client(
         client_id=gen_salt(40),
         client_secret=gen_salt(50),
         _redirect_uris=list([
             'http://localhost:8000/authorized',
             'http://127.0.0.1:8000/authorized',
             'http://127.0.1:8000/authorized',
             'http://127.1:8000/authorized',
             ]),
         _default_scopes='email',
         user=user,
     )
     try:
         item.save()
     except:
         return 'insert false'
     return jsonify(
             client_id = item.client_id,
             client_secret = item.client_secret
             )
Esempio n. 25
0
def add_client():  #fonction d'ajout de client
    log.info('Controler add_clients starts')
    if request.method == 'POST':
        # TODO check that firstname and lastname are defined
        client_email = db.query(Client).filter_by(
            email=request.form['email']).first()
        if client_email is None:
            client = Client(  # ici in instancie un objet client (de la classe client)
                request.form['firstname'],
                request.form['lastname'], request.form['email'],
                generate_token(), request.form['password'])
            db.add(client)
            db.commit()
            return redirect(url_for('client_file_client', token=client.token))
        if request.form['email'] == client_email.email:
            return render_template('redirect_add_client.html')
    else:
        return render_template('add_client.html')
    def __init__(self, first_state):
        """
        :param first_state: (State) State de depart
        """
        self._state = first_state
        self._first_state = self._state

        with open(CLIENT_DATA_BASE) as f:
            data_base = json.load(f)

        list_client = []

        # on charge les clients de la base de donnée
        for client in data_base:
            list_client.append(Client(Carte(client["card-number"], client["card-password"]),
                                      *[Compte(compt["name"], compt["sold"]) for compt in client["bank-accounts"]]))

        self.banque = Banque(*list_client)
        self.distrib = Distrib(self.banque)
Esempio n. 27
0
    def put(self, id):
        caller = get_caller(request)
        if caller["role"] != "admin":
            return res("⛔️ Must be an admin to modify a client", "error"), 400

        req = parse(request)
        errors = ClientSchema().validate(req)
        if errors:
            return res("Errors in request", "alert", errors=errors), 400
        try:
            client = Client.objects(id=id)[0]
        except:
            return res("Client doesn't exist", "error"), 400

        for i in req:
            client[i] = req[i]

        client.save()

        return res("Modified client", "success", client=convert_query(client))
Esempio n. 28
0
def render_booking(id, day, time):
    if request.method == 'POST':
        form = BookingForm()

        id = form.id.data
        name = form.name.data
        phone = form.phone.data
        day = form.day.data
        time = form.time.data

        with app.app_context():
            new_client = Client(name=name, phone=phone)
            db.session.add(new_client)

            new_booking = Booking(
                client=new_client,
                teacher_id=id,
                day=Day.query.filter(Day.code == day).first(),
                time=Time.query.filter(Time.code == time).first())
            db.session.add(new_booking)

            db.session.commit()

        return render_template('booking_done.html',
                               name=name,
                               phone=phone,
                               day=week[day],
                               time=time)
    else:
        form = BookingForm()

        return render_template('booking.html',
                               week=week,
                               id=id,
                               teacher=get_teacher(id),
                               day=day,
                               time=time,
                               form=form)
Esempio n. 29
0
 def test_get_clients(self):
     self.assertEqual(self.check_count(), len(Client.get_clients()))
Esempio n. 30
0
 def get_last_number(self):
     return max(Client.get_clients(), key=lambda client: client.number).number
Esempio n. 31
0
def play_view(request):
    client_id = request.POST.get('client_id')
    name = request.POST.get('name')
    resume = request.POST.get('resume', False)

    client = clients.get(client_id)
    if resume:
        return RESUME_ERROR
#        if client:
#            # preserve previous name if we are resuming a game
#            name = client.name
#
#            game = games.get(client.game_id)
#            if game is None or game.complete():
#                return RESUME_ERROR
#        else:
#            return RESUME_ERROR

    # initialize the client
    if client:
        # log the client out, killing their current games
        quit_view(request)
        if name:
            client.name = name
    else:
        client_id = client_id or create_client_id()
        name = name or create_name()
        client = Client(client_id, name)

        # new client, increase unique count
        global unique_client_num
        unique_client_num += 1

    # avoid multiple clients with the same name
    if name in client_names:
        return INVALID_CLIENT_NAME

    # add the client to a game and possibly begin
    if len(pending_games) > 0:
        game = pending_games.popleft()
        game.add_player(client)
        if game.is_ready():
            game.begin()
        else:
            pending_games.appendleft()
    else:
        game_id = create_game_id()
        game = TicTacToe(game_id)
        game.add_player(client)

        pending_games.append(game)
        games[game_id] = game

    # remember the client
    client.game = game
    clients[client.id] = client
    client_names.add(client.name)

    return {
        'client_id': client.id,
        'name': client.name,
        'game_id': game.id,
    }
Esempio n. 32
0
def add_client():
    firstname, lastname, email = view.add_client()
    client = Client(firstname, lastname, email)
    session.add(client)
    session.commit()
    return client
Esempio n. 33
0
 def get(self, *args, **kwargs):
     user = current_user.user()
     client_id = kwargs.get('client_id')
     client = Client.objects(client_id = client_id).first()
     return {"user":user, "client":client}
Esempio n. 34
0
class Taskparser(object):
    """Parser to manage de options and arguments"""
    def __init__(self):
        self.args = []
        self.parser = ArgumentParser(description="Task Manager app",
                                     formatter_class=RawTextHelpFormatter)
        self.create_argument_parser()
        self.dbclient = Client()

    def create_argument_parser(self):
        """Create the argument group and other arguments."""
        group = self.parser.add_mutually_exclusive_group()
        group.add_argument("-a",
                           "--add",
                           nargs="+",
                           dest="description",
                           help="Add a task",
                           metavar="DESCRIPTION")
        group.add_argument("-f",
                           "--file",
                           dest="file",
                           type=FileType('r', encoding=None),
                           help="Add batch of tasks in a file",
                           metavar="INPUT FILE")
        group.add_argument("-c",
                           "--complete",
                           type=int,
                           help="Check a task as complete",
                           metavar="TASK ID")
        group.add_argument("-l",
                           "--list",
                           nargs='?',
                           const='all',
                           help="List all task",
                           metavar="FILTER")
        group.add_argument("-s",
                           "--show",
                           type=int,
                           help="Show a task",
                           metavar="TASK ID")
        self.parser.add_argument("parameter", nargs="*", metavar="Description")
        self.parser.add_argument("-p",
                                 "--project",
                                 dest="project",
                                 help="Project of a task",
                                 metavar="PROJECT")
        self.parser.add_argument("-t",
                                 "--tags",
                                 nargs="+",
                                 dest="tags",
                                 help="Tags of a task(space between tags)",
                                 metavar="TAGS")
        self.parser.add_argument("-q",
                                 "--queue-priority",
                                 dest="priority",
                                 help="Priority ([H]igh, [L]ow)",
                                 metavar="PRIORITY")
        help_due = """Due date as a date(dd/mm/YY) or a period in the format
+NUMBERS[h|d|w|m|y] where
h -> hours
d -> days
w -> weeks
m -> months
y -> years"""
        self.parser.add_argument("-d",
                                 "--due-date",
                                 dest="due_date",
                                 help=help_due,
                                 metavar="DUE DATE")
        self.parser.add_argument("-b",
                                 "--bairn",
                                 dest="parent",
                                 help="Id of the parent task",
                                 metavar="PARENT ID")

    def parse_args(self, args=None):
        """Parse arguments"""
        if args:
            return self.parser.parse_args(args)
        else:
            return self.parser.parse_args()

    def process_args(self, args):
        """Process arguments to execute the right for each one."""
        if args.parameter:
            if [
                    key for key, val in vars(args).items()
                    if val and key not in OPTIONALS
            ]:
                self.parser.print_help()
            else:
                new_doc = self.dbclient.create_task(vars(args))
                self.dbclient.insert_task(new_doc)
        elif args.list:
            self.dbclient.show_all_task(args.list)
        elif args.show:
            self.dbclient.show_task(args.show)
        elif args.description:
            new_doc = self.dbclient.create_task(vars(args))
            self.dbclient.insert_task(new_doc)
        elif args.complete:
            self.dbclient.complete_task(args.complete)
        elif args.file:
            for line in args.file:
                args = self.parse_args(line.rstrip('\r\n').split())
                self.process_args(args)
        else:
            self.parser.print_usage()
Esempio n. 35
0
 def __init__(self):
     self.args = []
     self.parser = ArgumentParser(description="Task Manager app",
                                  formatter_class=RawTextHelpFormatter)
     self.create_argument_parser()
     self.dbclient = Client()
Esempio n. 36
0
 def __init__(self):
     self.gui = Gui()
     self.dao = ClientDAO()
     self.selected = None  #cliente selecionado
     self.currentClient = Client()
Esempio n. 37
0
    book_2 = Book(
        'Clean Code', 'Por que não testamos software? Porque é caro? '
        'Porque é demorado? Porque é chato? ', '## 1.2 Por que devemos testar?'
        '## 1.3 Por que não testamos?', 59.90, 194, '9788566250048',
        datetime(2020, 6, 20), category_1)

    books.add(book_2)
    categories.add(category_2)

    # Cadastrando Cupons

    date_expiration_coupon_1 = datetime(2020, 10, 10)
    date_expiration_coupon_2 = datetime(2020, 6, 10)

    coupon_1 = Coupon('ALURA10', date_expiration_coupon_1, 10)
    coupon_2 = Coupon('CDC40', date_expiration_coupon_2, 40)
    coupons.add(coupon_1)
    coupons.add(coupon_2)

    # Carrinho de Compras

    cart = ShoppingCartDatabase(books, coupons)
    client_1 = Client('Nádia', '*****@*****.**', '012.345.678-90',
                      Address('São Gonçalo', 'MG', '38900456'))

    cart.add_cart('Clean Code')
    cart.add_cart('Test-Driven Development')
    cart.add_cart('Test-Driven Development')
    cart.checkout(client_1, 'ALURA10')
Esempio n. 38
0
class Taskparser(object):
    """Parser to manage de options and arguments"""
    def __init__(self):
        self.args = []
        self.parser = ArgumentParser(
            description="Task Manager app",
            formatter_class=RawTextHelpFormatter
        )
        self.create_argument_parser()
        self.dbclient = Client()

    def create_argument_parser(self):
        """Create the argument group and other arguments."""
        group = self.parser.add_mutually_exclusive_group()
        group.add_argument(
            "-a",
            "--add",
            nargs="+",
            dest="description",
            help="Add a task",
            metavar="DESCRIPTION"
        )
        group.add_argument(
            "-f",
            "--file",
            dest="file",
            type=FileType('r', encoding=None),
            help="Add batch of tasks in a file",
            metavar="INPUT FILE"
        )
        group.add_argument(
            "-c",
            "--complete",
            type=int,
            help="Check a task as complete",
            metavar="TASK ID"
        )
        group.add_argument(
            "-l",
            "--list",
            nargs='?',
            const='all',
            help="List all task",
            metavar="FILTER"
        )
        group.add_argument(
            "-s",
            "--show",
            type=int,
            help="Show a task",
            metavar="TASK ID"
        )
        self.parser.add_argument(
            "parameter",
            nargs="*",
            metavar="Description"
        )
        self.parser.add_argument(
            "-p",
            "--project",
            dest="project",
            help="Project of a task",
            metavar="PROJECT"
        )
        self.parser.add_argument(
            "-t",
            "--tags",
            nargs="+",
            dest="tags",
            help="Tags of a task(space between tags)",
            metavar="TAGS"
        )
        self.parser.add_argument(
            "-q",
            "--queue-priority",
            dest="priority",
            help="Priority ([H]igh, [L]ow)",
            metavar="PRIORITY"
        )
        help_due = """Due date as a date(dd/mm/YY) or a period in the format
+NUMBERS[h|d|w|m|y] where
h -> hours
d -> days
w -> weeks
m -> months
y -> years"""
        self.parser.add_argument(
            "-d",
            "--due-date",
            dest="due_date",
            help=help_due,
            metavar="DUE DATE"
        )
        self.parser.add_argument(
            "-b",
            "--bairn",
            dest="parent",
            help="Id of the parent task",
            metavar="PARENT ID"
        )

    def parse_args(self, args=None):
        """Parse arguments"""
        if args:
            return self.parser.parse_args(args)
        else:
            return self.parser.parse_args()

    def process_args(self, args):
        """Process arguments to execute the right for each one."""
        if args.parameter:
            if [
                    key for key, val in vars(args).items()
                    if val and key not in OPTIONALS
            ]:
                self.parser.print_help()
            else:
                new_doc = self.dbclient.create_task(vars(args))
                self.dbclient.insert_task(new_doc)
        elif args.list:
            self.dbclient.show_all_task(args.list)
        elif args.show:
            self.dbclient.show_task(args.show)
        elif args.description:
            new_doc = self.dbclient.create_task(vars(args))
            self.dbclient.insert_task(new_doc)
        elif args.complete:
            self.dbclient.complete_task(args.complete)
        elif args.file:
            for line in args.file:
                args = self.parse_args(line.rstrip('\r\n').split())
                self.process_args(args)
        else:
            self.parser.print_usage()