Exemplo n.º 1
0
def forward_url():
    message = {}
    message['statusCode'] = '201'
    message['status'] = "跳转获取信息失败"
    error_message = jsonify(message)

    if request.method == "GET" and session.get("username"):
        headers_info = {'Cookie': 'sessionid=' + session.get('sessionid')}
        req_url = request.args.get("url")

        if req_url:

            try:
                set_networks = requests.get(base_url + req_url,
                                            headers=headers_info,
                                            timeout=10,
                                            verify=False)
                response_content = set_networks.content.decode()
                message['statusCode'] = '200'
                response_parse = etree.HTML(response_content)
                response_content = ''.join(
                    response_parse.xpath("/html//h2//text()"))

                message['status'] = response_content

            except Exception as e:
                logging.error(e)
                return error_message

            return jsonify(message)

    return error_message
Exemplo n.º 2
0
def get_js_api_ticket(Config):

    access_token = get_access_token(Config)
    url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi" % access_token
    try:
        response = json.loads(requests.get(url, timeout=4).content.decode())
        return response['ticket']
    except Exception as e:
        logging.error("获取临时ticket失败!")
        return None
Exemplo n.º 3
0
def get_access_token(Config):

    try:
        req_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (
            Config.app_id, Config.app_secret)
        token_response = requests.get(req_url, timeout=4).content.decode()
        token_dict = json.loads(token_response)
        return token_dict['access_token']
    except Exception as e:
        logging.error(e)
        logging.error("获取access_token失败!")
Exemplo n.º 4
0
def get_access_token_to_estimate(openid):
    # 尝试利用函数,绕过验证码登陆
    try:
        token = try_get_estimate_token(session.get('openid'))

    except Exception as e:
        logging.error(e)

        return False

    return token
Exemplo n.º 5
0
def create_menu(accessToken, menu_info):
    post_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % accessToken

    #删除菜单用下面这条
    # post_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s" %accessToken

    # post_data = json.dumps(menu_info)
    try:
        res = requests.post(post_url, menu_info.encode(),
                            timeout=5).content.decode()

        #删除菜单用这条
        # res = requests.get(post_url).content.decode()
        print(res)
    except Exception as e:
        logging.error(e)
        logging.error("创建菜单失败")
        print(e)
Exemplo n.º 6
0
def code2openid(code):
    get_openid_url = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code" % (
        Config.app_id, Config.app_secret, code)
    openid = ''
    try:
        res = requests.get(url=get_openid_url, timeout=4)
        response = res.content.decode()
        if res.status_code == 200:
            content = res.content.decode()

            # 将内容转换成为字典
            info = json.loads(content)
            openid = info['openid']
            return openid

        else:
            logging.error(response)
            return False

    except Exception:
        logging.error(response)
        return False
