예제 #1
0
파일: suikang.py 프로젝트: yue-litam/masks
def comfire_order(cat=0):
    data = comfirm_order_data.copy()
    if cat == 1:
        data['category'] = '普通N95口罩'
        data['commodity_id'] = '100005'
        data['number'] = 5
    elif cat == 2:
        data['category'] = '普通防护口罩'
        data['commodity_id'] = '100006'
        data['number'] = 10
    else:
        logger.warning('unknown mask category.')
        return False
    jstr = json.dumps(data, ensure_ascii=False)
    byte = jstr.encode('utf-8')
    response = post(URI_CONFIRM_ORDER,
                    data=byte,
                    headers=header,
                    timeout=config.ORDER_TIMEOUT_SECONDS)
    result = check_success_or_not(response)
    if result is not None:
        status = result['data']['status']
        if status == 'success':
            logger.info('预约成功!')
            return True
        else:
            logger.warn('unknown status: ' + status)
    return False
예제 #2
0
def runBehavior():
    global __current_behavior__, __send_readings__

    bhr = __current_behavior__
    readings = __readings__

    if bhr["lightAuto"]:
        current_hour = datetime.now().hour
        if bhr["lightStartHour"] <= current_hour and bhr["lightStopHour"] > current_hour:
            sys_gpio.setRelay(sys_gpio.__light_pin__, True)
            route = api.__toggle_light__(node.node_info['id'], True)
            httpclient.post(path=route, forbiddenErrorCallback=auth.checkResponse)
            #print "Ligth On"
        else:
            sys_gpio.setRelay(sys_gpio.__light_pin__, False)
            route = api.__toggle_light__(node.node_info['id'], False)
            httpclient.post(path=route, forbiddenErrorCallback=auth.checkResponse)
예제 #3
0
def dc_post(data):
    json = {
        "stream_id": stream_id,
        "stream_type": stream_type,
        "value": str(data)
    }
    r = httpclient.post(url, headers=headers, json=json)
    r.close()
    return r.status_code
예제 #4
0
 def notify_verify(self, request):
     params = {}
     params['is_success'] = request.get_argument('is_success', '')
     params['partnerId'] = request.get_argument('partnerId', '')
     params['notify_id'] = request.get_argument('notify_id', '')
     params['notify_type'] = request.get_argument('notify_type', '')
     params['notify_time'] = request.get_argument('notify_time', '')
     params['sign'] = request.get_argument('sign', '')
     params['sign_type'] = request.get_argument('sign_type', '')
     params['trade_no'] = request.get_argument('trade_no', '')
     params['subject'] = request.get_argument('subject', '')
     params['price'] = request.get_argument('price', '')
     params['quantity'] = request.get_argument('quantity', '')
     params['seller_email'] = request.get_argument('seller_email', '')
     params['seller_id'] = request.get_argument('seller_id', '')
     params['buyer_email'] = request.get_argument('buyer_email', '')
     params['buyer_id'] = request.get_argument('buyer_id', '')
     params['discount'] = request.get_argument('discount', '')
     params['total_fee'] = request.get_argument('total_fee', '')
     params['trade_status'] = request.get_argument('trade_status', '')
     params['is_total_fee_adjust'] = request.get_argument('is_total_fee_adjust', '')
     params['use_coupon'] = request.get_argument('use_coupon', '')
     params['body'] = request.get_argument('body', '')
     params['exterface'] = request.get_argument('exterface', '')
     params['out_trade_no'] = request.get_argument('out_trade_no', '')
     params['payment_type'] = request.get_argument('payment_type', '')
     params['logistics_type'] = request.get_argument('logistics_type', '')
     params['logistics_fee'] = request.get_argument('logistics_fee', '')
     params['logistics_payment'] = request.get_argument('logistics_payment', '')
     params['gmt_logistics_modify'] = request.get_argument('gmt_logistics_modify', '')
     params['buyer_actions'] = request.get_argument('buyer_actions', '')
     params['seller_actions'] = request.get_argument('seller_actions', '')
     params['gmt_create'] = request.get_argument('gmt_create', '')
     params['gmt_payment'] = request.get_argument('gmt_payment', '')
     params['refund_status'] = request.get_argument('refund_status', '')
     params['gmt_refund'] = request.get_argument('gmt_refund', '')
     params['receive_name'] = request.get_argument('receive_name', '')
     params['receive_address'] = request.get_argument('receive_address', '')
     params['receive_zip'] = request.get_argument('receive_zip', '')
     params['receive_phone'] = request.get_argument('receive_phone', '')
     params['receive_mobile'] = request.get_argument('receive_mobile', '')
     if not self.check_sign(request.get_argument('sign', '')):
         defer.returnValue(False)
     params = {}
     params['partner'] = self.settings.ALIPAY_PARTNER
     params['notify_id'] = request.get_argument('notify_id', '')
     if self.settings.ALIPAY_TRANSPORT == 'https':
         params['service'] = 'notify_verify'
         gateway = 'https://mapi.alipay.com/gateway.do'
     else:
         gateway = 'http://notify.alipay.com/trade/notify_query.do'
     resp = yield requests.post(gateway, data=urlencode(params))
     veryfy_result = yield resp.content()
     defer.returnValue(veryfy_result.lower().strip() == 'true')
