def main(): server = PubSubServer() cli1 = Client('Chris', server) cli1.subscribe('news') cli2 = Client('Tony', server) cli2.subscribe('news') cli3 = Client('Someone', server) print() cli3.publish('news', "It's a good day!")
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()
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)
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)
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'})
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)
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)
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)
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()
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}
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')
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)
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))
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)
def add_client(): firstname, lastname, email = view.add_client() client = Client(firstname, lastname, email) session.add(client) session.commit() return client
def __init__(self): self.args = [] self.parser = ArgumentParser(description="Task Manager app", formatter_class=RawTextHelpFormatter) self.create_argument_parser() self.dbclient = Client()
async def add_client(websocket, req_id, view_name): async with Cached.clients_lock: client = Client(websocket, req_id, view_name) Cached.clients.discard(client) Cached.clients.add(client) logger.info('added: %s' % client)
def register(username, password): password = set_pass(password) client = Client(username=username, password=password) session.add(client) session.commit()
def __init__(self): self.gui = Gui() self.dao = ClientDAO() self.selected = None #cliente selecionado self.currentClient = Client()
from repository import ClientRepository from model import Client class Bookshop: def __init__(self): self.clientRep = ClientRepository() def GetClientById(self,id): a = self.clientRep.GetClientById(id) return a def AddNewClient(self,client): self.clientRep.addClient(client) shop = Bookshop() client = shop.GetClientById(1) client1 = Client(420,699,"odin","artiom","pupkin") shop.AddNewClient(client1) shop.AddNewClient(client) print(client.toString())
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, }
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')
def do_POST(self): """Handles POST requests.""" data = str( self.rfile.read(int(self.headers.getheader("Content-Length")))) if self.path == "/api/stager": # Send back a unique encrypted payload. client_key = data.split("&")[0].split("=")[1] payload_options = json.loads( base64.b64decode( unquote_plus(data).split("&")[1].replace( "Cookie=session=", "", 1))) loader_options = payload_options["loader_options"] self._output_view.add(self._output_view.SEPARATOR) self._output_view.add( "[%s] Creating payload using key: %s" % (payload_options["loader_name"], client_key)), "info" if not self._payload_factory: self._payload_factory = PayloadFactory(self._loader_factory) self.wfile.write( self._payload_factory.create_payload(payload_options, loader_options, client_key)) elif self.path == "/api/get_command": # Command requests username = data.split("&")[0].replace("username="******"", 1) hostname = data.split("&")[1].replace("hostname=", "", 1) loader_name = data.split("&")[2].replace("loader=", "", 1) client_id = data.split("&")[3].replace("client_id=", "", 1) path = unquote_plus(data.split("&")[4].replace("path=", "", 1)) remote_ip = unquote_plus( data.split("&")[5].replace("remote_ip=", "", 1)) client = self._model.get_client(client_id) if not client: # This is the first time this client has connected. self._output_view.add(self._output_view.SEPARATOR) self._output_view.add( "New client \"%s@%s\" connected!" % (username, hostname), "info") self._model.add_client( Client(client_id, username, hostname, remote_ip, path, time.time(), loader_name)) self.send_headers() self.wfile.write("You dun goofed.") else: # Update the client's session (path and last_online). self._model.update_client(client_id, path, time.time()) # Send any pending commands to the client. command = self._model.get_command(client_id) if command: self._model.remove_command(command.id) # Special modules which need the server to do extra stuff. if command.module_name in [ "update_client", "remove_client" ]: self._model.remove_client(client_id) self.send_headers() self.wfile.write(str(command)) elif command.module_name == "upload": file_path = base64.b64decode( command.command).split(":")[0].replace("\n", "") file_name = os.path.basename(file_path) self._output_view.add("Sending file to client...", "info") with open(file_path, "rb") as input_file: file_size = os.fstat(input_file.fileno()) self.send_response(200) self.send_header("Content-Type", "application/octet-stream") self.send_header( "Content-Disposition", "attachment; filename=\"%s\"" % file_name) self.send_header("Content-Length", str(file_size.st_size)) self.send_header("X-Upload-Module", command.command) self.end_headers() shutil.copyfileobj(input_file, self.wfile) else: self.send_headers() self.wfile.write(str(command)) else: # Client has no pending commands. self.send_headers() self.wfile.write("") elif self.path == "/api/response": # Command responses json_response = json.loads( base64.b64decode(unquote_plus(data.replace("output=", "", 1)))) response = base64.b64decode(json_response["response"]) module_name = json_response["module_name"] self.send_headers() if module_name: # Send the response back to the module for name, module_imp in self._module_factory.get_modules( ).iteritems(): if name == module_name: try: module_imp.process_response( self._output_view, response) break except AttributeError: # The module doesn't have a process_response method, that's fine. self.output_response(response) else: # Command response self.output_response(response)