コード例 #1
0
 def create(self):
     request.post(self,
                  json={
                      "name": name,
                      "parentid": parentid,
                      "order": order,
                      id: ""
                  }), json()
コード例 #2
0
ファイル: client.py プロジェクト: Carsmaniac/paintjob-packer
    def _enqueue(self, msg):
        """Push a new `msg` onto the queue, return `(success, msg)`"""
        timestamp = msg['timestamp']
        if timestamp is None:
            timestamp = datetime.utcnow().replace(tzinfo=tzutc())
        message_id = msg.get('messageId')
        if message_id is None:
            message_id = uuid4()

        require('integrations', msg['integrations'], dict)
        require('type', msg['type'], string_types)
        require('timestamp', timestamp, datetime)
        require('context', msg['context'], dict)

        # add anonymousId to the message if not passed
        msg['anonymousId'] = msg['anonymousId'] or self.anonymoys_id

        # copy the userId to context.traits
        if msg['userId'] != None:
            if 'traits' in msg['context'].keys():
                msg['context']['traits']['userId'] = msg['userId']
            else :
                msg['context']['traits'] = {'userId': msg['userId']}

        msg['context']['traits']['anonymousId'] = msg['anonymousId']

        # add common
        timestamp = guess_timezone(timestamp)
        msg['timestamp'] = timestamp.isoformat()
        msg['messageId'] = stringify_id(message_id)
        msg['context']['library'] = {
            'name': 'rudder-analytics-python',
            'version': VERSION
        }

        msg['userId'] = stringify_id(msg.get('userId', None))
        msg['anonymousId'] = stringify_id(msg.get('anonymousId', None))

        msg = clean(msg)

        # if send is False, return msg as if it was successfully queued
        if not self.send:
            return True, msg

        if self.sync_mode:
            post(self.write_key, self.host, timeout=self.timeout, batch=[msg])

            return True, msg

        try:
            self.queue.put(msg, block=False)
            return True, msg
        except queue.Full:
            print("Analytics queue is full, skipping")
            return False, msg
コード例 #3
0
ファイル: shutdown.py プロジェクト: reshnm/WinControlServer
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-u',
                        '--url',
                        help='the url',
                        metavar='URL',
                        required=True)
    parser.add_argument('-t',
                        '--timeout',
                        help='the shutdown timeout',
                        metavar='Seconds',
                        default=0,
                        type=int)
    parser.add_argument('-f',
                        '--force',
                        help='force shutdown',
                        action='store_true',
                        default=False)
    args = parser.parse_args()

    url = args.url
    timeout = args.timeout
    force = args.force

    res = request.post(url + '/shutdown', {'timeout': timeout, 'force': force})
    request.print_response(res)
コード例 #4
0
ファイル: QuecThing.py プロジェクト: mfkiwl/EC100Y-SDK
def run():
    productKey = "K3I5ZkgyZjkydGli"
    productSecret = "VUFyVE92YVJmSUNQ"
    rand = "q9f5UdAlh687grFl0JVuyY6095302ehd"
    imei = modem.getDevImei()
    VER = '1'

    h1 = uhashlib.md5()
    h1.update(imei + "," + productSecret + "," + rand)
    SIGN = ubinascii.hexlify(h1.digest()).decode()
    print("MD5:   %s" % SIGN)  # 8ab41bc1e5e74fbf9cec16a6e0990d89

    DATA = imei + ";" + rand + ";" + SIGN
    print("DATA:  %s  " %DATA)
    h1 = uhashlib.sha1(productSecret)
    res = ubinascii.hexlify(h1.digest()).decode()
    print(res)
    res = uhashlib.hash_sha1(res, 20)
    print("SHA1(PS) :  %s" % res)
    aes_key = res[0:16].upper()
    print("aes_key : %s" % aes_key)
    res = uhashlib.aes_ecb(aes_key, DATA)
    print(res)
    raw = uhashlib.hash_base64(res)
    print(raw)
    data = productKey + ";" + raw + ";" + VER
    url = "220.180.239.212:8415"
    # url = "192.168.25.64:30884"
    response = request.post(url, data=data)
    print(response.json())   # 获取到密钥
    # {'RESPCODE': 10200, 'RESPMSG': 'SUCCESS', 'SERVERURI': 'mqtt://220.180.239.212:8420', 'DS': 'd5f01bddfc994c037be90ede69399ac0'}
    return response.json()
