Exemplo n.º 1
0
def import_img_resource():
    directory = get_form_param('Directory', not_none=True)
    config = Config.query.filter().first()
    access_key_id = config and config.accessKeyId or current_app.config[
        'ACCESS_KEY_ID']
    access_key_secret = config and config.accessKeySecret or current_app.config[
        'ACCESS_KEY_SECRET']
    oss_access_endpoint = config and config.ossAccessEndpoint or current_app.config[
        'OSS_TEST_ACCESS_ENDPOINT']
    oss_access_bucket = config and config.ossAccessBucket or current_app.config[
        'OSS_TEST_ACCESS_BUCKET']
    auth = oss2.Auth(access_key_id, access_key_secret)
    bucket = oss2.Bucket(auth, oss_access_endpoint, oss_access_bucket)
    # resource_list = []
    for obj in oss2.ObjectIterator(bucket, prefix=directory):
        # 通过is_prefix方法判断obj是否为文件夹。
        src_type = obj.key.split('.')[-1]
        if src_type in current_app.config['ALLOWED_EXTENSIONS']:
            if db.session.query(Information).filter_by(
                    imgPath=obj.key).first() is None:
                new_info = Information()
                new_info.imgPath = obj.key
                new_info.imgDirectory = directory
                db.session.add(new_info)
    db.session.commit()
    return jsonify({'Code': 'Success', 'Message': 'Success'})
Exemplo n.º 2
0
def athlete(id):
    athlete = Athlete.query.get_or_404(id)
    events_participated = Event.query.join(TargetResults).filter(\
                          TargetResults.athlete_id == id).order_by(\
                          Event.date.desc()).all()

    # Event object required
    query = db.session.query(Event.id, Event.name)
    # All the event_id that an athlete participates
    subquery = db.session.query(TargetResults.event_id).filter(\
        TargetResults.athlete_id == id).distinct()
    # Event that an athlete has not target/resuts
    events = query.filter(~Event.id.in_(subquery)).all()

    target_form = NewTargetResultsForm()
    target_form.set_choices(events)
    information_form = InformationForm()
    if information_form.validate_on_submit():
        TYPE_ID = 1
        info = Information(body=information_form.information.data,
                           user_id=current_user.id,
                           type_id=TYPE_ID)
        athlete.informations.append(info)
        db.session.commit()
        return redirect(url_for('athlete.athlete', id=id))
    return render_template('athlete/athlete.html', athlete=athlete, target_form=target_form, \
        information_form=information_form, events_participated=events_participated)
Exemplo n.º 3
0
def pickup():
    order = Order.query.filter_by(id=session.get('order_id'),
                                  status="Incomplete").first()
    current_app.logger.debug(order.shipping_type)
    current_app.logger.debug(order.shipping_time)
    current_app.logger.debug(order.shipping)
    if not order:
        return redirect(url_for('shop.cart'))
    shipping = order.shipping if order.shipping else Information()
    form = PickUpForm(obj=order)
    form.sdate.choices = order.pickup_dates()
    current_app.logger.debug(form.sdate.choices)
    current_app.logger.debug(form.sdate.data)
    form.stime.choices = order.pickup_times()
    if form.validate_on_submit():
        form.populate_obj(order)
        order.shipping_type = 'pickup'
        order.set_shipping_time(form.sdate.data, form.stime.data)
        db.session.commit()
        return redirect(url_for('shop.confirm'))
    return render_template(
        'shop/shipping.html',
        form=form,
        order=order,
        shipping_type='pickup',
    )
Exemplo n.º 4
0
def add_injury(id):
    info = Information(user_id=current_user.id, athlete_id=id, type_id=1)
    db.session.add(info)
    db.session.commit()
    return jsonify({
        'id': info.id,
        'timestamp': info.timestamp.strftime("%Y-%m-%d"),
        'author_first_name': info.author.first_name,
        'author_last_name': info.author.last_name
    })
Exemplo n.º 5
0
    def get(self, request, **kwargs):
        if (request.user.person.is_community_posting_offer
                or not request.user.is_superuser):
            return redirect("index")

        id = kwargs.get("id")

        post = Post.objects.filter(id=id)
        if not post.exists():
            return redirect("index")
        post = post.first()

        information = Information(type=post.type,
                                  title=post.title,
                                  text=post.text,
                                  is_public=False)
        information.person = request.user.person
        information.save()
        # 削除
        Post.objects.filter(id=id).delete()

        request.session["notification"] = Notification.POST_APPROVE

        return redirect("post_list")