Exemplo n.º 7
0
def index():
    db.session.close()
    if request.method == "POST":

        content_xml = request.data

        # timestamp = time.mktime(datetime.datetime.now().timetuple())
        timestamp = time.time()
        ##捕捉一些野生openid

        return_content = decode_msg(content_xml)
        req_con = return_content['Content']

        weixin_openid = return_content['ToUserName']

        if re.findall("(评分系统|评分|评价|系统)", req_con):

            #获取通讯码
            # code = weixin_checkin_token()
            openid = return_content['ToUserName']

            token = token_create({'open_id': openid}, 21600)

            return_content[
                'Content'] = "免账号密码登录\n可以点击这里登陆\n6个小时候需重新获取\n\n<a href=\"https://weixin.520langma.com/estimate/login/weixin_checkin/?code=%s\">点我点我</a>" % token

        elif re.findall("课室\d+(断|开网)", req_con):
            number = re.findall("课室\d+(?=断|开网)", req_con)

            operate_online = re.findall("开网", req_con)

            if not operate_online:
                operate = "deny"
            else:
                operate = "permit"

            #晕,还是需要去数据库获取课室的地址,不过,巧妙一点。用get的方式。
            try:
                exist_class = ClassRoom.query.filter(
                    ClassRoom.class_number == number[0],
                    ClassRoom.block_number.in_((2, 3, 4, 5))).first()
                # exist_class = ClassRoom.query.filter(ClassRoom.class_number==number).first()

                if not exist_class:
                    return_content['Content'] = "稳唔到课室(找不到课室)"

            except Exception as e:

                return_content['Content'] = "数据库连接出现异常!"
                db.session.rollback()

            else:
                try:
                    #获取具体课室的id
                    class_id = exist_class.id
                    #然后调动url了
                    set_network_url = "http://192.168.113.1/estimate/index/set_network/?cls=%s&operate=%s&acl=520su1314" % (
                        class_id, operate)

                    #然后尝试去请求了
                    res = redirect_after_weixin_checkin(
                        weixin_openid, set_network_url)
                    if res['success']:

                        content = re.findall("(?<=<h2>).+?,",
                                             res['msg'].content.decode())

                        return_content['Content'] = content[0]

                    else:
                        return_content['Content'] = res['msg']

                except Exception as e:
                    return_content['Content'] = "唔好意思(不好意思),设置失败:错误02"

            #然后就可以调用开网断网的url地址了,这里应该是调用函数了。
            #关键就是,拿到最新的cookie里面的sessionid数值就可以了
            #然后有各式各样的调用,就设置一个公共方法去登陆吧。
            #请求的url地址+weixin_openid就已经足够了,然后就是

        elif re.findall("邮箱|绑定", req_con):

            return_content[
                'Content'] = "邮箱绑定,请你按一定要求输入你的邮箱地址\n输入的格式带有前缀 'email#'然后加上'*****@*****.**',两部分信息\n,示例:\n\nemail#[email protected]\n\n或者是:\n\nemail#[email protected]\n\n发送过程稍慢,请不要重复提交命令"

        elif re.findall("验证|认证", req_con):

            from datetime import datetime as dates
            import random

            now = dates.now().strftime("%m-%d %H:%M")
            verify_code = "".join(
                [str(random.randint(0, 9)) for x in range(4)])
            verify_code_detail = now + " " + verify_code

            is_exist1 = User.query.filter(
                User.weixin_openid == weixin_openid).first()
            is_exist2 = User.query.filter(
                User.username == weixin_openid).first()

            if is_exist1 or is_exist2:
                return_content['Content'] = "出錯!你認證過嘅數據存在系數據庫當中,唔使重複申請認證!"
            else:
                # return_content['Content'] = "出錯!數據庫异常!!"

                #要么成功插入待认证数据,要么就是已经存在认证数据,又或者数据库异常
                try:
                    admin = User(username=weixin_openid,
                                 weixin_openid_tmp=weixin_openid,
                                 password="******",
                                 department=20,
                                 email="*****@*****.**",
                                 quick_verify=verify_code_detail,
                                 realname="wolfcode_employee")
                    # admin = User()
                    # admin.username = weixin_openid
                    # admin.password = "******"
                    # admin.department = 20
                    # admin.email = "*****@*****.**"
                    # admin.quick_verify = verify_code_detail
                    # admin.realname = "wolfcode_employee"

                    db.session.add(admin)
                    db.session.commit()

                except Exception as e:
                    logging.error(e)
                    logging.error(admin.__dict__)
                    db.session.rollback()
                    return_content['Content'] = "出錯!數據庫异常!!"

                else:

                    return_content[
                        'Content'] = "申請認證成功,呢個系你嘅隨機驗證:%s,請keep好" % verify_code

        #复用验证流程,添加多一个关键字
        elif re.findall("list", req_con):

            #先检查权限
            check_auth = User.query.filter(
                User.weixin_openid == weixin_openid).first()

            if check_auth and (check_auth.id == 5):

                #查询所有待验证的微信id
                wait_for_verify = User.query.filter(
                    or_(User.weixin_openid_tmp != None,
                        User.xcx_openid_tmp != None)).all()

                if wait_for_verify:

                    content = ''
                    for x in wait_for_verify:

                        if x.weixin_openid_tmp:
                            types = "公众号认证"
                        else:
                            types = "小程序认证"

                        content += "%s id:%s verify_code:%s\n" % (
                            types, x.id, x.quick_verify)

                    return_content['Content'] = content
                    return_content[
                        'Content'] += "\n\n提示:输入confirm#[需要通过的id]#[汉语名字],如果是是认证小程序,请添加#x"

                else:

                    return_content['Content'] = "没有需要等待认证"

            else:
                return_content['Content'] = "你没有权限!"

        elif re.findall("^confirm#(\d+)#(.+)", req_con):
            info = re.findall("^confirm#(\d+)#(.+)", req_con)

            ##复用验证功能.添加认证小程序,或者,
            ##可以给已经认证公众号的同事,添加快速添加小程序认证功能,这个再说吧.现在不急.

            set_xcx_verify = re.findall("^confirm#\d+#(.+)#x", req_con)

            if info:
                id = int(info[0][0])
                realname = set_xcx_verify[0]

                #尝试修改认证数据

                #ok,想将公众号刚提交的用户,关联到那些,可能已经登陆的用户信息
                #所以,现在用户名就是关键了.realname就是关键了.
                #所以需要修改规则了

                try:
                    verify = User.query.get(id)
                    if set_xcx_verify:
                        verify.xcx_openid = verify.xcx_openid_tmp
                        verify.xcx_openid_tmp = None
                    else:
                        verify.weixin_openid = verify.weixin_openid_tmp
                        verify.weixin_openid_tmp = None

                    verify.realname = realname

                    db.session.add(verify)
                    db.session.commit()
                    # verify.realname = realname

                    #查询以realname为条件,是否存在数据
                    is_exist = User.query.filter(
                        User.realname == realname).first()

                    if is_exist and (is_exist.id != verify.id):

                        if set_xcx_verify:
                            is_exist.xcx_openid = verify.xcx_openid
                            is_exist.xcx_openid_tmp = None
                        else:
                            is_exist.weixin_openid = verify.weixin_openid
                            is_exist.weixin_openid_tmp = None

                        db.session.add(is_exist)
                        db.session.delete(verify)
                        db.session.commit()

                except Exception as e:
                    logging.error(e)
                    db.session.rollback()
                    return_content['Content'] = "通过失败!"
                else:
                    return_content['Content'] = "通过!"

            else:

                return_content['Content'] = "通过失败!"

        elif re.findall("(?<=email#)([a-z]+[0-9]*@(wolfcode\.cn|520it\.com))",
                        req_con):
            x1 = re.findall(
                "(?<=email#)([a-z]+[0-9]*@(wolfcode\.cn|520it\.com))", req_con)

            #邮箱正确,然后就马上发送邮件,根据两端相同的密钥

            if send_verify_code(return_content['ToUserName'], x1[0][0]):

                return_content[
                    'Content'] = "已经成功发送咗(了)激活码到你的邮箱,请点击邮箱里面的激活码进行实名绑定!"
            else:
                return_content['Content'] = "发送唔成功(不成功)"

        elif re.findall("(控制|教室|课室|网络|断网|开网|关闭|打开)", req_con):

            return_content[
                'Content'] = "关于如何用语句控制网络的提示↓↓↓↓\n\n开启课室网络,请回复的指定内容,回复内容的格式是(例子):\n课室1开网\n\n关闭课室网络,回复内容的格式:\n课室15断网"
            return_content[
                'Content'] += "\n\n\n备注:目前仅支持广州远程操作,上海和北京暂时只能使用电脑网页端的<评价系统>里面的<网络管理>来控制网络"

        elif re.findall("([wW][iI][fF][iI]|无线|密码)", req_con):

            user_info = is_user_binding(weixin_openid)

            #可以先尝试组织wifi密码的表达方式

            wifi_info_str = ""

            for name, pwd in Config.WIFI_PWD.items():

                wifi_info_str += "wifi名字:%s\n密码:%s \n\n" % (name, pwd)

            if user_info:
                return_content['Content'] = wifi_info_str
            else:
                return_content['Content'] = "你尚未进行实名公司邮箱认证"

        else:

            return_content[
                'Content'] = "操作无效,目前支持的关键字是:教室|课室|网络|断网|开网|关闭|打开|评分系统|wifi"

        x1 = xmltodict.unparse({'xml': return_content})
        db.session.close()
        return x1

    else:

        #这里添加一个get请求,这里get请求就捆绑一个数据库请求,大概就是这样子
        if request.args.get("beetle"):
            if request.args.get("beetle") == "diaonimienijiangmiea":
                user_info = User.query.filter().first()

        db.session.close()
        return render_template('index.html')
