示例#1
0
    def post(self):

        # Write content to temporary file
        tempfile = os.path.join(TEMP_DIRECTORY, "temp.wav")
        with open(tempfile, "wb") as fp:
            fp.write(request.get_data())

        # Analyze file
        with io.open(tempfile, 'rb') as fh:
            parser = TinyTag.get_parser_class(tempfile, fh)

        # Check if WAV file
        print("Tag Parser Name: {}".format(parser.__name__), file=sys.stderr)
        if (parser.__name__ == "Wave"):
            tag = TinyTag.get(TEMP_DIRECTORY + '/temp.wav')
            fid = uuid.uuid1()
        else:
            return {
                'message': 'Sound not registered. Not a WAVE file.',
                'filetype': parser.__name__
            }, 400

        if (tag.filesize < 12):
            return {
                'message': 'Sound not registered. Empty WAVE file.',
                'size': tag.filesize
            }, 400

        # Save file
        print("Tag Title: {}".format(tag.title), file=sys.stderr)
        print("Filename: {}".format(UPLOAD_DIRECTORY + fid.hex + tag.title +
                                    ".wav"))
        filename = os.path.join(UPLOAD_DIRECTORY, fid.hex + tag.title + ".wav")
        with open(filename, "wb") as fp:
            fp.write(request.get_data())

        # Store in database
        shelf = get_db()
        shelf[fid.hex] = {
            'id': fid.hex,
            'name': tag.title + ".wav",
            'duration': tag.duration,
            'size': tag.filesize
        }

        return {
            'message': 'Sound registered',
            'id': fid.hex,
            'name': tag.title + ".wav",
            'size': tag.filesize,
            'duration': tag.duration
        }, 201
示例#2
0
文件: server.py 项目: amirj11/cortex
    def post(self, user_id):
        logging.debug("Got Snapshot for user {}".format(user_id))

        # get snapshot from POST data and deserialize it
        request.get_data()
        data = request.data
        snapshot_message = Snapshot()
        snapshot_message.ParseFromString(data)

        # re-serializing the snapshot into JSON, to de-couple the client-server protocol
        # from the server-mq protocol.
        pathlib.Path("{}".format(RAW_DIR)).mkdir(parents=True, exist_ok=True)
        # save color image data as binary
        color_image_path = "{}/{}_{}_color".format(RAW_DIR, user_id,
                                                   snapshot_message.datetime)
        try:
            with open(color_image_path, "wb") as f:
                f.write(snapshot_message.color_image.data)
        except EnvironmentError as e:
            logging.error("Could not open {}: {}".format(color_image_path, e))
            sys.exit(1)
        # save depth image data as json string
        depth_image_path = "{}/{}_{}_depth".format(RAW_DIR, user_id,
                                                   snapshot_message.datetime)
        try:
            with open(depth_image_path, "w") as f:
                new_array = []
                for item in snapshot_message.depth_image.data:
                    new_array.append(item)
                result = {
                    "data": new_array,
                }
                serialized = json.dumps(result)
                f.write(serialized)
        except EnvironmentError as e:
            exit_run("Could not open {}: {}".format(depth_image_path, e))

        snapshot_json = snapshot_to_json(data, user_id)
        if globals()["PUBLISH_METHOD"] == "message_queue":
            logging.debug("Publishing Snapshot {} for user {} to MQ".format(
                snapshot_message.datetime, user_id))
            publish_snapshot(snapshot_json)

        elif globals()["PUBLISH_METHOD"] == "function":
            logging.debug(
                "Passing Snapshot {} for user {} to function.".format(
                    snapshot_message.datetime, user_id))
            globals()["PUBLISH"](snapshot_json)

        return 200
示例#3
0
文件: server.py 项目: amirj11/cortex
    def post(self, user_id):
        request.get_data()
        logging.debug("Got user message for user {}".format(user_id))
        data = request.data
        user_json = user_to_json(data)
        if globals()["PUBLISH_METHOD"] == "message_queue":
            logging.debug(
                "Publishing user message for user {} to MQ".format(user_id))
            publish_user_message(user_json)

        elif globals()["PUBLISH_METHOD"] == "function":
            logging.debug(
                "Passing user message for user {} to function".format(user_id))
            globals()["PUBLISH"](user_json)

        return 200
