Пример #1
0
def import_db_from_json():
    """Imports a collection of links from a 'db.json' file (DESTRUCTIVE)."""
    app.logger.info(app.config.get('SQLALCHEMY_DATABASE_URI'))
    with open('db.json') as f:
        if prompt_bool("May I import links from 'db.json'"):
            app.logger.info('dropping all tables...')
            db.drop_all()
            app.logger.info('creating all tables...')
            db.create_all()

            content = json.load(f)

            app.logger.info('importing users...')
            if 'users' in content:
                for u in content['users']:
                    user = User(email=u['email'])
                    g.user = user
                    user.locale = u.get('locale', '')
                    user.timezone = u.get('timezone', '')
                    user.is_active = u.get('is_active', True)
                    db.session.add(user)
                db.session.commit()

            app.logger.info('importing tags...')
            tags = []
            for t in content.get('links', []):
                tagname = t.get('tag', '')
                if not tagname in tags:
                    tags.append(tagname)
            for tagname in tags:
                tag = Tag.query.filter_by(name=tagname).first()
                if tag is None:
                    try:
                        tag = Tag(name=tagname)
                        db.session.add(tag)
                    except Exception, e:
                        app.logger.error('error creating tag "%s"' % e)
                        continue
            db.session.commit()

            app.logger.info('importing bookmarks...')
            for l in content.get('links', []):
                link = Bookmark(name=l['name'], url=l['url'])
                link.menu = l.get('menu', None)
                link.public = l.get('public', False)
                link.clicks = l.get('clicks', 0)
                if 'user_email' in l:
                    user = User.query.filter_by(email=l['user_email']).first()
                    link.user_id = user.id
                # for tagname in l.get('tags', []):
                tagname = l.get('tag', '')
                tag = Tag.query.filter_by(name=tagname).first()
                link.tags.append(tag)
                db.session.add(link)
            db.session.commit()
Пример #2
0
def _users_from_json(app, content=''):
    if 'users' in content:
        for u in content['users']:
            user = User.query.filter_by(email=u['email']).first()
            if user is None:
                user = User()
            user.email = u['email']
            user.pw_hash = u['pw_hash']
            user.active = u['active']
            user.superuser = u['superuser']
            if 'locale' in u:
                user.locale = u['locale']

            app.logger.debug('adding user: %s' % user)
            db.session.add(user)
        db.session.commit()
Пример #3
0
def edit(user_id=None):
    """Create user for admins and edit for admins and users."""
    if not ModuleAPI.can_write('user') and\
            (current_user.is_anonymous or current_user.id != user_id):
        return abort(403)

    # Select user
    if user_id:
        user = User.query.get_or_404(user_id)
    else:
        user = User()

    user.avatar = UserAPI.has_avatar(user_id)

    if ModuleAPI.can_write('user'):
        form = EditUserForm(request.form, user)
        is_admin = True
    else:
        form = EditUserInfoForm(request.form, user)
        is_admin = False

    # Add education.
    educations = Education.query.all()
    form.education_id.choices = [(e.id, e.name) for e in educations]

    def edit_page():
        return render_template('user/edit.htm', form=form, user=user,
                               is_admin=is_admin)

    if form.validate_on_submit():

        # Only new users need a unique email.
        query = User.query.filter(User.email == form.email.data)
        if user_id:
            query = query.filter(User.id != user_id)

        if query.count() > 0:
            flash(_('A user with this e-mail address already exist.'),
                  'danger')
            return edit_page()

        # Because the user model is constructed to have an ID of 0 when it is
        # initialized without an email adress provided, reinitialize the user
        # with a default string for email adress, so that it will get a unique
        # ID when committed to the database.
        if not user_id:
            user = User('_')

        group = Group.query.filter(Group.name == 'all').first()
        group.add_user(user)

        try:
            user.update_email(form.email.data.strip())
        except HttpError as e:
            if e.resp.status == 404:
                flash(_('According to Google this email does not exist. '
                        'Please use an email that does.'), 'danger')
                return edit_page()
            raise(e)

        user.first_name = form.first_name.data.strip()
        user.last_name = form.last_name.data.strip()
        user.locale = form.locale.data
        if ModuleAPI.can_write('user'):
            user.has_paid = form.has_paid.data
            user.honorary_member = form.honorary_member.data
            user.favourer = form.favourer.data
            user.disabled = form.disabled.data
            user.alumnus = form.alumnus.data
        user.student_id = form.student_id.data.strip()
        user.education_id = form.education_id.data
        user.birth_date = form.birth_date.data
        user.study_start = form.study_start.data
        user.receive_information = form.receive_information.data

        user.phone_nr = form.phone_nr.data.strip()
        user.address = form.address.data.strip()
        user.zip = form.zip.data.strip()
        user.city = form.city.data.strip()
        user.country = form.country.data.strip()

        if form.password.data != '':
            user.password = bcrypt.hashpw(form.password.data, bcrypt.gensalt())

        db.session.add(user)
        db.session.add(group)
        db.session.commit()

        avatar = request.files['avatar']
        if avatar:
            UserAPI.upload(avatar, user.id)

        if user_id:
            copernica.update_user(user)
            flash(_('Profile succesfully updated'))
        else:
            copernica.update_user(user, subscribe=True)
            flash(_('Profile succesfully created'))
        return redirect(url_for('user.view_single', user_id=user.id))
    else:
        flash_form_errors(form)

    return edit_page()