Exemple #1
0
def m_events_update():
    id = _g("id")
    if not id:
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    action_type = _g("action_type")
    if not action_type in ["m", "c", "p"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    e = connection.Events.one({"id": int(id)})

    if action_type == "m":
        return render_template("m_events_update.html", event=e)
    elif action_type == "c":  #cancel
        e.status = 2
        e.save()
        msg = connection.Message()
        msg.id = msg.getID()
        msg.subject = u"Cancel Booking Event"
        msg.content = u"%s cancel the booking request." % session[
            'user_profile']['name']
        msg.uid = e.uid
        msg.save()
        return jsonify({"success": True, "message": "Update successfully !"})
    elif action_type == "p":  #confirmed
        e.status = 1
        e.save()
        msg = connection.Message()
        msg.id = msg.getID()
        msg.subject = u"Confirm Booking Event"
        msg.content = u"%s confirm the booking request." % session[
            'user_profile']['name']
        msg.uid = e.uid
        msg.save()
        return jsonify({"success": True, "message": "Update successfully !"})
Exemple #2
0
def m_events_update():
    id = _g("id")
    if not id :
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))
    action_type = _g("action_type")
    if not action_type in ["m", "c", "p"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(url_for("m_events_list"))

    e = DBSession.query(Events).get(id)
#    e = connection.Events.one({"id" : int(id)})

    if action_type == "m":
        return render_template("m_events_update.html", event = e)
    elif action_type == "c": #cancel       
        e.status = 2
        DBSession.add(Message(subject = u"Cancel Booking Event", user_id = e.user_id,
                              content = u"%s cancel the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
    elif action_type == "p": #confirmed
        e.status = 1
        DBSession.add(Message(subject = u"Confirm Booking Event", user_id = e.user_id,
                              content = u"%s confirm the booking request." % session['user_profile']['name']))
        DBSession.commit()
        return jsonify({"success" : True, "message" : "Update successfully !"})
Exemple #3
0
def getDoctorDetail():
    fields = ["lang", "doctorID", "clinicID"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    lang = _g("lang")
    dp = DBSession.query(DoctorProfile).get(_g("doctorID"))
    base_info = dp.getUserProfile()

    c = DBSession.query(Clinic).get(_g("clinicID"))
    latitude = longtitude = None
    if c.coordinate:
        latitude, longtitude = c.coordinate.split(",")

    return jsonify(
        {
            "result": 1,
            "data": {
                "doctorID": dp.id,
                "name": {"zh_HK": base_info["display_name_tc"], "zh_CN": base_info["display_name_sc"]}.get(
                    lang, base_info["display_name"]
                ),
                "desc": dp.desc,
                "tel": c.tel,
                "address": {"zh_HK": c.address_tc, "zh_CN": c.address_sc}.get(lang, c.address),
                "image": base_info["image_url"],
                "mapLocationX": longtitude,
                "mapLocationY": latitude,
                "rating": dp.rating,
            },
        }
    )
def put_facebook_page():
    """
    (PUT: social_connect/facebook/page)
    """
    from unifide_backend.action.social.facebook.action import get_fb_user, get_fb_page_list, put_fb_page

    verb = "put"
    noun = "social_connect/facebook/page"

    #req_vars
    user_id = request.form.get("user_id")
    brand_name = request.form.get("brand_name")
    fb_page_id = request.form.get("page_id")

    #auth check
    #to-do

    fbUser = get_fb_user(user_id, brand_name)

    page_list = get_fb_page_list(fbUser.fb_id, fbUser.access_token)
    for page in page_list:
        if page["id"] == fb_page_id:
            fb_page_obj = put_fb_page(fbUser, brand_name, page)
            break

    if fb_page_obj is None:
        return jsonify(({"status": "error",
                         "error": "Fail to save page access token"}))

    return jsonify({"status": "ok"})
Exemple #5
0
def getComment():
    fields = ["lang", "doctorID"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})
    comments = (
        DBSession.query(DoctorComment, User)
        .filter(
            and_(
                DoctorComment.active == 0,
                User.active == 0,
                DoctorComment.create_by_id == User.id,
                DoctorComment.doctor_id == _g("doctorID"),
            )
        )
        .order_by(desc(DoctorComment.create_time))
    )
    return jsonify(
        {
            "result": 1,
            "data": [
                {"userID": comment.create_by_id, "name": unicode(user), "comment": comment.content}
                for (comment, user) in comments
            ],
        }
    )
Exemple #6
0
def save_events():
    uid = request.values.get("uid", None)
    did = request.values.get("did", None)
    d = request.values.get("d", None)
    t = request.values.get("t", None)

    if not uid or not did or not d or not t:
        return jsonify({"success": False, "message": "The required info is not supplied !"})
    format_date = lambda v: "-".join([v[:4], v[4:6], v[-2:]])

    try:
        e = Events(user_id=uid, doctor_id=did, date=d, time=t, remark=request.values.get("remark", None))
        DBSession.add(e)
        doctor = DBSession.query(DoctorProfile).get(did).getUserProfile()
        m = Message(
            subject=u"Booking request submit",
            user_id=session["user_profile"]["id"],
            content=u"%s make a booking with doctor %s at %s , %s."
            % (session["user_profile"]["name"], doctor["name"], t, format_date(d)),
        )
        DBSession.add(m)
        DBSession.commit()
        return jsonify({"success": True, "message": "Save your request successfully !", "event_time": e.time})
    except:
        DBSession.rollback()
        app.logger.error(traceback.format_exc())
        return jsonify({"success": False, "message": "Error occur when submiting the request !"})
def connect_facebook():
    """
    (PUT: social_connect/facebook)
    """
    from unifide_backend.action.social.facebook.sdk import get_access_token_from_code
    from unifide_backend.action.social.facebook.action import get_fb_id, save_fb_user
    from unifide_backend.action.admin.user.action import get_user

    verb = "put"
    noun = "social_connect/facebook"

    #req_vars
    user_id = request.form.get("user_id")
    facebook_code = request.form.get("code")
    brand_name = request.form.get("brand_name")

    #auth check
    #to-do

    user = get_user(user_id)
    result = get_access_token_from_code(facebook_code, FB_REDIRECT_URI, FB_APP_ID, FB_APP_SECRET)
    access_token = result["access_token"]
    token_expiry = result["expires"] if "expires" in result else None
    fb_id = get_fb_id(access_token)
    fb_user = save_fb_user(user.get_id(), brand_name, fb_id, access_token, token_expiry)

    if fb_user is None:
        return jsonify({"status": "error",
                        "error": "Fail to save user access token"})

    return jsonify({"status": "ok"})
def connect_twitter():
    """
    (PUT: social_connect/twitter)
    """
    from unifide_backend.action.social.twitter.action import get_tw_user_oauth, save_tw_user

    verb = "put"
    noun = "social_connect/twitter"

    #req_vars
    user_id = request.form.get("user_id")
    brand_name = request.form.get("brand_name")
    verifier = request.form.get("oauth_verifier")

    auth = tweepy.OAuthHandler(TW_CONSUMER_KEY, TW_CONSUMER_SECRET)
    tw_user_oauth = get_tw_user_oauth(user_id, brand_name)
    if tw_user_oauth is None:
        return jsonify({"status": "error",
                        "error": "Failed to get user oauth key and secret"})

    auth.set_request_token(tw_user_oauth.oauth_key, tw_user_oauth.oauth_secret)

    try:
        auth.get_access_token(verifier)
    except tweepy.TweepError:
        print 'Error! Failed to get access token.'
        return jsonify({"status": "error",
                        "error": "Failed to get access token"})

    tw_user = save_tw_user(user_id, brand_name, auth.access_token.key, auth.access_token.secret)
    if tw_user is None:
        return jsonify({"status": "error",
                        "error": "Failed to save twitter user"})

    return jsonify({"status": "ok"})
def auth_twitter():
    """
    (GET: social_connect/twitter/auth)
    """
    from unifide_backend.action.social.twitter.action import save_tw_user_oauth

    verb = "get"
    noun = "social_connect/twitter/auth"

    #req_vars
    user_id = request.args.get("user_id")
    brand_name = request.args.get("brand_name")

    auth = tweepy.OAuthHandler(TW_CONSUMER_KEY, TW_CONSUMER_SECRET, TW_REDIRECT_URI + brand_name + "/")

    try:
        redirect_url = auth.get_authorization_url()
    except tweepy.TweepError:
        print 'Error! Failed to get request token.'
        return jsonify({"status": "error",
                        "error": "Failed to get request token."})

    save_tw_user_oauth(user_id, brand_name, auth.request_token.key, auth.request_token.secret)

    return jsonify({"status": "ok",
                    "auth_url": redirect_url})
Exemple #10
0
def getDoctorList():
    fields = ["lang", "locationIndex"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    ds = []
    lang = _g("lang")
    locationIndex = _g("locationIndex")
    for c in DBSession.query(Clinic).filter(and_(Clinic.active == 0, Clinic.area_id == locationIndex)):
        latitude = longtitude = None
        if c.coordinate:
            latitude, longtitude = c.coordinate.split(",")
        for d in c.doctors:
            ds.append(
                {
                    "doctorID": d.id,
                    "clinicID": c.id,
                    "name": {"zh_HK": c.name_tc, "zh_CN": c.name_sc}.get(lang, c.name),
                    "latitude": latitude,
                    "longtitude": longtitude,
                    "address": {"zh_HK": c.address_tc, "zh_CN": c.address_sc}.get(lang, c.address),
                }
            )

    return jsonify({"result": 1, "data": ds})
Exemple #11
0
    def ajax_save(self):
        id = _g("id")
        type = _g('form_type')
        if type not in ['sendout', 'transit', 'exception', 'arrived']:
            return jsonify({'code' :-1, 'msg' : unicode(MSG_NO_SUCH_ACTION)})

        header = DeliverHeader.get(id)
        if type == 'sendout':
            header.status = SEND_OUT[0]
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('send_out_time'),
                                      type = 1,
                                      remark = _g('send_out_remark')
                                      ))
            header.sendout_time = _g('send_out_time')

            DBSession.add(SystemLog(
                                    type = header.__class__.__name__,
                                    ref_id = header.id,
                                    remark = u'%s 确认该记录状态为已发货。' % session['user_profile']['name']
                                    ))


            DBSession.commit()
            self._sms(header, u'已发货。')
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})

        if type == 'transit':
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('transit_time'),
                                      type = 1,
                                      remark = _g('transit_remark')
                                      ))
            DBSession.commit()
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})


        if type == 'arrived' :
            header.status = GOODS_ARRIVED[0]
            DBSession.add(TransferLog(
                                      refer_id = header.id,
                                      transfer_date = _g('arrived_time'),
                                      type = 1,
                                      remark = _g('arrived_remark')
                                      ))
            DBSession.add(SystemLog(
                                    type = header.__class__.__name__,
                                    ref_id = header.id,
                                    remark = u'%s 确认记录状态为货物已到达目的站。' % session['user_profile']['name']
                                    ))

            for d in header.details:
                order_header = d.order_header
                order_header.actual_time = _g('arrived_time')
            DBSession.commit()
            self._sms(header, u'已到达。')
            return jsonify({'code' : 0 , 'msg' : unicode(MSG_SAVE_SUCC)})