示例#4
0
 def post(self):
     data=request.get_data(as_text=True)
     inputdict=json.loads(data)['input']
     mark = json.loads(data)['mark']
     # self.makedir(mark)
     result=self.run(inputdict,mark)
     return json.dumps({"result":result})
示例#5
0
    def post(self):
        db_sess = db_session.create_session()
        try:
            data = loads(request.get_data())
            validate(instance=data, schema=ADD_SCHEMA)
            token = data.pop('token')
            user = db_sess.query(User).filter(User.token == token)[0]
            data['time'] = dt.strptime(data['time'], "%H:%M").time()
            data['day'] = dt.strptime(data['day'], "%m-%d-%Y").date()
            assert user

        except AssertionError:
            data = dumps({"error": "Неверный токен"})
            response = Flask.response_class(status=403,
                                            mimetype="application/json",
                                            response=data)
            return response

        except Exception as e:
            data = dumps({"error": str(e)})
            response = Flask.response_class(status=400,
                                            mimetype="application/json",
                                            response=data)
            return response

        data['owner_id'] = user.id
        table = Tables(**data)
        db_sess.add(table)
        db_sess.commit()
        db_sess.close()
        response = Flask.response_class(status=200)
        return response
示例#6
0
    def post(self):
        r = request.get_data()
        req = json.loads(r.decode('utf-8'))

        answer_text = req['answer_text']
        question_id = req['question_id']
        question_order = req['question_order']
        # if 'response_id' in req:
        #     response_id = req['response_id']
        #     #print('response_id is ', response_id)
        # else:
        #     response_id = None
        #     #print('response_id is none.')
        response_id = req.get('response_id', None)
        print('response_id is ',response_id)
        magic_text = survey_instance.get_magic_reply(answer_text, question_id)
        next_question_id = survey_instance.get_next_question_id(question_id, answer_text)
        response_id, response_answer_id = survey_instance.save_answer(response_id, question_id, question_order, answer_text)
        
        resp = { "magic_text": magic_text, "response_id": response_id, "next_question_id": int(next_question_id)}
        if next_question_id == -1:
            content = survey_instance.survey_retrieval(next_question_id, response_id)
            # print(content)
            # if content.empty:
            #     print("No data for the current survey.")
            # else:
            #     survey_instance.send_email(content, user, pw)
            if not content.empty:
                survey_instance.send_email(content, user, pw)

        return resp
示例#7
0
    def get(self):
        db_sess = db_session.create_session()
        try:
            data = loads(request.get_data())
            validate(instance=data, schema=LIST_SCHEMA)
            token = data.pop('token')
            user = db_sess.query(User).filter(User.token == token)[0]
            start = dt.strptime(data['start'], "%d-%m-%Y").date()
            end = dt.strptime(data['end'], "%d-%m-%Y").date()
            assert user

        except AssertionError:
            data = dumps({"error": "Неверный токен"})
            response = Flask.response_class(status=403,
                                            mimetype="application/json",
                                            response=data)
            return response

        except Exception as e:
            data = dumps({"error": str(e)})
            response = Flask.response_class(status=400,
                                            mimetype="application/json",
                                            response=data)
            return response
        response = list()
        for obj in db_sess.query(Tables).filter(Tables.day.between(start,
                                                                   end)):
            response.append(obj.to_dict())
        print(response)
        response = dumps(response)

        response = Flask.response_class(status=400,
                                        mimetype="application/json",
                                        response=response)
        return response
示例#8
0
    def post(self):
        print("fdshgf")
        print('Headers: %s', request.headers)
        print('Body: %s', request.get_data())

        data = UserRegister.parser.parse_args()
        if UserModel.find_by_username(data['username']):
            return {
                "message": {
                    "answer": "A user with that username already exists",
                    "apicode": "111"
                }
            }, 400
        if UserModel.find_by_emailId(data['emailId']):
            return {
                "message": {
                    "answer": "A user with that emailId already exists",
                    "apicode": "121"
                }
            }, 400
        print(data['username'], data['password'], data['emailId'])
        user = UserModel(data['username'], data['password'], data['emailId'],
                         data['premium'], 0)
        user.save_to_db()

        return {
            "message": {
                "answer": "User created successfully.",
                "apicode": "100"
            }
        }, 201