Exemplo n.º 8
0
def verify_code():
    message = {}
    message['statusCode'] = '201'
    message['status'] = "验证码阶段出错"
    error_message = jsonify(message)

    # 首先获取合法的openid

    # 尝试获取openid,如果失败,就报错
    try:
        openid_get = request.args.get("code")
        openid = code2openid(openid_get)
        email = request.args.get("email") if (
            request.args.get("email")) else request.get_json().get("email")

        if not openid_get or not openid or not email:
            raise ValueError("错误,参数")
    except Exception as e:
        logging.error(e)
        return error_message

    if not re.findall("(@wolfcode.cn|520it.com)", email):
        message['status'] = "邮箱的格式必须是你的名字拼音加@wolfcode.cn"
        return jsonify(message)

    if request.method == 'GET':
        # 如果是get请求的话, 就准备生成验证码,放到数据库

        # 然后,想想用户的习惯,肯定是乱点乱按的,所以考虑到这一点,要多做一个步骤.

        # 查询具体openid有没有存在于数据库当中
        exist_openid = User.query.filter(
            or_(User.email == email, User.xcx_openid == openid,
                User.xcx_openid_tmp == openid)).first()

        if not exist_openid:

            exist_user = User()
            exist_user.username = openid
            exist_user.password = "******"
            exist_user.department = 20
            exist_user.email = email
            exist_user.realname = "wolfcode"
            exist_user.xcx_openid_tmp = openid

            # 如何判断时间呢?好像出了使用redis,好像真的没有其他好的方式了.一个有效期.
            # 现在只能简单点了,直接只能判断设置一次验证码吧.简单点,不用添加太多的流程.

            # 然后生成随机数
            verify_code = "".join(
                [str(random.randint(0, 9)) for x in range(4)])

            exist_user.quick_verify = verify_code
            print(verify_code)

            try:

                message1 = Message("叩丁狼小程序-认证",
                                   sender='*****@*****.**',
                                   recipients=[
                                       email,
                                   ])
                message1.html = "你的验证码是:%s" % verify_code
                mail.send(message1)

                db.session.add(exist_user)
                db.session.commit()
                db.session.close()
                message['statusCode'] = '200'
                message['status'] = "发送成功!请去邮箱查看验证码"

            except Exception as e:

                logging.error(e)
                logging.error("01")
                message['statusCode'] = '201'
                message['status'] = "发送失败,请检查-01"

        else:

            print(exist_openid.quick_verify)

            if not exist_openid.quick_verify:

                try:

                    verify_code = "".join(
                        [str(random.randint(0, 9)) for x in range(4)])
                    exist_openid.quick_verify = verify_code
                    exist_openid.xcx_openid_tmp = openid
                    db.session.add(exist_openid)
                    db.session.commit()
                    db.session.close()

                    message1 = Message("叩丁狼认证",
                                       sender='*****@*****.**',
                                       recipients=[
                                           email,
                                       ])
                    message1.html = "你的验证码是:%s" % verify_code
                    mail.send(message1)

                    message['statusCode'] = '200'
                    message['status'] = "已经发送验证码到你的邮箱"

                except Exception as e:
                    logging.error(repr(e))
                    logging.error(traceback.format_exc())
                    logging.error("在给已存在的用户发送验证码失败,-01")
                    return error_message

            else:

                message['status'] = "请检查你的邮箱,或者存在本次请求的验证码"
                return jsonify(message)

        db.session.close()
        return jsonify(message)

    elif request.method == 'POST':

        verify_code = request.get_json().get("verifyCode")

        if not verify_code:
            message['status'] = "缺少验证码"
            return jsonify(message)

        try:

            # 首先查询用户是否存在先.
            # 为了应付验证,先假想验证码统一都是6666.

            exist_user = User.query.filter(
                User.xcx_openid_tmp == openid, User.email == email,
                User.quick_verify == verify_code).first()
            # exist_user = User.query.filter(User.xcx_openid_tmp == openid, User.email == email).first()

            if exist_user:
                # if exist_user and verify_code == "6666":

                exist_user.xcx_openid = exist_user.xcx_openid_tmp
                exist_user.xcx_openid_tmp = None
                db.session.add(exist_user)
                db.session.commit()
                db.session.close()

                message['statusCode'] = '200'
                message['status'] = "注册成功,请下拉刷新数据!"

            else:

                message[
                    'status'] = "注册失败!\t可能原因一:你还没有发送验证码到你的邮箱\t原因二:可能你的邮箱地址和openid不对性\t原因三:你的验证码不正确,请检查"

        except Exception as e:
            logging.error(e)
            return error_message

        return jsonify(message)

    else:
        return error_message