Exemple #12
0
def item_detail(item_id):

    item_dic = dao.get_item_detail(item_id)
    
    if item_dic:
        return jsonify(item_dic)
    
    return jsonify({})
Exemple #13
0
    def ajax_change_flag(self):
        try:
            ids = _g('order_ids', '').split("|")
            flag = _g('flag')
            type = _g('type')
            for r in DBSession.query(OrderHeader).filter(OrderHeader.id.in_(ids)).order_by(OrderHeader.create_time):
                if type == 'APPROVE':
                    r.approve = flag
                    if flag == '1':  # approve
                        remark = u'%s 审核通过该订单。' % session['user_profile']['name']
                    else:  # disapprove
                        remark = u'%s 审核不通过该订单。' % session['user_profile']['name']
                elif type == 'PAID':
                    r.paid = flag
                    if flag == '1':
                        remark = u'%s 确认该订单为客户已付款。' % session['user_profile']['name']
                    else:
                        remark = u'%s 确认该订单为客户未付款。' % session['user_profile']['name']
                elif type == 'SUPLLIER_PAID':
                    r.supplier_paid = flag
                    if flag == '1':
                        remark = u'%s 确认该订单为已付款予承运商。' % session['user_profile']['name']
                    else:
                        remark = u'%s 确认该订单为未付款予承运商。' % session['user_profile']['name']
                elif type == 'ORDER_RETURN':
                    r.is_return_note = flag
                    if flag == '1':
                        remark = u'%s 确认该订单为客户已返回单。' % session['user_profile']['name']
                    else:
                        remark = u'%s 确认该订单为客户未返回单。' % session['user_profile']['name']
                elif type == 'EXCEPTION':
                    r.is_exception = flag
                    if flag == '1':
                        remark = u'%s 标记该订单为异常。' % session['user_profile']['name']
                    else:
                        remark = u'%s 取消该订单的异常标记。' % session['user_profile']['name']
                elif type == 'LESS_QTY':
                    r.is_less_qty = flag
                    if flag == '1':
                        remark = u'%s 标记该订单为少货。' % session['user_profile']['name']
                    else:
                        remark = u'%s 取消该订单的少货标记。' % session['user_profile']['name']


            DBSession.add(SystemLog(
                                    type = r.__class__.__name__,
                                    ref_id = r.id,
                                    remark = remark
                                    ))
            DBSession.commit()
            return jsonify({'code' : 0 , 'msg' : MSG_UPDATE_SUCC})
        except:
            _error(traceback.print_exc())
            DBSession.rollback()
            return jsonify({'code' : 1, 'msg' : MSG_SERVER_ERROR})