示例#9
0
 def post(self):
     jsoninfo = json.loads(request.get_data())
     username = jsoninfo['name']
     id = config.get_id_by_username(username)
     trialls_cmd = 'nnictl trial ls' + ' ' + id
     cm = subprocess.Popen(trialls_cmd, shell=True, stdout=subprocess.PIPE)
     info = cm.communicate()
     return jsonify(json.loads(info[0]))
示例#10
0
 def post(self):
     r = request.get_data()
     info = json.loads(r.decode('utf-8'))
     #print('info is ', info)
     user_request = info.get('user_request')
     recommendation = info.get('recommendation')
     start = time.time()
     episode_instance.save_recommendation_table(user_request,recommendation)
示例#11
0
    def post(self):
        data = request.get_data()
        sams = (json.loads(data)['sams'])

        for sam in sams:
            id = sam['id']
            Mutation.query.filter(Mutation.id == id).update(sam)
            db.session.commit()
        #     db.session.commit()
        return {'msg': '保存成功'}
示例#12
0
 def post(self):
     try:
         ui_data = request.form.to_dict()
         backend_data = request.get_data()
         req_body = ui_data if ui_data else json_loads(backend_data)
         status, res_body = self.actions.create(req_body)
         return get_response(status, res_body)
     except Exception as e:
         print e.message
         return error_handler(e.message)
示例#13
0
 def put(self, username):
     try:
         data = request.get_data()
         data = json.loads(data.decode("utf-8"))
     except Exception as e:
         self._logger.error("can't read put data", exc_info=True)
         raise ApiPreconditionFailedException(
             description="Application Error.")
     else:
         res = self.controllers.user.upsert_user(username, data)
     return res
示例#14
0
    def parsePostParameters(cls):
        print "-----parsePostParameters"
        print os.getcwd()
        args = loads(request.get_data())
        for key in cls.mandatoryFields:
            if key not in args:
                raise BadRequest("{0} parameter is missing".format(key))
            elif not isinstance(args[key], unicode):
                raise BadRequest("{0} value is not unicode".format(key))

        return args
示例#15
0
    def parsePostParameters(cls):
        print "-----parsePostParameters"
        print os.getcwd()
        args = loads(request.get_data())
        for key in cls.mandatoryFields:
            if key not in args:
                raise BadRequest('{0} parameter is missing'.format(key))
            elif not isinstance(args[key], unicode):
                raise BadRequest('{0} value is not unicode'.format(key))

        return args
示例#16
0
 def post(self):
     if ga_model == 'luis': 
         print('api: ga model is LUIS.') 
         ga_instance_report = ga_luis_report.ga_report()
     if ga_model == 'rasa':
         print('api: ga model is RASA.')
         ga_instance = ga_rasa.ga(update_model = True)
     r = request.get_data()
     ga_items = json.loads(r.decode('utf-8'))
     print('in google_analytics, input is ', ga_items)
     f = ga_instance_report.run(ga_items)
     return f # f is in json form: for example {'img': 'http://dataskeptic-static.s3.amazonaws.com/bot/ga-images/2017-11-10/transactions_userType_2016-11-10_2017-11-10.png', 'txt': ''}
示例#17
0
 def post(self, action=None):
     try:
         ui_data = request.form.to_dict()
         req_body = ui_data if ui_data else json.loads(request.get_data())
         if action == "start":
             status, res_body = self.actions.start_techslate_container(
                 req_body)
         else:
             status, res_body = 400, json.dumps({"message": "Bad request"})
         return get_response(status, res_body)
     except Exception as err:
         return error_handler(err)
示例#18
0
    def parse_args(self):
        """ Parses request based on arguments provided through add_argument
            method.

            Returns:
                :dict: if the request is correctly processed returns a dict
                       with arguments and their values
                :obj:'flask.wrappers.Response': if the parser failed to process
                                                returns a response object with
                                                an error message
        """
        data = {}
        locations = {
            'json':
            request.get_json(),
            'form':
            request.form.to_dict(),
            'args':
            request.args.to_dict(),
            'values':
            request.values.to_dict(),
            'text':
            request.get_data(),
            'headers':
            dict(
                zip([i[0] for i in request.headers.to_wsgi_list()],
                    [i[1] for i in request.headers.to_wsgi_list()])),
            'cookies':
            request.cookies
        }
        for loc in locations:
            if len(self.reqschema[loc].fields) > 0:
                try:
                    req = self.reqschema['json'].load(locations[loc])
                    if req.data is not None:
                        data.update(req.data)
                    error = {}
                    for i in self.reqschema['json'].fields:
                        f = self.reqschema['json'].fields[i]
                        if f.required and (req.data is None
                                           or i not in req.data):
                            error[i] = [f.error_messages['required']]
                    if len(error) > 0:
                        raise ValidationError(error)
                except ValidationError as err:
                    for r in err.messages:
                        if r in self.help:
                            err.messages[r].append(self.help[r])
                    for i in err.messages:
                        err.messages[i] = ' '.join(err.messages[i])
                    return mk_response(err.messages, 422)
        return data