Exemplo n.º 9
0
def request_verify():
    db.session.close()
    message = {}
    message['statusCode'] = '201'
    message['status'] = "初始状态,不带数据"

    if request.method == "GET":

        code = request.args.get("code")

        if not code:
            message['status'] = '缺少关键词code'
            return jsonify(message)

        openid = code2openid(code)
        # 去请求,尝试获取用户的openid

        if openid:
            # 可以使用数据库查询openid是否存在于数据库当中
            exist_openid = User.query.filter(User.xcx_openid == openid).first()

            if exist_openid:
                message['statusCode'] = '200'
                message['status'] = "用户名:%s" % (exist_openid.realname)

                # 就是这里了,应该需要返回另外的关键数据了.

                # 然后这里还可以添加其他的关键返回参数,例如是token值
                # response = make_response("set cookie")
                # response.set_cookie("username",exist_openid.realname)
                session['username'] = exist_openid.realname
                session['openid'] = exist_openid.xcx_openid
                session['uid'] = exist_openid.id

                try:
                    token = get_access_token_to_estimate(
                        exist_openid.xcx_openid)

                    # 尝试整理session值.
                    session['sessionid'] = token.split("=")[1]

                except Exception as e:
                    logging.error(e)
                    # 尝试获取estimate的访问token
                    message['status'] = "异常,将无法设置评分系统,但其他正常"
                    return jsonify(message)

            else:
                # 设置回复信息,

                message['statusCode'] = '201'
                message['status'] = '没有用户相关信息'

            db.session.close()

        return jsonify(message)

    else:

        register_info = request.get_json()
        print(register_info)

        realname = register_info['realname']
        code = register_info['code']

        if not all([realname, code]):
            message['status'] = "参数不完整"
            return jsonify(message)

        # 然后就是调用 解code为openid的函数了.

        # 获取的到openid,
        openid = code2openid(code)
        print(openid)
        if not openid:
            message['status'] = "获取openid失败"
            return jsonify(message)

        # 然后结合realname查询

        # 尝试查询是否存在用户
        try:
            exist_user = User.query.filter(User.realname == realname).first()

            if exist_user:

                # 如果存在,使用update更新用户信息
                exist_user.xcx_openid_tmp = openid

            else:

                exist_user = User()
                exist_user.username = openid
                exist_user.password = "******"
                exist_user.department = 20
                exist_user.email = "*****@*****.**"
                exist_user.realname = realname
                exist_user.xcx_openid_tmp = openid

            insert_time = datetime.now().strftime("%m-%d %H:%M")
            exist_user.quick_verify = insert_time

            db.session.add(exist_user)
            db.session.commit()
            db.session.close()

        except Exception as e:
            logging.error(e)
            message['status'] = "数据库操作异常"
            return jsonify(message)

        message['status'] = "申请成功,请等待管理员审核"

        return jsonify(message)
