Ejemplo n.º 1
0
def manage_p(request, url):
    article = Person.objects.get(pk=url)
    if request.method == 'GET':
        form = AddPersonForm(instance=article)
        return render_to_response('m_person.html', {'form': form},
                                  context_instance=RequestContext(request))
    form = AddPersonForm(request.POST or None,
                         request.FILES or None,
                         instance=article)
    response = lambda data: HttpResponse(simplejson.dumps(data),
                                         mimetype="application/json")
    if form.is_valid():
        form.save()
        return response('Data saved')
    else:
        errors = str()
        for data in form.errors.values():
            errors += str(data)
        return response(errors)
Ejemplo n.º 2
0
def admin_add_student():
    form = AddPersonForm()
    if form.validate_on_submit():
        if form.addtype.data == 'single':
            id = form.id.data
            name = form.name.data
            email = form.email.data
            password = form.password.data
            if id is None or id == "":
                flash(u'学号不能为空')
                return render_template('adminAddStudent.html', form=form)
            if not id.isdigit():
                flash(u'学号必须为整数')
                return render_template('adminAddStudent.html', form=form)
            student = Student.query.get(id)
            if student is not None:
                flash(u'学生已经存在,不能重复添加')
                return render_template('adminAddStudent.html', form=form)
            if password is None or password == "":  #:如果密码为空,则默认密码为学号
                password = str(id)
            student = Student(id=id, name=name, email=email, password=password)
            db.session.add(student)
            db.session.commit()
            flash(u'添加学生成功')
            return redirect(url_for('student_list'))
        else:
            errorList = []
            isError = False
            isAdd = False
            address = upload(form.file.data,
                             ['xls', 'xlsx'])  #:将文件保存到服务器并返回文件地址
            if address is None:
                flash(u'请选择正确的文件格式上传文件')
                return render_template('adminAddStudent.html', form=form)
            #:使用xlrd模块读取excel文件
            data = xlrd.open_workbook(address)
            table = data.sheets()[0]
            for i in range(table.nrows):
                line = table.row_values(i)
                try:
                    if type(eval(str(line[0]))) == float or str(
                            line[0]).isdigit():
                        id = int(line[0])
                        student = Student.query.get(id)
                        if student is not None:
                            isError = True
                            errorList.append(id)
                            continue
                        isAdd = True
                        name = line[1]
                        email = str(line[2])
                        password = str(line[3])
                        if password is None or password == "":
                            password = str(id)
                        student = Student(id=id,
                                          name=name,
                                          email=email,
                                          password=password)
                        db.session.add(student)
                except:
                    continue  #:对不符合的数据不做处理,直接跳过
            #:删除上传的文件
            if os.path.exists(address):
                os.remove(address)
            #:对错误结果进行处理
            if isError:
                message = u'学生'
                for error in errorList:
                    message += '"' + str(error) + '" '
                message += u'已经存在,不能重复添加'
                flash(message)
                db.session.commit()
                return render_template('adminAddStudent.html', form=form)
            elif isAdd:
                db.session.commit()
                flash(u'全部学生添加成功')
                return redirect(url_for('student_list'))
            else:
                flash(u'请选择正确的文件格式上传文件')
                return render_template('adminAddStudent.html', form=form)
    return render_template('adminAddStudent.html', form=form)
Ejemplo n.º 3
0
def add_person():
    form = AddPersonForm()
    if form.validate_on_submit():
        person_email = form.email.data
        person_registered = bool(
            Person.query.filter_by(email=form.email.data).first())
        if person_registered:
            # flash(('danger', f'Пользователь с email "<strong>{person_email}</strong>" уже зарегистрирован'))
            return jsonify({
                'status':
                'error',
                'message':
                f'Пользователь с email "<strong>{person_email}</strong>" уже зарегистрирован',
            })
        else:
            image = form.image.data
            if not image:
                return jsonify({
                    'status': 'error',
                    'error': 'Image is not specified'
                })
            if isinstance(image, str):
                try:
                    image = requests.get(image).content
                except RequestException:
                    return jsonify({
                        'status': 'error',
                        'error': 'Неверно указан URL'
                    })

            response = recognition_api.post(
                f'http://{FACE_RECOGNITION_SERVER}/add-person',
                files={
                    'image': image
                }).json()
            if response['status'] == 'success':
                first_name = form.first_name.data
                last_name = form.last_name.data
                person_id = response['person_id']
                person = Person(
                    id=person_id,
                    email=person_email,
                    first_name=first_name,
                    last_name=last_name,
                    additional_info=form.addition_info.data.strip() or None)
                db.session.add(person)
                db.session.commit()
                return jsonify({
                    'status':
                    'success',
                    'message':
                    f'<strong>{first_name} {last_name}</strong> успешно добавлен',
                })
                # flash(('success', f'{first_name} {last_name} успешно добавлен'))
                # form = AddPersonForm()
            else:
                # flash(('danger', response['error']))
                return jsonify({
                    'status': 'error',
                    'message': response['error'],
                })
    context = {
        'init_js_script': 'AddPerson',
        'recognition_server': FACE_RECOGNITION_SERVER,
        'form': form
    }
    return render_template('add_person.html', **context)