Exemple #14
0
def get_ad():
    """
    Retrieves all the information about an ad.
    """
    from db import Ad

    ad = Ad.query.get(request.form.get("id"))
    if ad:
        return jsonify({"res": ad.serialize})
    else:
        return jsonify({"res": False, "error": "We are unable to find any classifieds near you!"})
Exemple #15
0
    def upload(self):
        f = upload('upfile')
        if not f : return jsonify({
                                   'url' : '', 'title' : '', 'state' : 'ERROR',
                                   })

        return jsonify({
                        'url' : f.url ,
                        'title' : f.name,
                        'state' : 'SUCCESS',
                        })
Exemple #16
0
def get_checkpoint():
    """
    (GET: checkpoint)
    """
    type = request.args.get("type")
    user_id = request.args.get("user_id")
    signature = request.args.get("signature")
    
    if not authorize("get", "checkpoint", user_id, signature):
        return authorization_fail()
    
    if type == "search":
        user_checkpoints = _search_checkpoints()
        return jsonify({"checkpoints": user_checkpoint_sanify(user_checkpoints),
                        "status": "ok", 
                        })
    
    elif type == "near":
        friends_ucp, anon_ucp, notifications = _checkpoints_near_me()
        recent_checkpoints = get_recent_friend_user_checkpoints(get_user(user_id))
        lon = request.args.get("longitude")
        lat = request.args.get("latitude")
        
        dic = {"recent_checkpoints": [ucp.serialize for ucp in recent_checkpoints],
               "friends_checkpoints": user_checkpoint_sanify(friends_ucp),
               "anon_checkpoints": user_checkpoint_sanify(anon_ucp),
               "notifications": notification_sanify(notifications),
               "friends_proximity": checkpoint_proximity(friends_ucp, lat, lon),
               "anon_proximity": checkpoint_proximity(anon_ucp, lat, lon),
               "status": "ok", 
               }
        
        return jsonify(dic)
        
    elif type == "mine":
        user_checkpoints = _my_checkpoints()
        dic = {"checkpoints": user_checkpoint_sanify(user_checkpoints),
               "status": "ok"}
        _build_proximity(user_checkpoints, dic)
        return jsonify(dic)
        
    else:
        #single checkpoint info
        res = _checkpoint_details()
        return jsonify({
                        "total_likes": res.total_likes,
                        "total_shares": res.total_shares,
                        "current_user_like": res.current_user_like,
                        "comments": comment_sanify(res.comments),
                        "user": res.user,
                        "checkpoint": res.user_checkpoint_obj.serialize,
                        "status": "ok",
                        })