예제 #5
0
def runBehavior():
    global __current_behavior__, __send_readings__

    bhr = __current_behavior__
    readings = __readings__

    if bhr["lightAuto"]:
        current_hour = datetime.now().hour
        if bhr["lightStartHour"] <= current_hour and bhr[
                "lightStopHour"] > current_hour:
            sys_gpio.setRelay(sys_gpio.__light_pin__, True)
            route = api.__toggle_light__(node.node_info['id'], True)
            httpclient.post(path=route,
                            forbiddenErrorCallback=auth.checkResponse)
            #print "Ligth On"
        else:
            sys_gpio.setRelay(sys_gpio.__light_pin__, False)
            route = api.__toggle_light__(node.node_info['id'], False)
            httpclient.post(path=route,
                            forbiddenErrorCallback=auth.checkResponse)
예제 #6
0
def authenticate():
    global __auth_data__, __user_id__

    if __auth_data__ is None:
        __auth_data__ = getUserAndPass()

    response = httpclient.post(api.__authenticate__, __auth_data__)
    if response.status == 200:
        usr = json.loads(response.body)
        api.AUTH_TOKEN = usr['token']
        __user_id__ =  usr['id']
    return response
예제 #7
0
def getTranslation(q, appKey, fromText='auto', toText='auto'):
    params = getParams(q, appKey, fromText, toText)
    response = httpclient.post(url, params)
    items = list()
    if response.status == 200:
        items = getItemList(response.read())
    else:
        items.append(getItem('网络不给力,一会再试吧', ''))
    if len(items) == 0:
        items.append(getEmptyItem())

    jsonBean = {}
    jsonBean['items'] = filter(lambda x: x is not None, items)
    return json.dumps(jsonBean)