コード例 #5
0
ファイル: post.py プロジェクト: skinnyrad/PMT
def post_data(post_data, post_url, station, logger) -> bool:
    try:
        # init harware timer
        #timer = Timer(0)
        #TODO: Uncomment this for solution
        #timer.init(period=3000, mode=Timer.ONE_SHOT,callback=handlerTimer)
        try:
            [_, status, _, _, _] = post(post_url,
                                        headers=headers,
                                        data=post_data,
                                        timeout=10,
                                        verify=True)
        except ConnectionError as err:
            print("ConnectionError in post_data")
            print(err)
            return False

        #TODO: Uncomment this for solution
        #timer.deinit()
        if status == 200:
            #TODO: remove print
            print("Post Request [OK]")
            logger.info("Post Request [OK]")
            return True
        else:
            #TODO: remove print
            print("Post Request [Failed]")
            logger.info("Post Request [Failed]")
            return False
    except OSError as e:
        #TODO: remove print
        print("Error: {0}".format(str(e)))
        logger.warning(str(e))
        return False
コード例 #6
0
def call_keystone(username, password, tenant, auth_url):
    try:
        auth_req = {"auth": {
                             "tenantName": tenant,
                             "passwordCredentials": {
                                                     "username": username,
                                                     "password": password
                                                     }
                              }
                    }
    
    
        url = auth_url
        if url.endswith('/'):
            url = url + 'tokens'
        else:
            url = url + '/tokens'
        
        log.debug("Request post to URL %s " % url)
        log.debug("POST call payload %s " % json.dumps(auth_req))
        
        return request.post(url, data=auth_req, headers=headers)
    except Exception as e:
        log.info("Exception while calling Keystone %s " % e)
        raise Exception(e)
コード例 #7
0
 def test_method_post(self):
     body = {
         'name': 'Tester',
         'email': '*****@*****.**',
         'body': 'lorem ipsum',
         'postId': 1
     }
     self.assertTrue(len(request.post(COMMENTS_URL, data=body)))
コード例 #8
0
ファイル: test_app.py プロジェクト: zweifisch/klar
    def test_session(self):

        app = App()

        @app.get('/test')
        def test(session):
            if session.get('userid'):
                return 'userid: %s' % session.get('userid')
            return 'not logged in'

        @app.post('/login')
        def login(body, session):
            if body['username'] == 'admin' and body['passwd'] == 'secret':
                session.set('userid', 123)
                return 'logged in'
            return 'failed'

        @app.post('/logout')
        def logout(session):
            if session.get('userid'):
                session.destroy()
                return 'logged out'

        res = post(app, '/login', {'username': '******', 'passwd': 'secret'})
        assert res['status'] == '200 OK'
        assert res['body'] == 'logged in'
        assert res['headers'][1][0] == 'Set-Cookie'
        assert res['headers'][1][1].startswith('ksid=')
        sid = res['headers'][1][1][5:]

        res = get(app, '/test')
        assert res['status'] == '200 OK'
        assert res['body'] == 'not logged in'

        res = get(app, '/test', cookies={"ksid": sid})
        assert res['status'] == '200 OK'
        assert res['body'] == 'userid: 123'

        res = post(app, '/logout', cookies={"ksid": sid})
        assert res['status'] == '200 OK'
        assert res['body'] == 'logged out'

        res = get(app, '/test', cookies={"ksid": sid})
        assert res['status'] == '200 OK'
        assert res['body'] == 'not logged in'