Exemple #17
0
def status_comment_delete():
    id = request.args.get('id')
    c = Comment.query.filter_by(id=id).first()
    if c is not None:
        if c.user == current_user:
            c.active = False
            db.session.add(c)
            db.session.commit()
            response = jsonify(status="SUCCESS")
            return response
        else:
            return jsonify(status="NOTAUTHORIZED")
    else:
        return jsonify(status="FAIL")
Exemple #18
0
    def ajax_get_discount(self):
        id = _g('id')
        if not id:
            return jsonify({'code' : 1 , 'msg' : MSG_NO_ID_SUPPLIED})
        header = DBSession.query(OrderHeader).get(id)
        if not header:
            return jsonify({'code' : 1 , 'msg' : MSG_RECORD_NOT_EXIST})

        return jsonify({'code' : 0 , 'data' : {
                                             'ref_no' : header.ref_no,
                                             'actual_proxy_charge' : header.actual_proxy_charge,
                                             'discount_return_time' : header.discount_return_time,
                                             'discount_return_person_id' : header.discount_return_person_id,
                                             'discount_return_remark' : header.discount_return_remark,
                                             }})
Exemple #19
0
def category(parent_id=ROOT_CAT_ID):
    ''' This will render the main page with the selected category defined by parent_id, and with the
    content that it contains  '''
    contents = get_images_for_category(parent_id)
    if request.is_xhr:
        categories = [c.jsond() for c in CategoryModel.all().filter('parent_id', parent_id).filter('visible', True)]
        categories = sorted(categories, key=lambda c: c.order)
        return jsonify(categories=categories, contents=contents)
    else:
        category = CategoryModel.get_by_id(parent_id)
        path = None
        if category:
            path = category.get_path_ids_to_root() + [category.key().id()]
        categories = []
        for cat in CategoryModel.all().filter('parent_id', ROOT_CAT_ID).filter('visible', True):
            if path is not None and cat.key().id() in path:
                init_sub_tree_along_path(cat, path)
            categories += [cat]
            pass
        pass
        categories = sorted(categories, key=lambda c: c.order)
        contents = sorted(contents, key=lambda c: c['order'])
        return render_template('category/index.html', categories=categories, contents=contents,
                               current_category=category)
    pass