示例#19
0
 def post(self):
     if ga_model == 'luis': 
         print('api: ga model in extracting ga items is LUIS.') 
         ga_instance_item = ga_luis_items.ga_items()
     if ga_model == 'rasa':
         print('api: ga model in extracting ga items is RASA.')
         ga_instance = ga_rasa.ga(update_model = True)
     r = request.get_data()
     user_info = json.loads(r.decode('utf-8'))
     print('api: user_info is ', user_info)
     user_request = user_info.get('user_request')
     ga_items = ga_instance_item.extract_ga_items(user_request) # using luis model.
     return ga_items
示例#20
0
    def post(self,
             event='',
             timestamp=None,
             user_id=0,
             entity_id='',
             url=None):
        if event == "EXERCISE" and user_id > 0 and entity_id != "":
            self.logger.debug(
                "Polar webhook endpoint request: event={evt}, timestamp={time}, user_id={uid}, entity_id={eid}"
                .format(evt=event, time=timestamp, uid=user_id, eid=entity_id))
            signature_key = current_app.config['POLAR_API_WEBHOOK_SIGNATURE']
            received_signature = ''
            if 'Polar-Webhook-Signature' in request.headers:
                received_signature = request.headers['Polar-Webhook-Signature']

            request.content_length
            calc_signature = ''
            if request.content_length < 500000:
                calc_signature = get_hmac_signature(signature_key,
                                                    request.get_data())
            else:
                self.logger.debug(
                    "Polar webhook endpoint request ignored due to content length {clen}, event={evt}, timestamp={time}"
                    .format(clen=request.content_length,
                            evt=event,
                            time=timestamp))

            if calc_signature == received_signature:
                self.logger.info("Polar webhook signature validated")
                if timestamp is None:
                    timestamp = dt.datetime.utcnow()
                try:
                    exercise = PolarWebhookExerciseModel(
                        user_id, entity_id, timestamp, url)
                    exercise.save()
                    self.logger.info("Polar webhook saved")
                except:
                    self.logger.error("Polar webhook failed to save")
                    db.session.rollback()
            else:
                self.logger.info(
                    "Polar webhook signature doesn't match ({calc},{actual})".
                    format(calc=calc_signature, actual=received_signature))
        else:
            self.logger.debug(
                "Polar webhook endpoint request ignored, event={evt}, timestamp={time}"
                .format(evt=event, time=timestamp))

        # always just return 200 without content
        return {}, 200
示例#21
0
 def post(self):
     data = request.get_data()
     sams = (json.loads(data)['sams'])
     mg_id = (json.loads(data)['mg_id'])
     user = '******'
     print(sams)
     id = sams['id']
     # mu = Mutation.query.filter(Mutation.id == id).first()
     # if mu:
     #     print('hello')
     print(sams)
     Mutation.query.filter(Mutation.id == id).update(sams)
     db.session.commit()
     return {'msg': '修改完成'}
示例#22
0
 def post(self):
     r = request.get_data()
     req = json.loads(r.decode('utf-8'))
     user_request = req['request']
     start = time.time()
     result = episode_instance.recommend_episode(user_request)
     #print("the time it takes to make a recommendation is ", time.time() - start)
     # start = time.time()
     # episode_instance.save_recommendation_table(user_request, result)
     # print('the time it takes to save the recommendation to table is ', time.time() - start)
     if len(result) > 0:
         return result
     else:
         return None