コード例 #9
0
ファイル: adafruit.py プロジェクト: stynon/mandrakeMadness
def sendDataWifi(data):
    body = {'value': str(data)}
    headers = {'X-AIO-Key': aio_key, 'Content-Type': 'application/json'}
    try:
        r = request.post(url, json=body, headers=headers)
        print(r.text)
        time.sleep(5)
    except Exception as e:
        print(e)
コード例 #10
0
ファイル: app.py プロジェクト: honeycombcmu/BackendServer
def run():
    call(['/bin/spark-submit', '/home/honeycomb/SparkTeam/PySpark.py', '/user/honeycomb/sparkteam/input/sample_multiclass_classification_data.txt', '/user/honeycomb/sparkteam/input/sample_multiclass_classification_data_test.txt', '/home/honeycomb/SparkTeam'])
    while not os.path.exists(FILE_PATH):
        time.sleep(1)
    with open(FILE_PATH) as fin:
        str =  fin.read()
    str = str.replace('\n', ',')
    r = request.post(DB_PATH, data=str)
    print(r.status_code, r.reason)
    return '[' +  str[:-1] + ']'
コード例 #11
0
def parse_items(items):
    ret = []
    for item in items.findall(ITEM_TAG):
        parsed = parse_item(item)
        ret.append(parsed)
        data = json.dumps(parsed) 
        r = requests.post("https://localhost:3000/product/", data)
		print r
        r2 = request.post("https://localhost:3000/productPrice/", data)
        print r2
        ret.append(parsed)
コード例 #12
0
def populate(host, port):
    logger = logging.getLogger("Populator")
    for i in range(1, 10):
        for origin in origins:
            for resource in resources:
                uri = '/' + origin + '/' + resource + '/' + str(i)
                content = generate_random_content()
                res = post('http://' + host + ':' + str(port) + uri, content)
                logger.info(
                    "Made POST request with URI %r and content %r - Response %r",
                    uri, content, res.status_code)
コード例 #13
0
def callRequest(method, url, parameters=None, data=None):
    choice = switchMethod(method)
    if choice == 2:
        return str(request.post(url, parameters, data))
    elif choice == 3:
        return str(request.put(url, parameters, data))
    elif choice == 4:
        return str(request.patch(url, parameters, data))
    elif choice == 5:
        return str(request.delete(url, parameters, data))
    else:
        return str(request.get(url, parameters))
コード例 #14
0
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-u',
                        '--url',
                        help='the url',
                        metavar='URL',
                        required=True)
    args = parser.parse_args()

    url = args.url

    res = request.post(url + '/restart', {})
    request.print_response(res)
コード例 #15
0
def Brute_Force(userName, password, URL):
    COOKIES, USER_TOKEN = setSessionCookie(URL)
    post_data = {
        'username': userName,
        'password': password,
        'Login': '******',
        'user_token': USER_TOKEN
    }
    post_request = request.post(URL, data=post_data, cookies=COOKIES)
    if ERROR_STRING not in post:
        print("FOUND")
        print("Username : "******"Password : " + password)