Exemplo n.º 10
0
def query():
    # 重点,  1必须提供openid或者微信小程序的openid
    #       2.必须是登陆过的用户,直接提取session里面的openid来操作.
    # 是啊,一语惊醒梦中人,对啊,可以将token的值保存到临时的session当中的啦.!

    message = {}
    message['statusCode'] = '201'
    message['status'] = "query获取信息失败"
    error_message = jsonify(message)

    header = {
        "Cookie": "sessionid=" + session['sessionid'],
        'accept': 'application/json'
    }

    if session.get("username"):
        if request.method == 'GET':
            req_type = request.args.get("type")

            if req_type == 'network':

                req_url = base_url + "/estimate/index/network/"
                try:

                    html_1 = requests.get(req_url,
                                          headers=header,
                                          verify=False)
                except Exception as e:

                    message['status'] = "获取课室网络信息失败"
                    logging.error(e)

                    return jsonify(message)

                message['statusCode'] = '200'
                message['status'] = 'ok'
                message['all_class_info'] = json.loads(html_1.content.decode())
                message['forwardUrl'] = "/estimate/index/set_network/"

                return jsonify(message)

            elif req_type == 'class_network_account':

                message['statusCode'] = '200'
                message[
                    'status'] = "通常是用户名是:你的名字拼音\n通常密码是:你的拼音加@wolfcode\n\n例如:用户名:lizhixuan\n密码:lizhixuan@wolfcode\n\n\n\n如果不行的请使用通用账号\n账号:lizhixuan123\n密码:pc9527168"

                return jsonify(message)

            elif req_type == 'estimate_info':

                port = request.args.get('port')

                try:
                    response = requests.get(
                        url=base_url +
                        "/estimate/index/export/?port=%s" % port,
                        headers=header,
                        verify=False)

                    response_content = json.loads(response.content.decode())

                    response_content['status'] = '请求成功'
                    response_content['statusCode'] = '200'

                    return jsonify(response_content)

                except Exception as e:

                    logging.error(e)

                    return error_message

            elif req_type == 'show_detail':

                req_url = request.args.get("url")

                url = base_url + "/estimate/index/export_txt/" + req_url

                response = requests.get(url=url, headers=header)

                response_decode = response.content.decode()

                parse_content = etree.HTML(response_decode)

                content = (''.join(parse_content.xpath("/html//div//text()"))
                           ).strip().replace("\n", '').replace('\t\t',
                                                               '\t').replace(
                                                                   '  ', ' ')

                message['status'] = "请求成功"
                message['statusCode'] = '200'
                message['content'] = content

                return jsonify(message)

            return jsonify(message)

        else:

            return error_message

    else:

        message['status'] = "你尚未登陆"
        return jsonify(message)