示例#23
0
    def post(self):
        data = request.get_data()
        if data is None:
            app.logger.error('post data is none')
            return None, 200
        if len(data) == 0:
            app.logger.error('post data is blank')
            return None, 404
        try:
            data = re.sub('gbk', 'utf-8', data.decode('utf-8')).encode('utf-8')
            params = Xml.resove_xml(data)
        except BaseException as e:
            app.logger.error('请求内容编码格式错误,%s' % str(e))
            return '请求内容编码格式错误', '500'

        _info = params.get('inputchoosecontent')
        user_id = str(params.get('imUserNumber'))
        # print(params.get('imUserNumber'), ': ', _info)

        app.logger.info('%s: %s', params.get('imUserNumber'), _info)
        data = {'query': _info}
        api_url = 'http://localhost:5001/conversations/' + user_id + '/respond'
        response = requests.post(api_url,
                                 data=json.dumps(data),
                                 headers={
                                     'content-type': "application/json"
                                 }).text

        strs = json.loads(response, encoding='utf8')
        contents = ''
        for s in strs:
            content = s.get('text')
            contents = contents + str(content) + '\n'

        app.logger.info('机器人: \n%s', contents)
        results = {}
        results['key'] = 'inputchooseresult'
        results['value'] = contents
        results['code'] = 0
        results['reason'] = '响应成功'
        try:
            data = Xml.generate_xml(results)
            result = data
        except BaseException as e:
            app.logger.error('编码转换异常,%s' % str(e))
            return "编码转换异常", 500
        resp = make_response(result)
        resp.headers["Content-type"] = "application/xml;charset=gbk"
        return resp
示例#24
0
    def post(self):
        r = request.get_data() # request is RAW body in REST Console.
        user_info = json.loads(r.decode('utf-8'))
        #print('user_info is ', user_info)
        contact_type = user_info.get('contact_type')
        contact_account = user_info.get('contact_account')
        #reminder_time = user_info.get('reminder_time') 
        reminder_time = user_info.get('reminder_time')
        episode_titles = user_info.get('episode_titles')
        episode_links = user_info.get('episode_links')
       
        reminder_ins.save_reminder_task(contact_type, contact_account,reminder_time, 
                                                episode_titles, episode_links)

        return " Reminder will be sent."# + str(alarm_time)
示例#25
0
    def post(self):
        data = request.get_data()
        sams = (json.loads(data)['sams'])
        err = ''
        report = ''
        mmsg = ''
        user = '******'
        for sam in sams:
            sample = sam.get('sample_name')
            if sample.startswith('MG'):
                s = '(MG\d+)(\w{2})?(-\d)?'
                m = re.match(s, sample)
                if m:
                    # sam_name = m.group(1) + m.group(3) if m.group(3) else m.group(1)
                    sam_name = m.group(1)
                    sam_info = SampleInfo.query.filter(
                        SampleInfo.mg_id == sam_name).first()
                    if sam_info:
                        is_rep = 0
                        tags = []
                        for tag in sam_info.tags:
                            tags.append(tag.name)
                        if tags:
                            for tagg in tags:
                                if '承包中' in tagg:
                                    uuser = tagg.strip('承包中....')
                                    is_rep = 1
                        if is_rep:
                            mmsg += '{}已经被{}承包\t'.format(sam_name, uuser)
                        else:
                            tag = Tag.query.filter(
                                Tag.name == '{}承包中....'.format(user)).first()
                            if tag:
                                pass
                            else:
                                tag = Tag(name='{}承包中....'.format(user),
                                          description='报告正处于制作过程中')
                            db.session.add(tag)
                            sam_info.tags.append(tag)
                            db.session.commit()
                            mmsg += '成功承包{}这片鱼塘\t'.format(sam_name)
                    else:
                        mmsg += '请上传{}对应的样本信息\t'.format(sam_name)

            else:
                err += sample + '\t'

        return {'msg': mmsg, 'err': '{}'.format(err)}