Exemplo n.º 6
0
def delivery():
    order = Order.query.filter_by(id=session.get('order_id'),
                                  status="Incomplete").first()
    if not order:
        return redirect(url_for('shop.cart'))
    shipping = order.shipping if order.shipping else Information()
    form = ShippingForm(obj=shipping)
    form.state.choices = Information.STATE_CHOICES
    if form.validate_on_submit():
        form.populate_obj(shipping)
        order.email = form.email.data
        order.phone = form.phone.data
        order.shipping_type = 'delivery'
        shipping.type = 'shipping'
        if current_user.is_authenticated:
            shipping.user_id = current_user.id
        if not shipping.id:
            db.session.add(shipping)
        db.session.commit()
        order.shipping_id = shipping.id
        db.session.commit()
        return redirect(url_for('shop.confirm'))
    form.state.data = 'Pennsylvania'
    if current_user.is_authenticated:
        if current_user.first_name and current_user.last_name:
            form.full_name.data = f'{current_user.first_name} {current_user.last_name}'
        if current_user.email:
            form.email.data = current_user.email
        if current_user.phone:
            form.phone.data = current_user.phone
    form.email.data = order.email
    form.phone.data = order.phone
    return render_template(
        'shop/shipping.html',
        form=form,
        order=order,
        shipping_type='delivery',
    )
Exemplo n.º 7
0
    def post(self, request):
        session_form_data = request.session.get("post_form_data")
        session_form_data_format = request.session.get("post_form_data_format")

        if not session_form_data or not session_form_data_format:
            return redirect("post_input")

        del request.session["post_form_data"]
        del request.session["post_form_data_format"]

        format = session_form_data_format
        if format == "event":
            form = PostForm(session_form_data)
        elif format == "information":
            form = InformationForm(session_form_data)

        if form.is_valid():
            if format == "event":
                type = InformationTypeEn.event.value
                text = make_post_text(form.cleaned_data)
            elif format == "information":
                type = form.cleaned_data["type"]
                text = form.cleaned_data["text"]

            if request.user.person.is_community_posting_offer:
                post = Post(
                    type=type,
                    title=form.cleaned_data["title"],
                    text=text,
                    person=request.user.person,
                )
                post.save()

                current_site = get_current_site(self.request)
                domain = current_site.domain
                context = {
                    "protocol":
                    "https" if self.request.is_secure() else "http",
                    "domain": domain,
                    "post": post,
                }

                subject = render_to_string("app/mail/post_confirm_subject.txt",
                                           context).strip()
                message = render_to_string("app/mail/post_confirm_message.txt",
                                           context).strip()
                send_mail(
                    subject,
                    message,
                    settings.EMAIL_HOST_USER,
                    ["*****@*****.**"],
                )

                request.session["notification"] = Notification.POST_OFFER
            elif request.user.is_superuser:
                information = Information(
                    type=type,
                    title=form.cleaned_data["title"],
                    text=text,
                    person=request.user.person,
                    is_public=form.cleaned_data["is_public"],
                )
                information.save()
                request.session["notification"] = Notification.POST
            elif request.user.is_staff:
                information = Information(
                    type=type,
                    title=form.cleaned_data["title"],
                    text=text,
                    person=request.user.person,
                    is_public=False,
                )
                information.save()
                request.session["notification"] = Notification.POST

            return redirect("post_list")

        return redirect("post_input")
Exemplo n.º 8
0
    rd29,
    rd30,
    rd31,
    rd32,
    rd33,
    rd34,
    rd35,
    rd36,
    rd37,
    rd38,
    rd39,
])
db.session.commit()

info1 = Information(info_type=0,
                    info_province='浙江',
                    info_title='测试数据1',
                    info_text='0 浙江')
info2 = Information(info_type=0,
                    info_province='北京',
                    info_title='测试数据2',
                    info_text='0 北京')
info3 = Information(info_type=2,
                    info_province='浙江',
                    info_title='测试数据3',
                    info_text='2 浙江')
info4 = Information(info_type=1,
                    info_province='浙江',
                    info_title='测试数据4',
                    info_text='1 浙江')