コード例 #16
0
ファイル: tengxunyun.py プロジェクト: mfkiwl/EC100Y-SDK
    def DynamicConnectInfo(self):
        numTime = utime.mktime(utime.localtime())
        nonce = self.rundom()
        msg = "deviceName={}&nonce={}&productId={}&timestamp={}".format(
            self.devicename, nonce, self.productID, numTime)
        hmacInfo = hmacSha1.hmac_sha1(self.ProductSecret, msg)
        base64_msg = base64.b64encode(bytes(hmacInfo, "utf8"))

        data = {
            "deviceName": self.devicename,
            "nonce": nonce,
            "productId": self.productID,
            "timestamp": numTime,
            "signature": base64_msg.decode()
        }

        data_json = ujson.dumps(data)

        response = request.post(self.url, data=data_json)
        res_raw = response.json()

        code = res_raw.get("code")
        if code == 1021:
            print("Device has been activated!")
            if "tx_secret.json" in uos.listdir():
                msg = check_secret(self.devicename)
                if msg:
                    self.devicePsk = msg
                    self.formatConnectInfo()
                    return 0
            else:
                print(
                    "The device is active, but the key file tx_secret.json is missing."
                )
                return -1
        payload = res_raw.get("payload")
        mode = ucryptolib.MODE_CBC
        raw = base64.b64decode(payload)
        key = self.ProductSecret[0:16].encode()
        iv = b"0000000000000000"
        cryptos = ucryptolib.aes(key, mode, iv)
        plain_text = cryptos.decrypt(raw)
        data = plain_text.decode().split("\x00")[0]
        self.devicePsk = ujson.loads(data).get("psk")
        data = {self.devicename: self.devicePsk}
        save_Secret(data)
        self.formatConnectInfo()
コード例 #17
0
ファイル: authentication.py プロジェクト: rajbahl/django
    def authenticate(self, assertion):
        # send assertion to mozzila verifier service.

        data = {'assertion': assertion, 'audience': 'localhost'}
        print('sending to mozilla', data, file=sys.stderr)
        resp = request.post('https://verifier.login.persona.org/verify', data=data)
        print('got', resp.content, file=sys.stderr)

        # Did the verifier respond ?
        if resp.ok:
            verification_data = resp.json()
            #check if assertion is valid
            if verification_data['status'] == 'okay':
                email = verification_data['email']
                try:
                    return self.get_user(email)
                except ListUser.DoesNotExist:
                    return ListUser.objects.create(email=email)
コード例 #18
0
    def create_playlist(self, name, description, public):
        request_body = json.dumps({
            'name': name,
            'description': description,
            'public': public
        })

        query 'https://api.spotify.com/v1/users/{}/playlist'.format(self.user_id)
        response = request.post(
            query,
            data=request_body,
            headers={
                'Content-Type': 'application/json',
                'Authorization': 'Bearer {}'.format(self.spotify_token)
            }
        )
        response_json = response.json()

        return response_json['id']
コード例 #19
0
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-u',
                        '--url',
                        help='the url',
                        metavar='URL',
                        required=True)
    parser.add_argument('-p',
                        '--pid',
                        help='the PID',
                        metavar='PID',
                        required=True,
                        type=int)
    args = parser.parse_args()

    url = args.url
    pid = args.pid

    res = request.post(url + '/killprocess', {'pid': pid})
    request.print_response(res)
コード例 #20
0
def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', help='the url', metavar='URL', required=True)
    parser.add_argument('-i', '--serverid', help='the server id', metavar='ID', required=True)
    parser.add_argument('-s', '--settings', help='additional server settings (colon separated)', metavar='SETTINGS', required=False)
    args = parser.parse_args()

    url = args.url
    serverId = args.serverid
    settings = args.settings

    args = {
        'serverId': serverId
    }

    if settings is not None:
        args['settings'] = settings

    res = request.post(url + '/runparsec', args)
    request.print_response(res)
コード例 #21
0
ファイル: test_app.py プロジェクト: zweifisch/klar
    def test_routing(self):
        app = App()

        @app.get('/')
        def index():
            return 'index'

        @app.get('/foo')
        def foo():
            return 'foo'

        @app.route('/bar', methods=['get', 'post', 'put'])
        def bar(req):
            return '%s: %s' % (req.method, req.path)

        assert get(app, '/')['body'] == 'index'
        assert get(app, '/foo')['body'] == 'foo'
        assert get(app, '/baz')['status'].startswith('404')
        assert get(app, '/bar')['body'] == 'GET: /bar'
        assert post(app, '/bar')['body'] == 'POST: /bar'