Exemplo n.º 11
0
def review():
    db.session.close()
    message = {}
    message['status'] = ''
    message['code'] = 201
    message['content'] = ''

    message_json = jsonify(message)

    if (not check_user_login_status()):
        return jsonify(message)

    if (request.method == "GET"):

        # 获取权限组
        auth_users = AuthUser.query.filter(AuthUser.id == 1).first()

        userids = []

        if (auth_users):
            userids = auth_users.member.split(",")

        if (not session.get('username')
                or not str(session.get('uid')) in userids):
            return jsonify({'status': '没有权限操作!'})

        ##返回joson格式,让小程序可以直接接受

        # 查询有多少个符合的待审核结果
        now_time = datetime.datetime.now()
        activity_review = Activity.query.filter(Activity.end_date >= now_time,
                                                Activity.passed == 0).all()

        if (activity_review):

            ##然后就去整理结果了,!最后输出json格式.!

            # 我要组织成为一个数组?
            content = []
            for x in activity_review:
                content1 = {}
                content1['name'] = x.apply_name
                content1['topic'] = x.topic
                content1['start_date'] = x.start_date.strftime(
                    "%Y-%m-%d %H:%M")
                content1['end_date'] = x.end_date.strftime("%Y-%m-%d %H:%M")
                content1['uuid'] = x.uuid
                content.append(content1)

            message['content'] = content

        else:
            pass
            print("不好意思,这个位置是没有结果的!")

        return jsonify(message)

    elif (request.method == "PUT" or request.method == "DELETE"):

        # 这里就是更新操作了,就是通过和不通过的操作了.!
        ##这里就是当作是审核通过的意思了.!
        try:

            pass
            # 尝试接收数值
            json_data = json.loads(request.get_data())
            uuid = json_data.get('id')
            ##拿到uuid数值,然后就是需要进一步操作了.!

            # 查询对应的记录.两条记录
            act_now = Activity.query.filter(Activity.uuid == uuid).first()
            act_history = ActivityHistory.query.filter(
                ActivityHistory.uuid == uuid).first()

            # 审核的时候,判断是否和已经审核通过的条目对比
            try:
                if (request.method == "PUT"):
                    mess1 = check_activity_passed(act_now)

                    if (mess1['code'] == 500):
                        return jsonify(mess1)

            except Exception as e:

                logging.error(e)
                logging.error("更新出现问题")

            # 然后进行更新.
            if (request.method == "PUT"):
                act_now.passed = 1
                act_history.passed = 1
            else:

                act_now.passed = -1
                act_history.passed = -1

            db.session.add(act_now)
            db.session.add(act_history)

            db.session.commit()
            db.session.close()

        except Exception as e:

            logging.error(e)
            logging.error("审核流程出错!")
            db.session.rollback()
            db.session.close()
            message['status'] = "出错!"
            pass

        return jsonify(message)

    else:

        return jsonify(message)