Exemple #20
0
def new_like():
    """
    (PUT: like)
    Instantiates a new <<CheckpointLike>> from a user on a <<UserCheckpoint>>
    """
    
    #req var
    user_id = request.form.get("user_id")
    signature = request.form.get("signature")
    user_checkpoint_id = request.form.get("user_checkpoint_id")
    
    #generated var
    verb = "put"
    noun = "like"
    user = get_user(user_id)
    user_checkpoint = get_user_checkpoint(user_checkpoint_id)
    access_token = user.access_token
    
    #authorization check
    if not is_api_key_validated(access_token, user_id, signature, verb, noun):
        return authorization_fail()
    
    like = add_like(user, user_checkpoint)
    
    return jsonify({
                    "status": "ok",
                    "result": {
                               "like_id": like.id, 
                               }
                    })
Exemple #21
0
    def get_logs():
        if 'tags' in request.args:
            tags = json.loads(request.args['tags'])
        else:
            tags = []

        if 'params' in request.args:
            params = json.loads(request.args['params'])
        else:
            params = {}

        query = logger.db_session.query(logger.Log)

        for tag_name in tags:
            query = query.filter(logger.Log.tags.any(logger.Tag.name == tag_name))

        for param, value in params.items():
            query = query.join(logger.Log.values).filter(logger.Value.name == value).distinct().join(logger.Value.param).filter(logger.Param.name == param).distinct()

        count = query.count()

        query = query.order_by(logger.Log.time.desc())

        if 'offset' in request.args:
            query = query.offset(int(request.args['offset']))
        if 'limit' in request.args:
            query = query.limit(int(request.args['limit']))

        logs = query.all()
        return jsonify(logs=logs_for_response(logs), count=count)
Exemple #22
0
def add_checkpoint_to_catalog():
    """
    (POST: user_checkpoint)
    user likes a Checkpoint from a user and wants to add it into his catalog;
    adds checkpoint to user's catalog
    """
    
    #req vars
    user_id = request.form.get("user_id")
    signature = request.form.get("signature")
    to_add_user_checkpoint_id = request.form.get("user_checkpoint_id")
    
    #generated var
    verb = "post"
    noun = "catalog"
    user = get_user(user_id)
    
    if not authorize(verb, noun, user_id, signature):
        return authorization_fail()
    
    user_checkpoint = get_user_checkpoint(to_add_user_checkpoint_id)
    new_user_cp = add_existing_checkpoint_to_user(user, user_checkpoint)
    
    return jsonify({
                    "status": "ok",
                    "result": {
                               "user_checkpoint_id": new_user_cp.id,
                               },
                    }) 
Exemple #23
0
def delete_like():
    """
    (DELETE: like)
    Deletes an existing <<CheckpointLike>> between a user and a <<UserCheckpoint>>
    if it exists
    """
    #req var
    
    user_id = request.args.get("user_id")
    signature = request.args.get("signature")
    user_checkpoint_id = request.args.get("user_checkpoint_id")
    
    
    #generated var
    verb = "delete"
    noun = "like"
    user = get_user(user_id)
    user_checkpoint = get_user_checkpoint(user_checkpoint_id)
    access_token = user.access_token
    
    #authorization check
    if not is_api_key_validated(access_token, user_id, signature, verb, noun):
        return authorization_fail()

    delete_like_action(user, user_checkpoint)
    
    return jsonify({
                    "status": "ok",
                    })
Exemple #24
0
def user_login():
    """
    (PUT: user)
    Method to handle when a user authenticates (from Facebook), be it a new user, or recurring user
    """

    fb_code = request.form.get("fb_code", None)
    access_token = request.form.get("access_token", None)
    
    if access_token is None:
        access_token = get_user_access_token(fb_code, APP_ID, APP_SECRET)
    
    fb_user_info, user = save_user(access_token, fb_code)
    api_key = gen_api_key(access_token, user.id)
    
    friends = get_friends(user, exclude_self=True)

    return jsonify({"status": "ok",
                    "result": {
                        "user": {
                                 "id": user.id,
                                 "name": user.facebook_user.name, 
                                 },
                        "friends": sanify_friends(friends),
                        "facebook_user_id": fb_user_info["id"],
                        "facebook_portrait_url": "https://graph.facebook.com/%s/picture" % user.facebook_user.id,
                        "api_key": api_key,
                    }
                    })
