def login(): username = "" errors = {} global user if request.method == "POST": username = request.form.get("username").strip() if not username: errors["username"] = "******" password = request.form.get("password").strip() if not password: errors["password"] = "******" if len(errors) == 0: with database.connect() as conn: tmp = database.login(conn, username, password) if tmp == -1: errors["username"] = username + " does not exist" elif tmp == -2: errors["password"] = "******" else: user = User(tmp[0][0], tmp[0][1], tmp[0][2], tmp[0][3]) print("Successfully Logged In!") return redirect("/") return render_template("login.html", username=username, errors=errors, tab="login", user=user)
def getAllUsers(conn, order): c = conn.cursor() sql = "SELECT username, displayName, password, rank FROM users ORDER BY " + order if order == "rank": sql += " DESC" c.execute(sql) arr = c.fetchall() return [User(i[0], i[1], i[2], i[3]) for i in arr]
async def main(): longpoll = Api( token=group_token, group_id=group_id, ) user = User( token=user_token, group_id=group_id, ) async with longpoll as api: async for event in api.listen(): await user.approve_request(event['user_id'])
def signup(): username = "" displayName = "" errors = {} global user if request.method == "POST": with database.connect() as conn: username = request.form.get("username") if not username: errors["username"] = "******" elif len(username.split()) > 1 or username != username.strip(): errors["username"] = "******" elif not database.unique(conn, "username", username): errors["username"] = username + " has been taken" displayName = request.form.get("displayName") if not displayName: errors["displayName"] = "enter a display name" elif displayName != displayName.strip(): errors[ "displayName"] = "display name cannot start or end with spaces" elif not database.unique(conn, "displayName", displayName): errors["displayName"] = displayName + " has been taken" password = request.form.get("password") if not password: errors["password"] = "******" elif len(password.split()) > 1 or password != password.strip(): errors["password"] = "******" confirmPassword = request.form.get("confirmPassword") if not confirmPassword: errors["confirmPassword"] = "******" elif password != None and password != confirmPassword: errors["confirmPassword"] = "******" if len(errors) == 0: user = User(username, displayName, password, 0) database.addUser(conn, user) return redirect("/") return render_template("signup.html", username=username, displayName=displayName, errors=errors, tab="signup", user=user)
def main(args): # First we crate server. user_client = User() main_widget = MainWidget(None) login_menu = LoginMenu(user_client, main_widget) main_widget.change_main_widget(login_menu) # Urwid-asyncio mumbo jumbo, tl;dr is that # you need to run both urwid interface and server backend # at the same time so first you initialize (but not start) # Urwid loop aloop = asyncio.get_event_loop() ev_loop = urwid.AsyncioEventLoop(loop=aloop) loop = urwid.MainLoop(main_widget, event_loop=ev_loop) # And here you specify that alongside urwid you run server # All is set up - here execution starts loop.run()
def test_create_presence(self): # без параметров message = self.user.create_presence() assert message['action'] == "presence" # берем разницу во времени assert abs(message['time'] - time.time()) < 0.1 assert message["account_name"] == 'Leo' # с параметром имя message = self.user.create_presence() assert message["account_name"] == 'Leo' # неверный тип with raises(TypeError): self.user.create_presence(200) with raises(TypeError): self.user.create_presence(None) # Имя пользователя слишком длинное with raises(ToLongError): u = User('11111111111111111111111111') u.create_presence()
def start_chat(self): #name, password, result = AuthenticateDialog().get_username() # Создать контроллер self.client = User(self.name, self.password, addr, port) #print("Публичный ключ: {}, Приватный ключ: {} ".format(self.client.user_pub, self.client.user_priv)) self.window.setWindowTitle("Мессенджер - {}".format(self.name)) self.setGuiConnected(True) try: response = self.client.connect() if ERROR in response: if str(response[ERROR]) == str(WRONG_LOGIN): self.show_error_msg('Неверный логин', QMessageBox.Critical) self.client.disconnect() self.setGuiConnected(False) self.window.listWidgetContacts.clear() elif str(response[ERROR]) == str(WRONG_PASSWORD): self.show_error_msg('Неверный пароль', QMessageBox.Critical) self.client.disconnect() self.setGuiConnected(False) self.window.listWidgetContacts.clear() elif RESPONSE in response: if str(response[RESPONSE]) == str(OK): self.receiver = GuiReceiver(self.client.sock, self.client.request_queue) self.receiver.gotData.connect(self.update_chat) self.receiver.gotCryptoData.connect( self.append_user_public_keys) # Создание потока и помещение объекта-монитора в этот поток self.thread = QThread() self.receiver.moveToThread(self.thread) # ---------- Важная часть - связывание сигналов и слотов ---------- # При запуске потока будет вызван метод search_text self.thread.started.connect(self.receiver.poll) # При завершении поиска необходимо завершить поток и изменить GUI self.receiver.finished.connect(self.thread.quit) self.receiver.finished.connect(self.finished) # Запуск потока, который запустит self.monitor.search_text self.thread.start() self.contact_list, self.quantity = self.client.get_contacts( ) if self.quantity < 0: self.show_error_msg('У вас еще нет контактов!', QMessageBox.Warning) return for user_name in self.contact_list: user_public_keys_dict = { "name": user_name, "is_send_public_key": False, "is_received_public_key": False, "public_key": None } self.client.user_public_keys.append( user_public_keys_dict) # грузим контакты в список сразу при запуске приложения self.load_contacts(self.contact_list) else: raise ConnectionRefusedError except ConnectionRefusedError as e: print('Сервер недоступен') self.show_error_msg('Сервер недоступен!', QMessageBox.Critical) sys.exit() except Exception as e: print("Ошибка в функции start_chat:", e)
try: port = int(sys.argv[2]) except IndexError: port = 7777 except ValueError: print('Порт должен быть целым числом') sys.exit(0) try: name = sys.argv[3] print(name) except IndexError: name = 'GuiGuest' app = QtWidgets.QApplication(sys.argv) window = uic.loadUi('sv_main.ui') client = User(name, addr, port) client.connect() listener = GuiReceiver(client.sock, client.request_queue) @pyqtSlot(str) def update_chat(data): try: msg = data window.listWidgetMessages.addItem(msg) except Exception as e: print(e) listener.gotData.connect(update_chat) th = QThread()
import sys import Pyro4 import Pyro4.util import sys from client import User nameserver = Pyro4.locateNS() uri = nameserver.lookup("TSChatNow") # this is the ts chat now server app = Pyro4.Proxy(uri) user = User() user.initiate_chatapp(app)
def setup(self): self.user = User("Pavel", "password")
r.raw.decode_content = True shutil.copyfileobj(r.raw, f) print("{} downloaded.".format(file_name)) else: print("{} skipped.".format(file_name)) if __name__ == '__main__': webbrowser.open_new_tab( 'https://oauth.vk.com/authorize?client_id=6449285&response_type=token&scope=84&redirect_uri=https://limitedeternity.github.io/VK-SavedImagesDownloader/' ) try: access_token = input("Place access token here: ") user = User(token=access_token) vk_api = user.auth() print("Authorization successful.") except Exception: print("Your input data seems to be wrong. Please try again!") sys.exit(1) except KeyboardInterrupt: print("Keyboard interrupt detected!") sys.exit(0) try: start_time = time.time() creds = user.get_credentials(vk_api) folder = create_folder(creds)
def getUser(conn, username): c = conn.cursor() sql = "SELECT username, displayName, password, rank FROM users WHERE username = ?" c.execute(sql, (username, )) arr = c.fetchall() return User(arr[0][0], arr[0][1], arr[0][2], arr[0][3])
def seed_db(): db.session.add(User(username="******", email='*****@*****.**', password='******')) db.session.add(User(username="******", email='*****@*****.**', password='******')) db.session.commit()
try: addr = sys.argv[1] except IndexError: addr = 'localhost' try: prt = int(sys.argv[2]) except IndexError: prt = 7777 except ValueError: sys.exit(0) try: name = sys.argv[3] except IndexError: name = 'Leo' client = User(name) client.start() listener = ConsoleReceiver(client.sock, client.receiver_queue) thread_listener = Thread(target=listener.pull) thread_listener.daemon = True thread_listener.start() speaker = Sender(client.sock, client.login, client.sender_queue) thread_speaker = Thread(target=speaker.pull) thread_speaker.daemon = True thread_speaker.start() while True: # Получаем запрос/текст от пользователя text = input('<< ')
def setup(self): self.user = User('Leo')