Exemplo n.º 12
0
def set_activity():
    if request.method == "GET":

        return "NOT SUPPORT GET METHOD!"

    elif request.method == "POST":

        print(session)
        message = {}
        json_data = json.loads(request.get_data())
        message['statusCode'] = '201'
        message['status'] = "activity设置失败!"
        error_message = jsonify(message)

        if not check_user_login_status():
            return jsonify(message)

        setting_info = {}
        setting_info['topic'] = json_data.get('topic')
        setting_info['name'] = json_data.get('name')
        setting_info['startDate'] = json_data.get('startDate')
        setting_info['endDate'] = json_data.get('endDate')

        # 然后这里必须是获取了登陆!.
        # 其实简单查看一下是否存在username应该就差不多的了.!

        print(setting_info)

        if session.get("username") and all([
                setting_info['topic'], setting_info['name'],
                setting_info['startDate'], setting_info['endDate']
        ]):

            # 进行权限设置
            try:

                setting_info['startDate'] = datetime.datetime.strptime(
                    json_data.get('startDate'), "%Y-%m-%d %H:%M")
                setting_info['endDate'] = datetime.datetime.strptime(
                    json_data.get('endDate'), "%Y-%m-%d %H:%M")

            except Exception as e:

                if isinstance(setting_info['startDate'], datetime.datetime):

                    setting_info['endDate'] = setting_info['startDate']

                else:
                    logging.error(e)
                    message['status'] = "发生参数验证错误!或者没有设置日期"
                    return jsonify(message)

            if setting_info['endDate'] < setting_info['startDate']:
                message['status'] = "时间格式错误!"
                return jsonify(message)

            # 然后进入正式的时间设置流程了.!

            # 这个地方还没有设置好数据库的啦!.
            # message['status'] = True

            # 然后就是需要设计数据表了.!

            try:
                pass
                # 这里有两个地方需要设置,第一呢,就是,

                # 把过期的申请取消掉先.!
                # 获取当前时间
                now_time = datetime.datetime.now()

                update_activity()

                # 然后需要查询是否和当前的活动冲突!

            except Exception as e:

                logging.error(e)
                db.session.rollback()
                db.session.close()
                pass
            # topic
            # name
            # date

            # 需要检测当前那些已经申请通过的活动

            try:
                # 然后整理数据,准备插入.

                topic = Activity()
                topic_history = ActivityHistory()

                uuid1 = str(uuid.uuid1())[:8]
                topic_history.uuid, topic.uuid = uuid1, uuid1
                topic_history.topic, topic.topic = setting_info[
                    'topic'], setting_info['topic']
                topic_history.apply_name, topic.apply_name = setting_info[
                    'name'], setting_info['name']
                topic_history.crm_username, topic.crm_username = session.get(
                    'username'), session.get('username')
                topic_history.start_date, topic.start_date = setting_info[
                    'startDate'], setting_info['startDate']
                topic_history.end_date, topic.end_date = setting_info[
                    'endDate'], setting_info['endDate']

                class object1:

                    pass

                o1 = object1()

                o1.start_date = setting_info['startDate']
                o1.end_date = setting_info['endDate']

                print(o1.start_date)
                print(o1.end_date)

                mes1 = check_activity_passed(o1)

                if mes1['code'] == 500:
                    return jsonify(mes1)

                db.session.add(topic)
                db.session.add(topic_history)
                db.session.commit()

                message['status'] = True

            except Exception as e:

                logging.error(e)
                logging.error("数据库保存错误!")
                db.session.rollback()
                message['status'] = "数据保存失败!请联系beetle Lai"

            db.session.close()

            # 终于搞掂空参数问题了.!

            # 搞掂之后,需要给名胜和beetle发送一份邮件测试一下
            msg = Message("你有一个活动室申请需要审核,请打开wolfcodeOAservice小程序查看",
                          sender='*****@*****.**',
                          recipients=[
                              "*****@*****.**",
                              "*****@*****.**"
                          ])

            msg.body = "你有一个活动室申请需要审核,请打开wolfcodeOAservice小程序查看!"

            # 编辑好一个用于激活邮箱地址的加密token

            msg.html = "你有一个活动室申请需要审核,请打开wolfcodeOAservice小程序查看"

            mail.send(msg)

            return jsonify(message)

    else:
        pass

    message['status'] = "缺少参数"
    return jsonify(message)