コード例 #22
0
    def login(self, user):
        # check if the credentials has been changed in config.json
        if (user.username == '' or user.password == ''):
            return False

        # receive data until he receive challstr
        challstr = ''
        while challstr == '':
            self.receiveData()
            for c in self.commandQueue:
                if (c['c'] == 'challstr'):
                    challstr = c['a'][0] + '|' + c['a'][1]

        print('challstr: ' + challstr)

        # request data from authserver to get assertion
        data = {
            'act': 'login',
            'name': user.username,
            'pass': user.password,
            'challstr': challstr
        }
        r = request.post(self.config['actionServer'], data)
        response = json.loads(r.text[1:])
コード例 #23
0
ファイル: login.py プロジェクト: xiaohao0000001/gluon
import request
data = {'name':'123123', 'pass':'******'}
request.post('10.10.10.29', data)
コード例 #24
0
def add_data(summary, description=""):
    return request.post(_url('/data/{:d}.')),json={
    'summary'=summary,
    'description'=description
    })
コード例 #25
0
import request

url = 'http://localhost:5000/results'
r = request.post(url,
                 json={
                     'ApplicantIncome': 4000,
                     'CoaplicantIncome': 2000,
                     'LoanAmount': 600,
                     'Loan_Amount_Term': 360,
                     'Credit_History': 1,
                     'Self_Employed': 1,
                     'Property_Area': 1,
                     'Married': 1,
                     'Education': 0,
                     'Gender': 1
                 })

