Python model.User() Examples

The following are 20 code examples of model.User(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module model , or try the search function .
Example #1
Source File: seed.py    From ProductGenius with MIT License 6 votes vote down vote up
def create_favorite_products():
    """Create User favorite products"""

    users = User.query.all()
    products = Product.query.all()

    for user in users:

        # Select a random number of products for the user to have from 0-15
        n_products = randint(0, 15)
        user_products = sample(products, n_products)

        for product in user_products:

            user.favorite_products.append(product)

    db.session.commit()



##################### Run script ################################# 
Example #2
Source File: seed.py    From ProductGenius with MIT License 6 votes vote down vote up
def create_users():
    """Creates fake users and loads them into the db"""

    print "====================="
    print "Creating fake users"

    # Instantiate a Faker object
    fake = Faker()
    fake.seed(435)

    # Create N user objects and add them to the db
    for i in range(N_USERS):

        user = User(name=fake.name(),
                    email=fake.email(),
                    password=fake.bs())

        db.session.add(user)

    db.session.commit() 
Example #3
Source File: auth.py    From gae-angular-material-starter with MIT License 6 votes vote down vote up
def create_or_get_user_db(auth_id, name, username, email='', **kwargs):
    """This function will first lookup if user with given email already exists.
    If yes then it will append auth_id for his record and saves it.
    If not we'll make sure to find unique username for this user (for the case of signing up via social account)
    and then store it into datastore"""
    user_db = model.User.get_by('email', email.lower())
    if user_db:
        user_db.auth_ids.append(auth_id)
        user_db.put()
        return user_db

    if isinstance(username, str):
        username = username.decode('utf-8')
    username = unidecode.unidecode(username.split('@')[0].lower()).strip()
    username = re.sub(r'[\W_]+', '.', username)
    new_username = username
    suffix = 1
    while not model.User.is_username_available(new_username):
        new_username = '%s%d' % (username, suffix)
        suffix += 1

    return create_user_db(auth_id, name, new_username, email=email, **kwargs) 
Example #4
Source File: auth.py    From gae-angular-material-starter with MIT License 6 votes vote down vote up
def create_user_db(auth_id, name, username, email='', verified=False, password='', **props):
    """Saves new user into datastore"""
    if password:
        password = util.password_hash(password)

    email = email.lower()
    user_db = model.User(
        name=name,
        email=email,
        username=username,
        auth_ids=[auth_id] if auth_id else [],
        verified=verified,
        token=util.uuid(),
        password_hash=password,
        **props
    )
    user_db.put()
    task.new_user_notification(user_db)
    return user_db 
Example #5
Source File: test_openmoves.py    From openmoves with MIT License 6 votes vote down vote up
def test_login_logout_other_user(self, tmpdir):

        username = 'other_user'
        password = 'Paßswörd→✓≈'

        with app.test_request_context():
            user = User(username=username, active=True)
            user.password = openmoves.app_bcrypt.generate_password_hash(password, 10)
            db.session.add(user)
            db.session.commit()

        response = self._login(username=username, password=password)
        response_data = self._validate_response(response, tmpdir)
        assert '<title>OpenMoves – Dashboard</title>' in response_data
        assert username in response_data

        response = self.client.get('/logout', follow_redirects=True)
        response_data = self._validate_response(response, tmpdir)
        assert '<title>OpenMoves</title>' in response_data
        assert username not in response_data 
Example #6
Source File: test_openmoves.py    From openmoves with MIT License 6 votes vote down vote up
def test_login_valid(self, tmpdir):

        username = 'test_user'
        password = 'test password'

        with app.test_request_context():
            User.query.delete(synchronize_session=False)

            user = User(username=username, active=True)
            user.password = openmoves.app_bcrypt.generate_password_hash(password, 10)
            db.session.add(user)
            db.session.commit()

        response = self._login()
        response_data = self._validate_response(response, tmpdir)
        assert "<title>OpenMoves – Dashboard</title>" in response_data 
Example #7
Source File: commands.py    From openmoves with MIT License 6 votes vote down vote up
def run(self, username, password=None):
        with self.app_context():
            if not password:
                wordfile = xp.locate_wordfile()
                mywords = xp.generate_wordlist(wordfile=wordfile, min_length=5, max_length=8)
                password = xp.generate_xkcdpassword(mywords, acrostic="ambit")
                print("generated password: '%s'" % password)

            assert not User.query.filter_by(username=username).scalar(), "user already exists"

            user = User(username=username)
            user.password = self.app_bcrypt.generate_password_hash(password, 10)

            if user.password is not str:
                user.password = user.password.decode('utf-8')

            user.active = True
            db.session.add(user)
            db.session.commit()

            print("created user '%s' in '%s'" % (user.username, db.engine.url)) 
Example #8
Source File: user.py    From github-stats with MIT License 6 votes vote down vote up
def user_list():
  args = parser.parse({
    'email': wf.Str(missing=None),
    'permissions': wf.DelimitedList(wf.Str(), delimiter=',', missing=[]),
  })
  user_dbs, cursors = model.User.get_dbs(
    email=args['email'], prev_cursor=True,
  )
  permissions = list(UserUpdateForm._permission_choices)
  permissions += args['permissions']
  return flask.render_template(
    'user/user_list.html',
    html_class='user-list',
    title='User List',
    user_dbs=user_dbs,
    next_url=util.generate_next_url(cursors['next']),
    prev_url=util.generate_next_url(cursors['prev']),
    api_url=flask.url_for('api.admin.user.list'),
    permissions=sorted(set(permissions)),
  )


###############################################################################
# User Update
############################################################################### 
Example #9
Source File: test_openmoves.py    From openmoves with MIT License 6 votes vote down vote up
def test_add_user(self):
        with app.test_request_context():
            assert User.query.count() == 0

        cmd = AddUser(lambda: app.app_context(), app_bcrypt=openmoves.app_bcrypt)
        cmd.run(username='test_user')

        with app.test_request_context():
            assert User.query.count() == 1
            assert User.query.filter_by(username='test_user').one()

        with pytest.raises(AssertionError) as e:
            cmd.run(username='test_user')
        assert "user already exists" in str(e.value)

        cmd.run(username='test_user2')
        with app.test_request_context():
            assert User.query.count() == 2
            assert User.query.filter_by(username='test_user').one() != User.query.filter_by(username='test_user2').one() 
Example #10
Source File: commands.py    From openmoves with MIT License 5 votes vote down vote up
def run(self, username, filename):
        user = User.query.filter_by(username=username).one()
        with open(filename, 'r') as f:
            move = move_import(f, filename, user)
            if move:
                print("imported move %d" % move.id) 
Example #11
Source File: seed.py    From ProductGenius with MIT License 5 votes vote down vote up
def extract_product_keywords_from_reviews():
    """Extract the top ten positive and negative keywords from reviews"""

    print "======================"
    print "extracting keywords"

    for product in Product.query.all():

        # Loop through all products. Run naive bayes to extract the 10
        # keywords with the highest likelihood of being in positive
        # and negative reviews

        # Include the product's name as stop words
        more_stop_words = product.title.split(' ')
        more_stop_words = [w.lower() for w in more_stop_words]

        # keywords is a tuple with a list of positive keywords and negative keywords
        keywords = get_keywords_from_naive_bayes(product, more_stop_words)

        # need to do tuple unpacking
        product.pos_words = keywords[0]
        product.neg_words = keywords[1]

        db.session.commit()


##################### Seed User data ############################### 
Example #12
Source File: strava.py    From openmoves with MIT License 5 votes vote down vote up
def find_device(current_user):
    device_ids = [device_id for device_id, in db.session.query(func.distinct(Move.device_id))
        .join(User)
        .join(Device)
        .filter(Device.name != gpx_import.GPX_DEVICE_NAME)
        .filter(Move.user == current_user).all()]

    if not device_ids:
        return None

    assert len(device_ids) == 1
    device_id = device_ids[0]
    device = db.session.query(Device).filter_by(id=device_id).one()
    return device 
Example #13
Source File: auth.py    From github-stats with MIT License 5 votes vote down vote up
def get_user_db_from_email(email, password):
  user_dbs, cursors = model.User.get_dbs(email=email, active=True, limit=2)
  if not user_dbs:
    return None
  if len(user_dbs) > 1:
    flask.flash('''We are sorry but it looks like there is a conflict with
        your account. Our support team has been informed and we will get
        back to you as soon as possible.''', category='danger')
    task.email_conflict_notification(email)
    return False

  user_db = user_dbs[0]
  if user_db.password_hash == util.password_hash(user_db, password):
    return user_db
  return None 
Example #14
Source File: auth.py    From github-stats with MIT License 5 votes vote down vote up
def create_user_db(auth_id, name, username, email='', verified=False, **props):
  email = email.lower() if email else ''
  if verified and email:
    user_dbs, cursors = model.User.get_dbs(email=email, verified=True, limit=2)
    if len(user_dbs) == 1:
      user_db = user_dbs[0]
      user_db.auth_ids.append(auth_id)
      user_db.put()
      task.new_user_notification(user_db)
      return user_db

  if isinstance(username, str):
    username = username.decode('utf-8')
  username = unidecode.unidecode(username.split('@')[0].lower()).strip()
  username = re.sub(r'[\W_]+', '.', username)
  new_username = username
  n = 1
  while not model.User.is_username_available(new_username):
    new_username = '%s%d' % (username, n)
    n += 1

  user_db = model.User(
    name=name,
    email=email,
    username=new_username,
    auth_ids=[auth_id] if auth_id else [],
    verified=verified,
    token=util.uuid(),
    **props
  )
  user_db.put()
  task.new_user_notification(user_db)
  return user_db 
Example #15
Source File: auth.py    From github-stats with MIT License 5 votes vote down vote up
def form_with_recaptcha(form):
  should_have_recaptcha = cache.get_auth_attempt() >= config.RECAPTCHA_LIMIT
  if not (should_have_recaptcha and config.CONFIG_DB.has_recaptcha):
    del form.recaptcha
  return form


###############################################################################
# User related stuff
############################################################################### 
Example #16
Source File: auth.py    From github-stats with MIT License 5 votes vote down vote up
def signup():
  next_url = util.get_next_url()
  form = None
  if config.CONFIG_DB.has_email_authentication:
    form = form_with_recaptcha(SignUpForm())
    save_request_params()
    if form.validate_on_submit():
      user_db = model.User.get_by('email', form.email.data)
      if user_db:
        form.email.errors.append('This email is already taken.')

      if not form.errors:
        user_db = create_user_db(
          None,
          util.create_name_from_email(form.email.data),
          form.email.data,
          form.email.data,
        )
        user_db.put()
        task.activate_user_notification(user_db)
        cache.bump_auth_attempt()
        return flask.redirect(flask.url_for('welcome'))

  if form and form.errors:
    cache.bump_auth_attempt()

  title = 'Sign up' if config.CONFIG_DB.has_email_authentication else 'Sign in'
  return flask.render_template(
    'auth/auth.html',
    title=title,
    html_class='auth',
    next_url=next_url,
    form=form,
    **urls_for_oauth(next_url)
  )


###############################################################################
# Sign out stuff
############################################################################### 
Example #17
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_reset(token=None):
  user_db = model.User.get_by('token', token)
  if not user_db:
    flask.flash('That link is either invalid or expired.', category='danger')
    return flask.redirect(flask.url_for('welcome'))

  if auth.is_logged_in():
    flask_login.logout_user()
    return flask.redirect(flask.request.path)

  form = UserResetForm()
  if form.validate_on_submit():
    user_db.password_hash = util.password_hash(user_db, form.new_password.data)
    user_db.token = util.uuid()
    user_db.verified = True
    user_db.put()
    flask.flash('Your password was changed succesfully.', category='success')
    return auth.signin_user_db(user_db)

  return flask.render_template(
    'user/user_reset.html',
    title='Reset Password',
    html_class='user-reset',
    form=form,
    user_db=user_db,
  )


###############################################################################
# User Activate
############################################################################### 
Example #18
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_forgot(token=None):
  if not config.CONFIG_DB.has_email_authentication:
    flask.abort(418)

  form = auth.form_with_recaptcha(UserForgotForm(obj=auth.current_user_db()))
  if form.validate_on_submit():
    cache.bump_auth_attempt()
    email = form.email.data
    user_dbs, cursors = util.get_dbs(
      model.User.query(), email=email, active=True, limit=2,
    )
    count = len(user_dbs)
    if count == 1:
      task.reset_password_notification(user_dbs[0])
      return flask.redirect(flask.url_for('welcome'))
    elif count == 0:
      form.email.errors.append('This email was not found')
    elif count == 2:
      task.email_conflict_notification(email)
      form.email.errors.append(
        '''We are sorry but it looks like there is a conflict with your
        account. Our support team is already informed and we will get back to
        you as soon as possible.'''
      )

  if form.errors:
    cache.bump_auth_attempt()

  return flask.render_template(
    'user/user_forgot.html',
    title='Forgot Password?',
    html_class='user-forgot',
    form=form,
  )


###############################################################################
# User Reset
############################################################################### 
Example #19
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_verify(token):
  user_db = auth.current_user_db()
  if user_db.token != token:
    flask.flash('That link is either invalid or expired.', category='danger')
    return flask.redirect(flask.url_for('profile'))
  user_db.verified = True
  user_db.token = util.uuid()
  user_db.put()
  flask.flash('Hooray! Your email is now verified.', category='success')
  return flask.redirect(flask.url_for('profile'))


###############################################################################
# User Forgot
############################################################################### 
Example #20
Source File: user.py    From github-stats with MIT License 5 votes vote down vote up
def user_update(user_id=0):
  if user_id:
    user_db = model.User.get_by_id(user_id)
  else:
    user_db = model.User(name='', username='')
  if not user_db:
    flask.abort(404)

  form = UserUpdateForm(obj=user_db)
  for permission in user_db.permissions:
    form.permissions.choices.append((permission, permission))
  form.permissions.choices = sorted(set(form.permissions.choices))
  if form.validate_on_submit():
    if not util.is_valid_username(form.username.data):
      form.username.errors.append('This username is invalid.')
    elif not model.User.is_username_available(form.username.data, user_db.key):
      form.username.errors.append('This username is already taken.')
    else:
      form.populate_obj(user_db)
      if auth.current_user_key() == user_db.key:
        user_db.admin = True
        user_db.active = True
      user_db.put()
      return flask.redirect(flask.url_for(
        'user_list', order='-modified', active=user_db.active,
      ))

  return flask.render_template(
    'user/user_update.html',
    title=user_db.name or 'New User',
    html_class='user-update',
    form=form,
    user_db=user_db,
    api_url=flask.url_for('api.admin.user', user_key=user_db.key.urlsafe()) if user_db.key else ''
  )


###############################################################################
# User Verify
###############################################################################