def system_health_restart_service(service_name):
    output = restart_service(service_name)
    if output[0] == True:
        logger.logger(level=logger.INFO , type="admin", message="Service ["+service_name+"] has been restarted")
        return json.jumps({'result' : 'success' , 'data': output[1]})
    else:
        logger.logger(level=logger.ERROR , type="admin", message="Failed restarting the service ["+service_name+"]" , reason=output[1])
        return json.jumps({'result' : 'failed' , 'data': output[1]})
Example #2
0
def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    headers = {"Content-Type": "application/json;charset=UTF-8"}
    for line in event['Records']:
        if line.get('eventName') == 'INSERT':
            try:
                courseId = line.get('dynamodb').get('NewImage').get(
                    'courseId').get('S')
            except:
                courseId = ''
            course = dynamodb.Table('Course')
            response_board = course.query(
                KeyConditionExpression=Key('courseId').eq(courseId))

            registeredStudentNum = len(response_board['Items'])
            request_body = {}
            json_object = line.get('dynamodb').get('NewImage')

            request_body['input'] = json.dumps(json_object)
            request_body['name'] = str(uuid.uuid4())
            request_body[
                'stateMachineArn'] = 'arn:aws:states:us-east-2:540381565181:stateMachine:HelloWorld'

            response = requests.post(
                'https://06pya8zi41.execute-api.us-east-2.amazonaws.com/alpha/execution',
                data=json.jumps(request_body),
                headers=headers)

            print(response.json())

    return {'statusCode': 200, 'body': json.dumps(event)}