print(r.json())
コード例 #26
0
'''
PROJECT_NAME = "QuecPython_Requect_post_example"
PROJECT_VERSION = "1.0.0"

checknet = checkNet.CheckNetwork(PROJECT_NAME, PROJECT_VERSION)

# 设置日志输出级别
log.basicConfig(level=log.INFO)
http_log = log.getLogger("HTTP POST")

url = "http://httpbin.org/post"
data = {"key1": "value1", "key2": "value2", "key3": "value3"}

if __name__ == '__main__':
    '''
    手动运行本例程时,可以去掉该延时,如果将例程文件名改为main.py,希望开机自动运行时,需要加上该延时,
    否则无法从CDC口看到下面的 poweron_print_once() 中打印的信息
    '''
    utime.sleep(5)
    checknet.poweron_print_once()
    '''
    如果用户程序包含网络相关代码,必须执行 wait_network_connected() 等待网络就绪(拨号成功);
    如果是网络无关代码,可以屏蔽 wait_network_connected()
    【本例程必须保留下面这一行!】
    '''
    checknet.wait_network_connected()

    # POST请求
    response = request.post(url, data=ujson.dumps(data))  # 发送HTTP POST请求
    http_log.info(response.json())
コード例 #27
0
def lambda_handler(event, context):

    url = 'ec2-54-167-213-131.compute-1.amazonaws.com'
    response = request.post(url)

    return {'statusCode': 200, 'body': json.dumps('Hello from Lambda!')}
コード例 #28
0
import request

url = 'http://127.0.0.1:5000/classify_api'
r = request.post(url, json={'hi': True, 'i': True, 'am': True, 'happy': True})

print(r.json)
コード例 #29
0
ファイル: scan.py プロジェクト: JasperStam/nfc-timetracking
def tag_connected(tag):
    print('Connected: ' + tag)
    request.post(tag, True)
コード例 #30
0
def newUser():
    r = request.post(base_url + 'users/', json.JSONEncoder().encode(bottle.request.json), auth = ('cse3213', 'test'))
    bottle.response.status = r.status_code

    return r.json
コード例 #31
0
def updateUser(id):
    r = request.post(base_url + 'users/' + str(id), bottle.request.json, auth = ('cse3213', 'test'))
    bottle.response.status = r.status_code

    return r.json
コード例 #32
0
def switchWeapon(amount):
    if post("/api/player/actions", {'type': 'switch-weapon','amount': amount}) != 201:
        raise ValueError('Switch weapon command was not executed')
コード例 #33
0
def forward(amount):
    if post("/api/player/actions", {'type': 'forward','amount': amount}) != 201:
        raise ValueError('Forward command was not executed')
コード例 #34
0
def pull_report(
    identity_type, 
    identity_number, 
    report_type=IDENTITY, 
    report_reason=NEW_CREDIT, 
    user=None, 
    loan_amount=None
):
    headers = {
        "Content-Type": "application/json",
        "X-METROPOL-REST-API-KEY": "DKKEIE3CKGPAIRJVN495JFJAJ",
        "X-METROPOL-REST-API-TIMESTAMP": "20140708175839987843",
        "X-METROPOL-REST-API-HASH": "6b4412c63b19cd86e9939c43d115x961ef4357698da42f984287e6d0029c5671",
    }

    with db_transaction.atomic():
        data = {
            "report_type": IDENTITY,
            "identity_type": identity_type,
            "identity_number": identity_number, 
        }
        
        if not MetropolRiskProfile.objects.filter(
            identity_type=identity_type,
            identity_number=identity_number
        ).exists():
            m_risk_profile = MetropolRiskProfile.objects.create(
                identity_type=identity_type,
                identity_number=identity_number
                loan_profile=loan_profile,
                created_at=timezone.now(),
                created_by=user,
            )
        else:
            m_risk_profile = MetropolRiskProfile.objects.get(
                identity_type=identity_type,
                identity_number=identity_number
            )

        REPORT_TYPE_ENDPOINT = ENDPOINTS.get(report_type)

        m_risk_profile.save()

        if report_type == IDENTITY:
            data["loan_amount"] = loan_amount
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()

            m_risk_profile.first_name = json['first_name']
            m_risk_profile.other_name = json['other_name']
            m_risk_profile.last_name = json['last_name']
            
            m_risk_profile.gender = json['gender']
            m_risk_profile.dob = json['dob']
            m_risk_profile.dod = json['dod']
            
            m_risk_profile.is_verified = True

        elif report_type == DELINQUENCY_STATUS:
            data["loan_amount"] = loan_amount
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()

            m_risk_profile.delinquency_status = json['delinquency_code']

        elif report_type == REPORT_PDF:
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()
            
            m_risk_profile.credit_score = json['credit_score']

        elif report_type == REPORT_JSON:
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()
            
            m_risk_profile.delinquency_status = json['delinquency_code']

        elif report_type == SCORE_CONSUMER:
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()
            
            m_risk_profile.delinquency_status = json['credit_score']

        elif report_type == IDENTITY_SCRUB:
            json = request.post(REPORT_TYPE_ENDPOINT, headers=headers, data=data).json()

            for name in json['names']:
                r_name = RiskProfileName.objects.create(
                    risk_profile=m_risk_profile,
                    name=name
                )

            for phone in json['phone']:
                r_phone = RiskProfilePhone.objects.create(
                    risk_profile=m_risk_profile,
                    phone=phone
                )

            for email in json['email']:
                r_email = RiskProfileEmail.objects.create(
                    risk_profile=m_risk_profile,
                    email=email
                )

            for postal_address in json['postal_address']:
                r_postal_address = RiskProfilePhysicalAddress.objects.create(
                    risk_profile=m_risk_profile,
                    town=postal_address['town']
                    address=postal_address['address']
                    country=postal_address['country']
                )

            for physical_address in json['physical_address']:
                r_physical_address = RiskProfilePostalAddress.objects.create(
                    risk_profile=m_risk_profile,
                    town=physical_address['town'],
                    code=physical_address['code'],
                    number=physical_address['number'],
                    country=physical_address['country'],
                )

            for employment in json['employment']:
                r_employment = RiskProfileEmployment.objects.create(
                    risk_profile=m_risk_profile,
                    employer_name=employment['employer_name'],
                    employment_date=employment['employment_date'],
                )

            m_risk_profile.delinquency_status = json['delinquency_code']

        metropol_report = MetropolReport.objects.create(
            transaction_id=json['trx_id'],
            has_error=json['has_error'],
            api_ref_code=json['api_code'],
            api_ref_code_description=json['api_code_description'],
            identity_type=identity_type,
            identity_number=identity_number,
            report_type=report_type,
            loan_amount=json.get('loan_amount', D('0')),
            report_reason=report_reason,
        )

        m_risk_profile.identity_type = json['identity_type']
        m_risk_profile.identity_number = json['identity_number']

        m_risk_profile.last_report = metropol_report
        m_risk_profile.last_report_date = timezone.now()
        m_risk_profile.save()

        return metropol_report
コード例 #35
0
ファイル: Request.py プロジェクト: fanlishen/test
    def post_request_multipart(self, url, data, header, file_parm, file,
                               f_type):
        """
        提交Multipart/form-data 格式的post请求
        :param url:
        :param data:
        :param header:
        :param file_parm:
        :param file:
        :param f_type:
        :return:
        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)
            print(url)

        try:
            if data is None:
                response = request.post(url=url,
                                        header=header,
                                        cookies=self.get_session)

            else:
                data[file_parm] = os.path.basename(file), open(file,
                                                               'rb'), f_type

                enc = MultipartEncoder(fields=data,
                                       boundary='--------' +
                                       str(random.randint(1e28, 1e29 - 1)))

                header['Content-Type'] = enc.content_type
                response = request.post(url=url,
                                        params=data,
                                        header=header,
                                        cookies=self.get_session)

        except request.RequestException as e:
            print('%s%s' % ('RequestException url:', url))
            print(e)
            return ()

        except Exception as e:
            print('%s%s' % ('Exception url:', url))
            print(e)
            return ()

        #time_consuming为响应时间,单位为毫秒
        time_consuming = response.elapsed.microseconds / 1000
        #time_total为响应时间,单位为毫秒
        time_total = response.elapsed.total_seconds()

        Common.Consts.STRESS_LIST.append(time_consuming)

        response_dicts = dict()
        response_dicts['code'] = response.status_code
        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            print(e)
            response_dicts['body'] = ''

        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total

        return response_dicts
コード例 #36
0
diffCounter = 0

while (True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    grayNow = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # if (firstTime == 1):
    #     grayPrev = grayNow
    #     firstTime = 0
    # (score, diff) = compare_ssim(grayNow, grayPrev, full=True)
    # diff = (diff * 255).astype("uint8")
    # if score < 0.8:
    #     print('DIFFERENT! {}'.format(diffCounter))
    #     diffCounter = diffCounter + 1
    # print("SSIM: {}".format(diff))

    # Display the resulting frame
    cv2.imshow('frame', frame)
    cv2.imwrite('frame.jpg', frame)
    request.post("http://localhost:8000/")
    time.sleep(1)
    # grayPrev = grayNow
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
コード例 #37
0
def shoot(amount):
    if post("/api/player/actions", {'type': 'shoot','amount': amount}) != 201:
        raise ValueError('Shoot command was not executed')
コード例 #38
0
ファイル: scan.py プロジェクト: JasperStam/nfc-timetracking
def tag_released(tag):
    print('Released: ' + tag)
    request.post(tag, False)
コード例 #39
0
def deleteUser(id):
    r = request.post(base_url + 'users/destroy/' + str(id), json.JSONEncoder().encode(bottle.request.json), auth = ('cse3213', 'test'))
    bottle.response.status = r.status_code

    return r.json
コード例 #40
0
ファイル: api.py プロジェクト: shoudusse/Pasteque-installer
#!/usr/bin/env python

import request

request.post('http://pasteque.escale-biere.com', data={location: 0, reason: 1, date: '07/06/2016', qty-a69548391fcc6cb6603b2a580e43ffd7: 27})
コード例 #41
0
def strafeRight(amount):
    if post("/api/player/actions", {'type': 'strafe-right','amount': amount}) != 201:
        raise ValueError('Strafe right command was not executed')