def essay_post_new():
    """
    Route for the processing of an essay submitted by POST request
    @param text:    the text to process
    @return:
        - a JSON object containing the learning analytics of the essay, an error message if problems
        - the status code of the transaction (200 or 500)
    """

    text0 = request.form['text']
    essay = {}
    status = 200

    if (app.debug is True):
        essay = Flask_process_text(text0)
    else:
        try:
            essay = Flask_process_text(text0)
        except Exception as e:
            ## Any unsupported exceptions coming from code
            ## TODO: get a better error message (not revealing internal error)
            status = 500
            essay = {'error': {'status': status, 'msg': e.message}}

    return jsonify(essay), status
def essay_post_new():
    """
    Route for the processing of an essay submitted by POST request
    @param text:    the text to process
    @return:
        - a JSON object containing the learning analytics of the essay, an error message if problems
        - the status code of the transaction (200 or 500)
    """
    
    try:
        text0 = request.form['text']
        module = request.form['module']
        task = request.form['task']
        essay = {}
        status = 200
    
        #if (app.debug is  True):
        #    essay = Flask_process_text(text0,module,task) 
        #else:
        essay = Flask_process_text(text0,module,task) 
    except Exception as e:
        ## Any unsupported exceptions coming from code
        ## TODO: get a better error message (not revealing internal error)
        print repr(e)
        status = 500
        essay = { 'error' : {  
            'status' : status,
            'msg'    :repr(e)}}
    
    return jsonify(essay) , status  
Exemple #27
0
def powerOff(channel):
    '''
    Power off relay
    @param channel: canale 
    '''
    relayBoard = appModules[MODULE_RELAY_BOARD]
    return jsonify(result = relayBoard.powerOff(channel));
Exemple #28
0
def category(parent_id=ROOT_CAT_ID):
    ''' This will render the main page with the selected category defined by parent_id, and with the
    content that it contains  '''
    contents = get_images_for_category(parent_id)
    if request.is_xhr:
        categories = [
            c.jsond() for c in CategoryModel.all().filter(
                'parent_id', parent_id).filter('visible', True)
        ]
        categories = sorted(categories, key=lambda c: c.order)
        return jsonify(categories=categories, contents=contents)
    else:
        category = CategoryModel.get_by_id(parent_id)
        path = None
        if category:
            path = category.get_path_ids_to_root() + [category.key().id()]
        categories = []
        for cat in CategoryModel.all().filter('parent_id', ROOT_CAT_ID).filter(
                'visible', True):
            if path is not None and cat.key().id() in path:
                init_sub_tree_along_path(cat, path)
            categories += [cat]
            pass
        pass
        categories = sorted(categories, key=lambda c: c.order)
        contents = sorted(contents, key=lambda c: c['order'])
        return render_template('category/index.html',
                               categories=categories,
                               contents=contents,
                               current_category=category)
    pass
Exemple #29
0
def status(channel):
    '''
    Get relay status
    @param channel: canale 
    '''
    relayBoard = appModules[MODULE_RELAY_BOARD]
    return jsonify(result = relayBoard.status(channel));
Exemple #30
0
    def get_fighters(page):
        if page < 1: page = 0

        return jsonify(
            fighters=g.fighterRepository.find(skip=(page - 1) * 100,
                                              limit=100,
                                              sort=[('name',
                                                     pymongo.ASCENDING)]))
Exemple #31
0
def update():
    success = False
    title = request.form['title']
    shorturl = request.form['shorturl']
    if shorturl and title :
        update_filename(title,shorturl)
        success = True
    return jsonify(success=success)
Exemple #32
0
def upload():
    """
    Upload file to Dropbox.
 
    If user not logged in - redirects to "Home" page.
    """
    if not dp.is_authenticated:
        return redirect(url_for('home'))

    if request.method == 'POST':
        url = request.form['urlInput']
        print url
        if url:            
            uploadTask.apply_async((session['dropbox_access_token'], url))
            return jsonify(message="Upload has been started. Check back in few minutes.")

    return jsonify(message="Something wrong with url or upload")
Exemple #33
0
    def ajax_check_before_save(self):
        try:
            note_id = _g('note_id')
            note_no = _g('note_no')
            note = DBSession.query(Note).get(note_id)
            note_no = int(note_no)
            if not (int(note.begin_no) <= int(note_no) <= int(note.end_no)):
                return jsonify({'code' : 0 , 'result' : 1, 'msg' : u'该票据不在可用范围内(%s~%s),请修改!' % (note.begin_no, note.end_no)})

            ref_no = _g('ref_no')
            if DBSession.query(OrderHeader).filter(and_(OrderHeader.active == 0, OrderHeader.ref_no == ref_no)).count() > 0:
                return jsonify({'code' : 0 , 'result' : 1, 'msg' : u'已经存在重复的订单号码!'})

            return jsonify({'code' : 0 , 'result' : 0})
        except:
            _error(traceback.print_exc())
            return jsonify({'code' : 1 , 'msg' : MSG_SERVER_ERROR})