示例#26
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('address')
        parser.add_argument('status')
        args = parser.parse_args()
        dtime = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
        try:
            status = '['+str(args['status'])+']'
            address = '['+str(args['address'])+']'
        except KeyError as e:
            print(dtime + ' no data' + str(e))
            print(request.get_data())
            return False

        print(dtime + " new status " + status + " for " + address)
        if status is not '':
            unspents = blistunspent(wallet)
        #print(unspents)
            for unspent in unspents:
                if address == unspent['address']:
                    amount_sats = unspent['value']*100000000
                    outhash = status
                    prev_outhash = unspent['prevout_hash']
                    if unspent['height'] == 0:
                        if not find_tx(outhash):
                            add_tx(address=address, txhash=outhash, amount_sats=amount_sats, status='paid', chargeid='none', prev_outhash=prev_outhash)
                        else:
                            print(dtime + 'tx already exists')
                    elif unspent['height'] > 0:
                        existing_tx = find_tx(outhash)
                        if existing_tx:
                            if existing_tx['status'] == 'paid':

                                new_host = find_host(address)
                                if new_host:
                                    if new_host['status'] == 'new':
                                        serverData = new_server(address, new_host['image'])

                                update_tx(address, outhash, 'confirmed')
                                hours = convert_sats2hours(address, amount_sats)
                                subscribe_host(address, hours)
                                print("\n\n" + str(find_host(address)) + "\n\n")
                            else:
                                print(dtime + ' ' + outhash + 'tx already confirmed')
                        else:
                            print(dtime + ' ' + outhash + ' tx not found but confirmed')

        return True
示例#27
0
 def post(self):
     # 接收对象
     parser = json.loads(request.get_data())
     content = str(parser['content'])
     sa_score = round(float(model.predict([content])[0][1]), 5)
     show_data = dict()
     show_data['sa_score'] = sa_score
     show_data['status'] = 1
     if sa_score > 0.5:
         show_data['label'] = '积极'
     elif sa_score < 0.5:
         show_data['label'] = '消极'
     else:
         show_data['label'] = '中性'
     # print(show_data)
     return show_data
示例#28
0
    def put(self):
        raw_data = request.get_data()
        print('Client request received.')
        print(raw_data)

        args = json.loads(raw_data)

        to_list = list(args.values())
        nparray = np.array(to_list)

        prediction = model.predict(nparray.reshape(1, -1))
        proba = model.predict_proba(nparray.reshape(1, -1))

        answer = prediction + ',' + str(proba[0])

        print('Responding to client request...')
        print(answer)
        return json.dumps(answer.tolist()), 201
示例#29
0
 def post(self):
     jsoninfo = json.loads(request.get_data())
     username = jsoninfo['name']
     id = config.get_id_by_username(username)
     stop_cmd = 'nnictl stop' + ' ' + id
     cm = subprocess.call(stop_cmd, shell=True)
     if (cm == 0):
         config.release_port_by_username(username)
         return jsonify({
             'status': '0',
             'message': 'Successfully stop the experiment!',
             'experiment_ID': id
         })
     else:
         return jsonify({
             'status': '1',
             'message': 'Failed to stop the experiment!',
             'experiment_ID': 'error'
         })
示例#30
0
 def post(self, item):
     from urllib.parse import unquote
     data = (request.get_data()).decode(encoding='UTF-8', errors='strict')
     data_dic = {}
     for i in data.split('&'):
         a, b = i.split('=')
         data_dic[a] = unquote(
             b) if a not in data_dic else data_dic[a] + ('-*-' + unquote(b))
     print('data:**************', data)
     if item == 'category':
         name = data_dic['name'] if 'name' in data_dic else None
         if Category.query.filter_by(name=name).first():  #查询该类名已经存在
             return json.dumps({'info': 'already exist', 'result': 'fail'})
         else:  #该类名不存在,创建新的类
             try:
                 new_category = Category(name)
                 db.session.add(new_category)
                 db.session.commit()
                 info = '<%s> 创建成功!' % name
                 result = (new_category.id, name)
             except Exception as e:
                 info = '<%s> 创建失败,原因: [%s]' % (name, e)
                 result = 'fail'
             return json.dumps({'info': info, 'result': result})
     elif item == 'student' or item == 'teacher':
         name = data_dic['name'] if 'name' in data_dic else None
         birthday = data_dic['birthday'] if 'birthday' in data_dic else None
         gender = data_dic['gender'] if 'gender' in data_dic else None
         categorys = (data_dic['categorys']
                      ).split('-*-') if 'categorys' in data_dic else None
         if (name and birthday and gender and categorys):
             if item == 'student':
                 new_people = Student(
                     name, gender, datetime.strptime(birthday, "%Y-%m-%d"))
             elif item == 'teacher':
                 new_people = Teacher(
                     name, gender, datetime.strptime(birthday, "%Y-%m-%d"))
             [
                 new_people.categorys.append(Category.query.get(category))
                 for category in categorys
             ]
             db.session.add(new_people)
             db.session.commit()