예제 #8
0
def sendReadings(nextRun):

    if datetime.now() >= nextRun:

        #turn on the sensors
        # the transisotr enable the sensors to be powered
        sys_gpio.setTransistor(True)

        log.current_state = "Reading Air Temperature"
        air_temp = DHT11TemperatureSensor.read()
        log.current_state = "Posting Air Temperature"
        httpclient.post(api.__send_readings__, air_temp, auth.checkResponse)
        scn.update(env_temp=str(air_temp['reading']))

        log.current_state = "Reading Air Humidity"
        air_hum = DHT11HumiditySensor.read()
        log.current_state = "Posting Air Humidity"
        httpclient.post(api.__send_readings__, air_hum, auth.checkResponse)
        scn.update(env_hum=str(air_hum['reading']))

        log.current_state = "Reading Luminosity"
        air_lum = LDR.read()
        log.current_state = "Posting Luminosity"
        httpclient.post(api.__send_readings__, air_lum, auth.checkResponse)
        scn.update(env_lum="{0:0.2f}".format(air_lum['reading']))

        log.current_state = "Reading Soil Temperature"
        soil_temp = DS18B20TemperatureSensor.read()
        log.current_state = "Reading Soil Temperature"
        httpclient.post(api.__send_readings__, soil_temp, auth.checkResponse)
        scn.update(soil_temp="{0:0.2f}".format(soil_temp['reading']))

        sys_gpio.setTransistor(False)

        #print air_lum["date"]
        #print "Env: Temp.: {0:0.2f}C  Humidity: {1:0.2f}%  &  Luminosity:{2:0.2f}%".format(air_temp['reading'], air_hum['reading'], air_lum['reading'])
        #print "Soil: Temp.: {0:0.2f}C  &  Moisture: 0%".format(soil_temp['reading'])
        #print "\n"
        log.log_info("System Ok")

        nextRun = datetime.now() + timedelta(seconds=60)

    return nextRun
예제 #9
0
파일: suikang.py 프로젝트: yue-litam/masks
def check_status():
    data = {"city_id": 20}
    response = post(URI_STATUS_CHECK,
                    data=json.dumps(data),
                    headers=header,
                    timeout=config.CEHCK_STATUS_TIMEOUT_SECONDS)
    result = check_success_or_not(response)
    if result is not None:
        status = result['data']['status']
        if status == 'preorder':
            return True
        elif status == 'finish':
            yesterday = datetime.date.today() + datetime.timedelta(days=-1)
            yesterday_str = str(yesterday.year) + str(yesterday.month) + str(
                yesterday.day)
            logger.info('本轮预约未开始。上一轮(' + yesterday_str + ')预约已结束。')
        elif status == 'wait':
            logger.info('本轮预约未开始。')
        else:
            exit(1)
    return False
예제 #10
0
        q_dist[_k] = q.get(_k)[0]

q_dist['appId'] = appid
q_dist['idfa'] = payload['idfa']
q_dist['ipv4'] = payload['ipv4']

qs_dist = urlencode(q_dist)

u_dist = (u.scheme, u.netloc, u.path, '', qs_dist, '')

url = urlunparse(u_dist)

print('request to: %s' % url)

from httpclient import get, post

resp = get('http://127.0.0.1:4567/')
logging.debug(resp.code)
logging.debug(resp.message)
logging.debug(resp.body)

resp = post('http://127.0.0.1:4567/post', data={'a': 1, 'b': 2})
logging.debug(resp.code)
logging.debug(resp.message)
logging.debug(resp.body)

resp = post('http://127.0.0.1:4567/post', data=open('/tmp/a', 'rb'))
logging.debug(resp.code)
logging.debug(resp.message)
logging.debug(resp.body)
예제 #11
0
    try:
        new_node = False;
        while True:
            user_input = raw_input("Is this a new node[y/N]?")
            if user_input is "":
                user_input = "n"
            user_input = user_input.lower()
            if user_input == "y" or user_input == "n":
                if user_input == "y":
                    new_node = True
                else:
                    new_node = False
                break

        log.current_state = "Ready to do the handshake"
        response = httpclient.post(api.__handshake__, node.get(new_node, auth.__user_id__), auth.checkResponse)
        print response.status, response.reason
        if response.status == 200:
            #print response.body
            body = json.loads(response.body)
            node.update(body)

            log.current_state = "Handshake succeeded"
            print "handshake succeeded"
    except:
        error_msg = "handshake fail"
        e = sys.exc_info()[0]
        print error_msg
        error_msg = "\n" + error_msg + "\n" + str(e)
        log.log_error(error_msg)
예제 #12
0
def request(apiurl, data=None, **kwargs):
    headers = {'Content-Type': ['application/json']}
    return httpclient.post(apiurl, data=data, **kwargs)