Exemple #34
0
def register():
    fields = ["email", "password", "repassword"]
    if _check_params(fields) != 0:
        return jsonify({"result": 0, "msg": MSG_PARAMS_MISSING})

    email = _g("email")
    password = _g("password")
    repassword = _g("repassword")

    if not email:
        return jsonify({"result": 0, "msg": MSG_EMAIL_BLANK_ERROR})
    if not password:
        return jsonify({"result": 0, "msg": MSG_PASSWORD_BLANK_ERROR})
    if password != repassword:
        return jsonify({"result": 0, "msg": MSG_PASSWORD_NOT_MATCH})

    try:
        DBSession.query(User).filter(and_(User.active == 0, func.upper(User.email) == email.upper())).one()
        return jsonify({"result": 0, "msg": MSG_EMAIL_EXIST})
    except:
        traceback.print_exc()
        pass
    display_name = _g("display_name") or email
    try:
        u = User(email=email, password=password, display_name=display_name)
        DBSession.add(u)
        DBSession.commit()
        return jsonify({"result": 1, "msg": MSG_SAVE_SUCCESS, "id": u.id, "point": u.point})
    except:
        traceback.print_exc()
        return jsonify({"result": 0, "msg": MSG_SERVER_ERROR})
Exemple #35
0
def edit():
    user_id = request.form.get('id')
    address = request.form.get('address')
    tel = request.form.get('tel')
    user = User.objects.get(id=user_id)
    user.address = address
    user.tel = tel
    user.save()
    return jsonify({'ok': True})
Exemple #36
0
def delete_entry():
    success = False
    filename = request.args.get('fname', '', type=str)
    file = File.query.filter(File.filename == filename).first()
    if file is not None:
        file.remove()
        success = True
        os.remove(file.fileabslink)  # delete file from OS.^_^
    return jsonify(result=success)
Exemple #37
0
    def post_fighter():
        initiative = None
        try:
            initiative = get_initiative()
        except (ValueError):
            return jsonify(success=False)

        fighter = Fighter(name=request.form["name"], initiative=initiative)

        return save_fighter(fighter)
Exemple #38
0
def save_events():
    uid = request.values.get("uid", None)
    did = request.values.get("did", None)
    d = request.values.get("d", None)
    t = request.values.get("t", None)

    if not uid or not did or not d or not t:
        return jsonify({
                        "success" : False,
                        "message" : "The required info is not supplied !"
                        })
    format_date = lambda v : "-".join([v[:4], v[4:6], v[-2:]])

    try:
        e = connection.Events()
        e.id = e.getID()
        e.uid = int(uid)
        e.did = int(did)
        e.date = d
        e.time = t
        e.remark = request.values.get("remark", None)
        e.save()

        doctor = connection.DoctorProfile.one({'id':int(did)}).populate()
        m = connection.Message()
        m.id = m.getID()
        m.subject = u'Booking request submit'
        m.uid = session['user_profile']['id']
        m.content = u'%s make a booking with doctor %s at %s , %s.' % (session['user_profile']['name'], doctor['name'], t, format_date(d))
        m.save()

        return jsonify({
                        "success" : True,
                        "message" : "Save your request successfully !",
                        "event_time" : e.time,
                        })
    except:
        app.logger.error(traceback.format_exc())
        return jsonify({
                        "success" : False,
                        "message" : "Error occur when submiting the request !"
                        })
Exemple #39
0
def get_date_info():
    pdate = request.values.get("pdate", None)
    pdoctor = request.values.get("pdoctor", None)
    if not pdate or not pdoctor:
        return jsonify({"success" : False, "message" : "No date or doctor supplied!"})

    doctor = connection.DoctorProfile.one({"id" : int(pdoctor)})
    require_date = dt.strptime(pdate, "%Y%m%d")

    day = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"][require_date.weekday()]
    time_spans = {}
    for setting in doctor.worktime_setting[day]:
        begin, end = setting['times']

        app.logger.info(setting)
        bHour, bEnd = begin.split(":")
        eHour, eEnd = end.split(":")

        if bHour == eHour:
            time_spans[bHour] = [begin, end, setting['seats'], 0]
        else:
            h1 = int(bHour)
            h2 = int(eHour)
            for h in range(h1 + 1, h2):
                time_spans[h] = [("0%d:00" % h)[-5:], ("0%d:00" % (h + 1))[-5:], 0, 0]
            if eEnd != "00":
                time_spans[h2] = [("0%d:00" % h2)[-5:], end, 0, 0]
            time_spans[h1] = [begin, ("0%d:00" % (h1 + 1))[-5:], 0, 0]

            spans = sorted(time_spans.keys())
            for i in range(setting['seats']) : time_spans[spans[i % len(spans)]][2] += 1


    for e in connection.Events.find({"active":0, "did" : int(pdoctor), "date" : pdate}):
        h, m = e.time.split(":")
        if int(h) in time_spans:
            time_spans[int(h)][3] += 1

    return jsonify({
                    "success" : True,
                    "time_spans" : time_spans
                    })