def gdisconnect():
    credentials = login_session.get('credentials')
    if credentials is None:
        response = make_response(json.jumps('Current user not connected.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    access_token = credentials.access_token
    url = 'https://accounts.google.com/o/oauth2/revoke?token=%s' % access_token
    h = httplib2.Http()
    result = h.request(url, 'GET')[0]

    if result['status'] == '200':
        # Reset the user's sesson.
        del login_session['credentials']
        del login_session['gplus_id']
        del login_session['username']
        del login_session['email']
        del login_session['picture']

        response = make_response(json.dumps('Successfully disconnected.'), 200)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        # For whatever reason, the given token was invalid.
        response = make_response(
            json.dumps('Failed to revoke token for given user.', 400))
        response.headers['Content-Type'] = 'application/json'
        return response
Example #4
0
def resetFixture(request):
	if (request.method == "POST"):
		u = models.User.objects # ?
		status = u.TESTAPI_resetFixture()
		response = HttpResponse(json.jumps({'errCode': models.SUCCESS}),
                                content_type = 'application/json')
	else: # request.method == 'GET'
		response = HttpResponseServerError()
	return response
Example #5
0
 def proof_of_work(self):
     """
     Simple Proof of Work Algorithm
     Stringify the block and look for a proof.
     Loop through possibilities, checking each one against `valid_proof`
     in an effort to find a number that is a valid proof
     :return: A valid proof for the provided block
     """
     # TODO: one line version of code to stringify a block
     block_string = json.jumps(self.last_block, sort_keys=True).encode()
     proof = 0
     while self.valid_proof(block_string, proof) is False:
         proof += 1
     # return proof
     return proof
Example #6
0
def del_cls(cls):
    """
    delete a given class
    """
    sql_db = query.DB(SQLDB_PATH)
    if len(sql_db.search("blog", ("cls", cls))) != 0:
        sql_db.close()
        return json.dumps({
            "success": "false",
            "msg": "this class is not null"
        })
    else:
        sql_db.delete("cls", ("name", cls))
    sql_db.close()
    return json.jumps({"success": "true"})
Example #7
0
def handle_files():
    if request.method == 'POST':
        file = request.files['file']
        # validate file type
        if file is None:
            return json.jumps({'code': -2, 'msg': 'Missing uploaded file.'})
        try:
            file_id = create_file(file)
            return json.dumps({'code': 0, 'data': file_id})
        except ValueError as e:
            return json.dumps({'code': -1, 'msg': str(e)})
    else:
        file_id = request.data.decode('utf-8')
        if file_id is None or file_id == '':
            return json.dumps({'code': -1, 'msg': 'Missing file id.'})
        remove_file(file_id)
        return json.dumps({'code': 0, 'data': file_id})
Example #8
0
def put(header,
        address,
        request_parameter_type,
        data,
        timeout=8,
        files=None,
        cookie=None):
    if request_parameter_type == 'raw':
        data = json.jumps(data)
    response = requests.put(url=address,
                            data=data,
                            headers=header,
                            timeout=timeout,
                            files=files,
                            cookies=cookie)
    try:
        return response.status_code, response.json()
    except json.decoder.JSONDecodeError:
        return response.status_code, ''
    except Exception as e:
        logging.exception("ERROR")
        logging.error(e)
        raise
Example #9
0
def update(id, data):
    data = json.jumps(data)
    headers = {'content-type': 'application/json'}
    URL += '/{}'.format(id)
    response = requests.post(URL, data=data, headers=headers)
    return response
api_key = os.environ.get('api_key')
location = '&location=10.779614,106.699256'
radius = '&radius=5000'
type = '&type=cafe'
key = '&key={}'.format(api_key)
query = 'query=coffee'
link = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
tokens = '{}{}{}{}{}{}'.format(link, query, location, radius, type, key)

session = HTMLSession()
resp = session.get(tokens)
data = resp.json()

next_token = link + 'pagetoken={}' + key
fina_data = [dic['name'] for dic in data['results']]
print(next_token.format(data['next_page_token']))
while 'next_page_token' in data:
        try:
            resp = session.get(next_token.format(data['next_page_token']))
            data = resp.json()
            print(data['next_page_token'])
            fina_data.extend([name['name'] for name in data['results']])
            time.sleep(10)
        except KeyError:
            break


with open('coffee.json', 'wt', encoding='utf-8') as f:
    coffee_json = json.jumps(fina_data[:50])
    f.write(coffee_json)
Example #11
0
    def switch_done_callback(self, channel):
        print("done-state:" + self.state)
        # 승차 정류장 설정
        if self.state == "DEACTIVE":
            # GPS보내기
            pos_x, pos_y = hw.gps()
            dict_data = dict()
            dict_data['pos_x'] = pos_x
            dict_data['pos_y'] = pos_y
            url = host + '/api/gps/stn'
            res = requests.post(url, data=json.dumps(dict_data))

            self.current_stn_name = res.json()[0]['stn_name']
            self.current_stn_id = res.json()[0]['stn_id']

            print("승차 할 정류소가 \'" + self.current_stn_name + "\'가 맞습니까?\n")
            #tts.tts_input("승차할 정류소가 "+selected_stn_name+"가 맞습니까?")
            # TODO : 승차 정류소가 맞다면 save, 아니면 pre 눌러서 분기--> 그 이후에 상태 바꾸기
            self.state = "DEACTIVE_CHK"

        # 승차 정류장 설정 확인
        elif self.state == "DEACTIVE_CHK":
            print("승차 정류장 설정 완료")
            #tts.tts_input("승차 정류장 설정이 완료되었습니다.")
            print("노선 번호를 입력하세요")
            self.state = "ROUTE_NAME"

        # 노선 입력
        elif self.state == "ROUTE_NAME":
            if self.selected_route_name != "":
                print("승차 노선이 " + self.selected_route_name + "가 맞습니까?\n")
                #tts.tts_input("승차 노선이 "+selected_route_name+"가 맞습니까?")
                self.state = "ROUTE_NAME_CHK"
            else:
                print("입력된 노선이 없습니다")

        # 노선 입력 확인
        elif self.state == "ROUTE_NAME_CHK":
            print("노선 설정 완료")
            #tts.tts_input("노선 설정이 완료되었습니다.")
            self.state = "STN_NAME"
            print("하차역을 설정하세요")
            bs.selectStation(self.selected_route_name, self.current_stn_name)

        # 하차벨 예약
        elif self.state == "STN_NAME":
            self.selected_stn_name = bs.curr_stop
            self.selected_stn_id = bs.bus_stop_id[bs.ind]
            print("buttonClass" + str(self.selected_stn_name) +
                  str(self.selected_stn_id))
            if self.selected_stn_id == "" or self.selected_route_name == "":
                self.state = "STN_NAME"
                print("유효하지 않은 역 또는 노선")

                return
            # else:
            #     #하차벨 예약 중 누름
            #     tts.tts_input("성수역")

            dict_data = dict()
            dict_data['stn_id'] = self.selected_stn_id
            dict_data['route_nm'] = self.selected_route_name
            url = host + '/api/route-station-chk'
            data = requests.post(url, data=json.dumps(dict_data))
            if data.status_code != 200:
                print("해당 역이 노선에 없습니다.")
                print("하차역을 설정하세요")
                return

            print("status code : " + str(data.status_code) + "\n")

            print("노선 " + self.selected_route_name + " 과 정류장 이름 " +
                  self.selected_stn_id + " 가 맞습니까? ")
            self.state = "STN_NAME_CHK"
        elif self.state == "STN_NAME_CHK":
            dict_data = dict()
            dict_data['stn_id'] = self.selected_stn_id
            dict_data['route_nm'] = self.selected_route_name
            dict_data['user_id'] = self.userId
            url = host + '/buzzer/register'
            data = requests.post(url, data=json.jumps(dict_data))
            if data.status_code == 200:
                print("예약 성공!")
            else:
                print("예약 실패")
            return
Example #12
0
                return json.dumps({rescode:SERVER_ERROR})
        elif para[request] == 'delType':
            try:
                if not ifTypeExist(para[typename]):
                    return json.dumps({rescode:TYPE_NOT_EXIST})
                delType(para[typename])
                return json.dumps({rescode:SUCCESS}) 
            except BaseException, e:
                print 'Trace back: ', e
                return json.dumps({rescode:SERVER_ERROR})
        elif para[request] == 'updateType':
            try:
                if not ifTypeExist(para[typename]):
                    return json.dumps({rescode:TYPE_NOT_EXIST})
                if not typetext in para:
                    return json.jumps({rescode:PARA_ERROR})
                updateType(para[typename], para[typetext])
                return json.dumps({rescode:SUCCESS}) 
            except BaseException, e:
                print 'Trace back: ', e
                return json.dumps({rescode:SERVER_ERROR})
        else:
            return json.dumps({rescode:PARA_ERROR})

class Seller:
    def GET(self):
        pass
    def POST(self):
        para = web.input()
        print para
        if not username in para or not request in para:
 def update(self, key, content):
     updated = self.service.request(self.path + "/%s" % (key), method='POST', headers=self.headers, \
         owner='nobody', app=self.APPNAME, body=json.jumps(content))