示例#31
0
    def post(self):
        data = request.get_data()
        if data is None:
            app.logger.error('post data is none')
            return None, 200
        if len(data) == 0:
            app.logger.error('post data is blank')
            return None, 404
        try:
            data = re.sub('gbk', 'utf-8', data.decode('utf-8')).encode('utf-8')
        except BaseException as e:
            app.logger.error('请求内容编码格式错误,%s' % str(e))
            return '请求内容编码格式错误', '500'
        params = Xml.resove_xml(data)

        _info = params.get('inputchoosecontent')
        print(params.get('imUserNumber'), ': ', _info)

        app.logger.info('%s: %s', params.get('imUserNumber'), _info)
        data = {
            'key': '5765096de11a4f5381e4c63cb84392ea',
            'info': _info,
            'userid': 'robot',
        }
        api_url = 'http://www.tuling123.com/openapi/api'
        response = requests.post(api_url, data).json()
        print('机器人: ', response.get('text'))
        app.logger.info('机器人: %s', response.get('text'))
        results = {}
        results['key'] = 'inputchooseresult'
        results['value'] = response.get('text')
        results['code'] = 0
        results['reason'] = '响应成功'
        try:
            data = Xml.generate_xml(results)
            result = data
        except BaseException as e:
            app.logger.error('编码转换异常,%s' % str(e))
            return "编码转换异常", 500
        resp = make_response(result)
        resp.headers["Content-type"] = "application/xml;charset=gbk"
        return resp
示例#32
0
    def post(self):
        utils.debug_print('POSTED!')
        utils.debug_print('H',request.headers)
        try:
            utils.debug_print('L',len(request.get_data()))
        except Exception as exc:
            print(exc)
            print('OH NO an error in assistant_blueprint!',exc,sys.exc_info())

        # TODO? replace with msgpack
        args = self.deserialise(request.get_data())

        # Unpacking the YAML/ZIP file
        for key in args:
            if key not in {'bucket_id', 'key_id', 'secret_key'}:
                comma_idx = args[key].find(',')
                args[key] = args[key][comma_idx + 1:]
                if args[key] in {'True', 'False'}:
                    args[key] = True if args[key] == 'True' else False
                else:
                    args[key] = base64.decodestring(args[key])

        if all([key not in args for key in ['bucket_id', 'key_id', 'sercret_key']]):
            args['upload'] = False
        else:
            args['upload'] = True

        utils.debug_print('args.keys() = ', args.keys())

        args['args'] = yaml.load(args['args'])

        try:
            init_exp_args = args['args']
            utils.debug_print("args.keys = ", args['args'].keys())
            if 'targets' in args.keys():
                target_zipfile = args['targets']
                utils.debug_print("args = ", args)
                if args.get('upload', True):
                    bucket_id = args['bucket_id']
                    key_id = args['key_id']
                    secret_key = args['secret_key']

                    for x_ in ['bucket_id', 'secret_key', 'key_id']:
                        utils.debug_print(x_, args[x_])
                    # Unpack the targets
                    targets = target_unpacker.unpack(target_zipfile, key_id,
                                                     secret_key, bucket_id)
                else:
                    targets = target_unpacker.unpack_csv_file(target_zipfile)
                init_exp_args['args']['targets'] = {'targetset':  targets}

            # Init the experiment:
            app_id = init_exp_args['app_id']
            exp_uid = '%030x' % random.randrange(16**30)

            r = broker.applyAsync(app_id, exp_uid, 'initExp',
                                  json.dumps(init_exp_args))
            response_json, didSucceed, message = r
            if not didSucceed:
                raise ValueError(message)
        except:
            tb = traceback.format_exc()
            info = sys.exc_info()
            if hasattr(info[1], 'message') and len(info[1].message) > 0:
                message = info[1].message
                if 'time' in message:
                    message += ("\nNOTE: error has to do with time; try "
                                "restarting docker, more detail at "
                                "https://stackoverflow.com/questions/27674968/amazon-s3-docker-403-forbidden-the-difference-between-the-request-time-and")
            else:
                message = str(info[1]) + str(info[-1])
                message = '\n'.join(tb.split('\n')[-5:])
            message = message + '\n\nDetails:\n' + tb

            return {'success': False, 'message': message, 'exp_uid': None}

        return {'success': didSucceed, 'message': message, 'exp_uid': exp_uid,
                'app_id': args['args']['app_id']}