Exemple #40
0
def search(rid):
    try:
        username = request.form.get('username', '')
        password = request.form.get('password', '')
        print 'request %s with {user:%s,remote_addr:%s}' % (
            request.path, username, request.remote_addr)
        time = request.form.get('time', '')
        verify_snda(username, password, time)
        post_data = {'username': username, 'password': '******'}
        params = urllib.urlencode(post_data)
        response = urllib.urlopen(REFRESH_ROOT + '/' + rid + '?%s' % params)
        return response.read()
    except InputError, e:
        return jsonify({"success": False, "message": e.__str__()}), 403
Exemple #41
0
def progress(as_list=False):
    """
    Gets messages from the queue and exports them to JSON.
    """
    result = {'items': []}
    try:
        while True:
            item = bufferqueue.get_nowait()
            result['items'].append(item)
            bufferqueue.task_done()
    except Empty:
        pass

    if as_list:
        return result['items']

    return jsonify(result)
Exemple #42
0
def m_user_update():
    id = _g("id")
    redirect_url = url_for("m_user_list")
    if not id:
        flash("No id supplied !", MESSAGE_ERROR)
        return redirect(redirect_url)
    action_type = _g("action_type")
    if not action_type in ["v", "c"]:
        flash("No such action !", MESSAGE_ERROR)
        return redirect(redirect_url)
    u = connection.User.one({"id": int(id)})

    if action_type == "v":
        return render_template("m_user_view.html", user=u)
    elif action_type == "c":  #cancel
        u.active = 1
        e.save()
        return jsonify({"success": True, "message": "Update successfully !"})
Exemple #43
0
def receiver_snda_proload():
    try:
        username = request.form.get('username', '')
        password = request.form.get('password', '')
        time = request.form.get('time', '')
        print 'request %s with {user:%s,remote_addr:%s}' % (
            request.path, username, request.remote_addr)
        verify_snda(username, password, time)
        task = load_task(request.form.get("task", "{}"))
        post_data = {
            'username': username,
            'password': '******',
            'task': task
        }
        params = urllib.urlencode(post_data)
        response = urllib.urlopen(REFRESH_ROOT, params)
        return response.read()
    except InputError, e:
        return jsonify({"success": False, "message": e.__str__()}), 403
Exemple #44
0
def search():
    q = request.values.get('q', None)
    r = connection.Role.one({"name": "DOCTOR"})
    contain = {"$regex": "/.*%s.*/i" % q}
    contain = "/.*%s.*/i" % q
    #search the user
    us = connection.User.find({
        'active':
        0,
        'roles': {
            '$all': [r.id]
        },
        '$or': [
            {
                'first_name': contain
            },
            #                                      {'last_name' : contain},
        ]
    })
    data = [u.populate() for u in us]
    app.logger.info(data)
    return jsonify(data)
def hello_world():
    """
    Route for the documentation of the API
    
    @return: a JSON object containing the APIs of the services
    """

    apis = []
    apis.append({
        'method': 'POST',
        'url': '/api/analysis',
        'params': [{
            'attribute': 'text',
            'value': 'string'
        }]
    })

    info = {}
    info['name'] = 'pyEssayAnalyser'
    info['version'] = "3.0"
    info['api'] = apis

    return jsonify(info)
Exemple #46
0
 def get_fighter(fighter_id):
     return jsonify(fighter=g.fighterRepository.find_one(_id=fighter_id))
Exemple #47
0
 def save_fighter(fighter):
     g.fighterRepository.save(fighter)
     return jsonify(success=False)
Exemple #48
0
def check_email():
    u = connection.User.one({"active": 0, "email": _g("email")})
    return jsonify({"is_exist": bool(u)})
Exemple #49
0
def serve_cluster(type):
    global cluster_data
    with dict_and_scores_lock:
        return jsonify(**cluster_data[type])