def create_tables(): ''' Our method where we will create the database tables''' try: User.create_table() Mweet.create_table() except pw.OperationalError: print(" Users or Messages table already exists!")
def __init__(self, text, n, un): self.text = text self.n = n self.un = un super().__init__(self.text, self.n, self.un) self.Words = Word(User.script(self)) self.Messages = User.script(self)
class Hangman: def __init__(self, wordlist, usr): self.word = Randword(wordlist) self.usr = User(usr) self.tries = set() self.chances = 8 def decrement_chances(self): self.chances -= 1 if self.chances > 0: print(f'you have {self.chances} to survive') def end_game(self, success): if success: print(self.word) self.usr.increment_score(10) print("That's right, you've guessed the word") else: print('you died') print(f'the word was {self.word}') def logic(self, letter): if letter not in self.tries: self.tries.add(letter) if self.word.check_letter_correctness(letter): self.word.parse_letter(letter) if self.word.blanks == self.word.word: self.end_game(True) return 1
def add_user(user_name): value = User.create_id() new_user = User(user_name, value, {}) id_for_dict = {value: new_user.__dict__} users.update(id_for_dict) response = app.response_class(response=json.dumps(users), status=200, mimetype='application/json') return response
def addUser(self,id_user, quizzes): user = User() user = user.findOne(int(id_user)) for quiz in quizzes.keys(): id_quiz = self.findOne(quizzes[quiz]) u = user.quiz_users.append(id_quiz) db.session.commit() return 200
def create_user(**kwargs): ''' Our method where we will create the user objects''' try: new_user = User(**kwargs) new_user.save() print("*" * 40) for key, value in kwargs.items(): print("{0} = {1}".format(key, value)) print("Added!") print("*" * 40) except pw.IntegrityError: user = kwargs.pop('username') print(user, "is already in the database!") pass
def put(self): """ The `put()` method will modify current_user's email and password """ content = request.json if content.get('username') is not None \ and content.get('email') is not None: check_user = User.objects(username=content.get('username'), email=content.get('email')).first() if check_user: return make_response("user existed", 400) updated_user = { "$set": { 'username': content.get('username'), 'email': content.get('email') } } query = { "username": current_user.username, "email": current_user.email } userCollection.update_one(query, updated_user) current_user.username = content.get('username') current_user.email = content.get('email') return make_response("account updated successfully", 200) return make_response("wrong parameters", 400)
def register_user(): data = json.loads(request.data) name = data.get('name', None) lastname = data.get('lastname', None) username = data.get('username', None) password = data.get('password', None) list = [name, lastname, username, password] for element in list: if (not element or element == ""): return jsonify({ "RESULT": "No ha brindado toda la informacion necesaria", "RETURNCODE": "-1", "METHOD": "POST" }) newUser = User(name, lastname, username, password, "client") result = UsersHandler.addUser(newUser) if result: return jsonify({ "RESULT": f"Usuario {username} Registrado con exito", "RETURNCODE": "0", "METHOD": "POST" }) else: return jsonify({ "RESULT": f"Ya existe un usario con username {username}", "RETURNCODE": "1", "METHOD": "POST" })
def add_user(): try: # generate database schema Base.metadata.create_all(engine) # create a new session session = Session() name = request.args.get('name') age = request.args.get('age') dni = request.args.get('dni') ctry = request.args.get('country') # create an employee user = User(name, age, dni, ctry) # persists data session.add(user) # commit and close session session.commit() session.close() return 'User added' except Exception as error: return str(error)
def preprocessing_from_database(self): try: self.cursor.execute( "CREATE TABLE users (uid integer, gid integer)") self.connect.commit() except: print("Table 'users' already exist") self.cursor.execute("SELECT * FROM users") users = self.cursor.fetchall() for user in users: if user[0] not in self.tracked_users: peer = peers_pb2.Peer(type=peers_pb2.PEERTYPE_PRIVATE, id=user[0]) self.tracked_users[user[0]] = User( self.bot.manager.get_outpeer(peer), [user[1]]) else: self.tracked_users[user[0]].groups.append(user[1]) try: self.cursor.execute( "CREATE TABLE reminder (time text, uid integer)") self.connect.commit() except: print("Table 'reminder' already exist") self.cursor.execute("SELECT * FROM reminder") reminder = self.cursor.fetchall() for remind in reminder: if remind[0] in self.reminder: self.reminder[remind[0]].append(remind[1]) else: self.reminder[remind[0]] = [remind[1]] self.tracked_users[remind[1]].remind_time = remind[0]
def register(): form = RegistrationForm(request.form) if request.method == 'POST' and form.validate(): user = User(form.username.data, form.email.data, form.password.data) db_session.add(user) flash('Thanks for registering') return redirect(url_for('login')) return render_template('register.html', form=form)
def add_tracked_user(self, peer): self.tracked_users[peer.id] = User( self.bot.manager.get_outpeer(peer), self.get_default_groups_for_user(peer)) for group_id in self.tracked_users[peer.id].groups: self.cursor.execute("INSERT INTO users values (?, ?)", [peer.id, group_id]) self.connect.commit()
def callback(): # Get authorization code Google sent back to you code = request.args.get("code") google_provider_cfg = get_google_provider_cfg() token_endpoint = google_provider_cfg["token_endpoint"] # Prepare and send a request to get tokens! Yay tokens! token_url, headers, body = client.prepare_token_request( token_endpoint, authorization_response=request.url, redirect_url=request.base_url, code=code) token_response = requests.post( token_url, headers=headers, data=body, auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET), ) # Parse the tokens! client.parse_request_body_response(json.dumps(token_response.json())) userinfo_endpoint = google_provider_cfg["userinfo_endpoint"] uri, headers, body = client.add_token(userinfo_endpoint) userinfo_response = requests.get(uri, headers=headers, data=body) if userinfo_response.json().get("email_verified"): user_data = userinfo_response.json() users_email = user_data["email"] picture = user_data["picture"] users_name = user_data["given_name"] else: return "User email not available or not verified by Google.", 400 user = User(name=users_name, email=users_email, profile_pic=picture) # # Doesn't exist? Add it to the database. if not User.get(users_email): User.create(users_name, users_email, picture) # # Begin user session by logging the user in login_user(user) # Send user back to homepage return redirect(url_for("index"))
def mkClients(self): users = [] for filename in glob.glob(os.path.join("clients", '*.txt')): info = [] with open(filename, "r", encoding="utf-8") as f: for line in f: info.append(line.strip('\n')) users.append(User(info[0], info[1], info[2], info[3:])) return users
def __init__(self): self.users = [] self.confirmed = {} kwargs1 = { "card": Card(0, "111111111111111", "111", date.fromisocalendar(2021, 1, 1)) } user1 = User(0, "user1", "*****@*****.**", "+111111111111", **kwargs1) self.users.append(user1)
def post(self): req_data = request.get_json() username = req_data['username'] follow_user = req_data['follows'] if User(username=username).follow_user(follow_user): return {'message': 'Relationship created'}, 200 else: return {'message': 'Relationship already created'}, 202
def launch_one_processing(processing_index, true_global, device, user_list_for_processings, local_model_queue, config, done): print("launch local model training process: ", device, processing_index) #print('true global', true_global) ready_model = models.__dict__[config.model]() ready_model.to(device).load_state_dict(true_global) #print('1') for user_index in user_list_for_processings[processing_index]: #print('2: ', ready_model, '|', true_global['fc2.bias'].device) ready_model.load_state_dict(true_global) #print('3') current_user = User(user_index=user_index, ready_model=ready_model, config = config) #print('4') current_user.local_train() #print('5') local_model_queue.put(move_to_device(copy.deepcopy(current_user.net.state_dict()), torch.device('cpu')), block=True) print("Ending local model training process: ", device, processing_index) done.wait() print("**Ending local model training process: ", device, processing_index)
def CreateNewUser(): name = input("Ingrese su nombre: ") last_name = input("Ingrese su apellido: ") dni = input("Ingrese su número de DNI: ") user = User(dni, name, last_name) addUser(user) password = input("Ingrese una clave: ") password = Password(user.dni, password) Password.save(password) print("Usuario Creado") return
def save(self, user) -> User: val = UserModel(username=user.get_name(), email=user.get_email(), phone=user.get_phone()) self.db.session.add(val) self.db.session.commit() res = UserModel.query.filter_by(username=user.get_name()) user = User(id=res.id, name=res.username, email=res.email, phone=res.phone) return user
def post(self, requestId=""): request = self.getRequestByUUID(requestId) request.requestAccepted = True self.response.status = 200 # Send everyone a push notification about the request being accepted gcm = GCM('AIzaSyC6y8uyxPSjxPABKieRa2iB2wLxFVyJuQY') data = {'param1': 'value1', 'param2': 'value2', 'appName': 'SafeWalk'} users = User.query().fetch() gcm_ids = [] for user in users: gcm_ids.append(user.gcmID) response = gcm.json_request(registration_ids=gcm_ids, data=data)
def __init__(self): self.users = [] kwargs1 = {"card": Card(1, "1111111111111111", "111", date.fromisocalendar(2021, 1, 1))} kwargs2 = {"card": Card(2, "2222222222222222", "222", date.fromisocalendar(2021, 1, 1))} deal2 = Deal(2, 2, 2) user1 = User(1, "user1", "*****@*****.**", "+000000000000", **kwargs1) user2 = User(2, "user2", "*****@*****.**", "+222222222222", **kwargs2) user2.register_seller_deal(deal2) user1.register_buyers_deal(deal2) self.users.append(user1) self.users.append(user2)
def AddUser(): try: data = request.data data = json.loads(data) name = data['name'] password = data['password'] user_id = data['user_id'] products_list = [] street = data['street'] city = data['city'] state = data['state'] location = {} location['state'] = state location['city'] = city location['street'] = street phone = data['phone'] email = data['email'] user = User(name=name, password = password, user_id = user_id, products_list = products_list, location = location, phone = phone, email = email) res = user.Save() return res, 200 except Exception as e: logger.debug('Exception in adduser method') return str(e),500
def post(self): id = self.request.get("UUID") user = (User.get_by_id(int(id))) if user == None: noUser = {} noUser['id'] = 0 self.response.write(json.dumps(noUser)) self.response.status = 200 return id = user.key.id() userID = {} userID['id'] = id self.response.write(json.dumps(userID)) self.response.status = 200
def on_join(data): user = User(data['username'], data['pwhash']) room = testgame.game_id #data['room'] if room in ROOMS: # add player ROOMS[room].add_player(user) # rebroadcast game object join_room(room) emit('game_update', ROOMS[room].to_json(), room=room) else: emit('error', {'error': 'Unable to join room. Room does not exist.'})
def post(self): req_data = request.get_json() username = req_data['username'] password = req_data['password'] if User(username=username).verify_password(password): access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) return { 'message': 'User has been registered', 'access_token': access_token, 'refresh_token': refresh_token }, 200 else: return {'message': 'User cannot be authenicated'}, 404
def on_create(data): user = User(data['username'], data['pwhash']) # create a game and add player gm = Game(data['name'], data['size']) gm.add_player(user) # save gamestate room = gm.game_id ROOMS[room] = gm # broadcast gamestate over socket join_room(room) emit('update_rooms', [room.to_json() for room in ROOMS.values()]) emit('join_room', room)
def on_leave(data): user = User(data['username'], data['pwhash']) room = data['room'] # prevent errors if not room in ROOMS.keys(): emit('error', {'error': 'Room does not exist.'}) return # remove player rooms[room].remove_player(user) # rebroadcast game object leave_room(room) emit('game_update', ROOMS[room].to_json(), room=room)
def login(): form = LoginForm() if request.method == 'POST': if form.validate_on_submit(): if bd.login(con, form.email.data): password_user = bd.get_password_profesor(con, form.email.data) if check_password_hash(password_user[0], form.password.data): rutProfesor = bd.get_rut_profesor(con, form.email.data) datosProfesor = bd.get_datos_profesor(con, rutProfesor[0]) user = User(datosProfesor[0], datosProfesor[1], datosProfesor[2], datosProfesor[3]) login_user(user, remember = form.remember_me.data) next_page = request.args.get('next', None) if not next_page or url_parse(next_page).netloc != '': next_page = url_for('asignaturas') return redirect(next_page) return render_template('login/login.html', formul = form)
def signup(): try: username = request.args.get("username") password = request.args.get("password") email = request.args.get("email") potentialUser = User(username, password, email) result = Users.validateUser(potentialUser) if result == "U": return jsonify({"Error": "Username is taken"}) if result == "E": return jsonify({"Error": "Email is taken"}) Users.createNewUser(potentialUser) return jsonify({"Result": "Success"}) except: return jsonify({ "Error": "POST request invalid" })
def get_config(): cfg = configparser.ConfigParser() cfg.read("config.cfg") keys = [] for string in str(cfg.get("DEFAULT", "keys")).strip().split(","): keys.append(string.strip()) list_users = [] for value in keys: newUser = User(value, cfg.get(value, "Username"), cfg.get(value, "Password"), cfg.get(value, "RewardLevel")) list_users.append(newUser) return list_users
def Enter(self): #User identification and building user objects while True: userName = input("Login: "******"Welcome {}!".format(userName)) self.__status = { user: User(user, self.accessNameRights.get(user), "Admin" if user == self.USERS[0] else "Guest", Rig.NAMERIGHTS) for user in self.USERS } return self.__status.get( userName) if userName in self.__status.keys() else "none" else: print("Profile not found")
def listModels(self): responseFields = {"name": True, "description": True, "created": True, "owner": True} userCollection = User._get_collection() models = None if current_user.is_authenticated(): user = current_user._get_current_object() # modelUserRelation = [own, shared, public, all] modelUserRelation = request.args.get("modelUserRelation", "own") if modelUserRelation == "own": searchFilter = {"owner": user.id} elif modelUserRelation == "shared": models = [] sharedModelAccess = MP.ModelUserAccess.objects( user=user, access__gte=MP.ModelUserAccess.ACCESS_DCT["list"] ) for modelAccess in sharedModelAccess: model = modelAccess.model models.append( { "_id": model.id, "name": model.name, "description": model.description, "created": model.created, "owner": model.owner.username, "access": modelAccess.access, } ) elif modelUserRelation == "public": searchFilter = {"publicAccess": {"$gte": Model.PUBLIC_ACCESS_DCT["list"]}} responseFields["publicAccess"] = True elif modelUserRelation == "all": if AdminPermission.can(): searchFilter = {} else: raise UnauthorizedError("Only administrators can list all models in the database") else: raise APIException("Invalid value for modelUserRelation, must be one of [own, shared, public, all]") else: searchFilter = {"publicAccess": {"$gte": Model.PUBLIC_ACCESS_DCT["list"]}} responseFields["publicAccess"] = True if models is None: models = list(Model._get_collection().find(searchFilter, responseFields, sort=[("name", 1)])) for model in models: model["owner"] = userCollection.find_one({"_id": model["owner"]})["username"] return makeJsonResponse(models)
def find_file(): name = input('Please enter name:\n') filename = '{}.json'.format(name).lower() if is_file(filename): with open(filename) as f: data = json.load(f) user = User.load_file(data) else: user = User(name) keep_running = True while keep_running: selection = input( "\nEnter 'a' to add a film, 'd' to delete a film \n" "Enter 's' to see the films, 'w' to set a film as watched \n" "Enter 'c' to see the list of watched movies\n" "Enter 'q to save and quit'\n") if selection == 'a': film_name = input('enter the film name').capitalize().strip() film_genre = input(' enter the film genre').capitalize().strip() print(user.add_movies(film_name, film_genre)) elif selection == 'd': movie_inp = input('enter a movie to delete from the list') print(user.delete_movie(movie_inp)) elif selection == 's': for movie in user.movies: print("'Name:' {} 'Genre:' {}, 'Watched:' {} ".format( movie.name, movie.genre, movie.watched)) elif selection == 'w': movie_name = input(' the film you ar e looking for?') print(user.change_status(movie_name)) elif selection == 'c': for movie in user.watched_movies(): print("'Name:' {} 'Genre:' {}, 'Watched:' {} ".format( movie.name, movie.genre, movie.watched)) elif selection == 'q': with open(filename, 'w') as json_file: json.dump(user.data_to_json(), json_file) keep_running = False
def get(self, requestId=""): """Respond to a GET request.""" user = self.getRequestByUUID(requestId) user.requestAccepted = True user.put() logging.info("requestAccepted = %s" %str(user.requestAccepted)) # Send everyone a push notification about the request being accepted gcm = GCM('AIzaSyC6y8uyxPSjxPABKieRa2iB2wLxFVyJuQY') data = {'param1': 'value1', 'param2': 'value2', 'appName': 'SafeWalk'} users = User.query().fetch() gcm_ids = [] for user in users: logging.info("user = %s" %str(user)) logging.info("this gcm_id = %s" %str(user.gcmID)) gcm_ids.append(user.gcmID) logging.info("gcm_ids = %s" %str(gcm_ids)) response = gcm.json_request(registration_ids=gcm_ids, data=data) self.response.status = 200; return