info5 = Information(info_type=3,
                    info_province='江苏',
Exemplo n.º 9
0
def get_information():
    id = get_form_param('Id', type='int', not_none=True)
    info_query = db.session.query(Information)
    info = info_query.filter_by(id=id).first()
    if info is not None:
        face_id = info.faceId
        next_filter = (Information.imgDirectory == info.imgDirectory,
                       Information.id > info.id)
        next_res = info_query.with_entities(Information.id).filter(
            *next_filter).order_by(Information.id).first()
        next_id = next_res and next_res[0] or None
        img_url = _get_img_url(info)
        record = _get_info_updated_record(info)
        if info.addTime is not None:
            if info.updateTime is not None:
                info_update = InformationUpdate.query.filter_by(
                    infoId=id).first()
            else:
                info_update = None
            if info_update is None:
                face_attribute = {
                    'Gender': {
                        'Value': info.gender
                    },
                    'Age': {
                        'Value': info.age
                    },
                    'HeadPose': info.to_head_pose(),
                    'EyeStatus': info.to_eye_status_dict(),
                    'Blur': {
                        'Blurness': {
                            'Threshold': info.blurThreshold,
                            'Value': info.blurValue
                        }
                    },
                    'FaceQuality': {
                        'Threshold': info.faceQualityThreshold,
                        'Value': info.faceQualityValue
                    }
                }
                info_data = {
                    'Id': id,
                    'FaceAttribute': face_attribute,
                    'FaceRectangle': info.to_face_rectangle_dict(),
                    'FaceId': face_id,
                    'EyeGlassStatus': info.to_eye_glass_status_dict()
                }
            else:
                face_attribute = {
                    'Gender': {
                        'Value': info_update.gender or info.gender
                    },
                    'Age': {
                        'Value': info_update.age or info.age
                    },
                    'HeadPose':
                    _get_info_update_dict(info.to_head_pose(),
                                          info_update.to_head_pose()),
                    'EyeStatus': {
                        'LeftEyeStatus':
                        _get_info_update_dict(
                            info.to_left_eye_status_dict(),
                            info_update.to_left_eye_status_dict()),
                        'RightEyeStatus':
                        _get_info_update_dict(
                            info.to_right_eye_status_dict(),
                            info_update.to_right_eye_status_dict()),
                    },
                    'Blur': {
                        'Blurness': {
                            'Threshold': info_update.blurThreshold
                            or info.blurThreshold,
                            'Value': info_update.blurValue or info.blurValue
                        }
                    },
                    'FaceQuality': {
                        'Threshold':
                        info_update.faceQualityThreshold
                        or info.faceQualityThreshold,
                        'Value':
                        info_update.faceQualityValue or info.faceQualityValue
                    }
                }
                info_data = {
                    'Id':
                    id,
                    'FaceAttribute':
                    face_attribute,
                    'FaceRectangle':
                    _get_info_update_dict(
                        info.to_face_rectangle_dict(),
                        info_update.to_face_rectangle_dict()),
                    'FaceId':
                    face_id,
                    'EyeGlassStatus':
                    _get_info_update_dict(
                        info.to_eye_glass_status_dict(),
                        info_update.to_eye_glass_status_dict())
                }
        # 尚未Index过的图片
        else:
            config = Config.query.filter().first()
            access_key_id = config and config.accessKeyId or current_app.config[
                'ACCESS_KEY_ID']
            access_key_secret = config and config.accessKeySecret or current_app.config[
                'ACCESS_KEY_SECRET']
            imm_region = config and config.region or current_app.config[
                'IMM_REGION']
            oss_access_bucket = config and config.ossAccessBucket or current_app.config[
                'OSS_TEST_ACCESS_BUCKET']
            my_client = Client(access_key_id,
                               access_key_secret,
                               imm_region,
                               timeout=60)
            project = config and config.project or current_app.config[
                'FACE_PROJECT']
            set_id = config and config.setId or current_app.config[
                'FACE_SET_ID']
            data = {
                'Project': project,
                'SrcUris':
                '["oss://%s/%s"]' % (oss_access_bucket, info.imgPath),
                'SetId': set_id,
                'Force': 1
            }
            status, response = sent_request(my_client, 'IndexFaceRequest',
                                            data)
            if status == httplib.OK:
                if len(response['SuccessDetails']) == 0:
                    return jsonify({
                        'Code': 'IndexActionProblem',
                        'Message': 'Please try again later.'
                    })
                info_data = response['SuccessDetails'][0]['Faces'][0]
                face_attribute = info_data['FaceAttribute']
                gender = face_attribute['Gender']['Value']
                age = face_attribute['Age']['Value']
                head_pose = face_attribute['HeadPose']
                yaw_angle = head_pose['YawAngle']
                pitch_angle = head_pose['PitchAngle']
                roll_angle = head_pose['RollAngle']

                # LeftEyeStatus
                left_eye_status = face_attribute['EyeStatus']['LeftEyeStatus']
                left_normal_glass_eye_open = left_eye_status[
                    'NormalGlassEyeOpen']
                left_no_glass_eye_close = left_eye_status['NoGlassEyeClose']
                left_occlusion = left_eye_status['Occlusion']
                left_no_glass_eye_open = left_eye_status['NoGlassEyeOpen']
                left_normal_glass_eye_close = left_eye_status[
                    'NormalGlassEyeClose']
                left_dark_glasses = left_eye_status['DarkGlasses']

                # RightEyeStatus
                right_eye_status = face_attribute['EyeStatus'][
                    'RightEyeStatus']
                right_normal_glass_eye_open = right_eye_status[
                    'NormalGlassEyeOpen']
                right_no_glass_eye_close = right_eye_status['NoGlassEyeClose']
                right_occlusion = right_eye_status['Occlusion']
                right_no_glass_eye_open = right_eye_status['NoGlassEyeOpen']
                right_normal_glass_eye_close = right_eye_status[
                    'NormalGlassEyeClose']
                right_dark_glasses = right_eye_status['DarkGlasses']

                # Blur
                blur_threshold = face_attribute['Blur']['Blurness'][
                    'Threshold']
                blur_value = face_attribute['Blur']['Blurness']['Value']

                # FaceQuality
                face_quality_threshold = face_attribute['FaceQuality'][
                    'Threshold']
                face_quality_value = face_attribute['FaceQuality']['Value']

                # FaceRectangle
                face_rectangle = info_data['FaceRectangle']
                rectangle_left = face_rectangle['Left']
                rectangle_top = face_rectangle['Top']
                rectangle_width = face_rectangle['Width']
                rectangle_height = face_rectangle['Height']

                face_id = info_data['FaceId']

                info.gender = gender
                info.age = age
                info.yawAngle = yaw_angle
                info.pitchAngle = pitch_angle
                info.rollAngle = roll_angle
                info.blurThreshold = blur_threshold
                info.blurValue = blur_value
                info.faceQualityThreshold = face_quality_threshold
                info.faceQualityValue = face_quality_value

                # LeftEyeStatus
                info.leftNormalGlassEyeOpen = left_normal_glass_eye_open
                info.leftNoGlassEyeClose = left_no_glass_eye_close
                info.leftOcclusion = left_occlusion
                info.leftNoGlassEyeOpen = left_no_glass_eye_open
                info.leftNormalGlassEyeClose = left_normal_glass_eye_close
                info.leftDarkGlasses = left_dark_glasses
                # RightEyeStatus
                info.rightNormalGlassEyeOpen = right_normal_glass_eye_open
                info.rightNoGlassEyeClose = right_no_glass_eye_close
                info.rightOcclusion = right_occlusion
                info.rightNoGlassEyeOpen = right_no_glass_eye_open
                info.rightNormalGlassEyeClose = right_normal_glass_eye_close
                info.rightDarkGlasses = right_dark_glasses

                # EyeGlassStatus
                info.leftEyeGlassStatus = Information.get_eye_status(
                    left_eye_status)
                info.rightEyeGlassStatus = Information.get_eye_status(
                    right_eye_status)

                # FaceRectangle
                info.faceRectangleTop = rectangle_top
                info.faceRectangleLeft = rectangle_left
                info.faceRectangleWidth = rectangle_width
                info.faceRectangleHeight = rectangle_height

                info.faceId = face_id
                info.addTime = time.strftime('%Y-%m-%d %H:%M:%S')

                db.session.add(info)
                db.session.commit()
                info_data['Id'] = info.id
                info_data['EyeGlassStatus'] = info.to_eye_glass_status_dict()
            elif status == httplib.INTERNAL_SERVER_ERROR:
                return jsonify({
                    'Code': 'IndexActionProblem',
                    'Message': 'Please try again later.',
                    'Next': next_id
                })
            else:
                logging.error('IndexActionError: %s' % str(response))
                raise CustomFlaskErr('UnknownError')

        return jsonify({
            'Code': 'Success',
            'Message': 'Success',
            'Data': {
                'Face': info_data,
                'Next': next_id,
                'ImgUrl': img_url,
                'Record': record
            }
        })
    else:
        raise CustomFlaskErr('NotFound.%s' % 'Id')