最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python輪詢(xún)機(jī)制控制led實(shí)例

 更新時(shí)間:2020年05月03日 15:06:42   作者:Neil-Yale  
這篇文章主要介紹了python輪詢(xún)機(jī)制控制led實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

我就廢話(huà)不多說(shuō)了,大家還是直接看代碼吧!

# -*- coding:utf-8 -*- 
# File: ceshitianqi
 
import urllib2
import json
import time
import datetime
import serial 
import random
import os
import sys
 
APIKEY = 'ZPdLyl***=' #改成你的APIKEY
ser=serial.Serial("/dev/ttyUSB2",9600,timeout=1)
 
def read(key):
  ser.write(key)
  print("output:"+key)
  time.sleep(1)
  response = ser.readall()
  print(response)
  print(type(response))
  return response
 
def http_put(key):
  val = read(key) #獲取Arduino的數(shù)據(jù)
  CurTime = datetime.datetime.now()
  url='http://api.heclouds.com/devices/**1/datapoints'
  #values={'datastreams':[{"id":"temp","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
  print(type(val))
  if key== "a" :
   values={'datastreams':[{"id":"humidity","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
  if key== "b" :
   values={'datastreams':[{"id":"temperature","datapoints":[{"at":CurTime.isoformat(),"value":val}]}]}
  jdata = json.dumps(values)         # 對(duì)數(shù)據(jù)進(jìn)行JSON格式化編碼
  #打印json內(nèi)容
  print jdata
  request = urllib2.Request(url, jdata)
  request.add_header('api-key', APIKEY)
  request.get_method = lambda:'POST'     # 設(shè)置HTTP的訪問(wèn)方式
  request = urllib2.urlopen(request)
  return request.read()  
 
str = ("a","b")
while True:
	for i in str: 
		f = open('1.txt')
		e = f.read()
		if e == "1\n":
			ser.write("c")
		if e == "0\n":
			ser.write("d")
 
		f.close()  
		resp = http_put(i)
   		time.sleep(2)

輪詢(xún)1.txt

1則點(diǎn)亮

0則關(guān)閉

補(bǔ)充知識(shí):python筆記(輪詢(xún)、長(zhǎng)輪詢(xún))

一、輪詢(xún)

views.py

from flask import Flask,render_template,request,jsonify

app = Flask(__name__)

USERS = {
  '1':{'name':'貝貝','count':1},
  '2':{'name':'小東北','count':0},
  '3':{'name':'何偉明','count':0},
}

@app.route('/user/list')
def user_list():
  import time
  return render_template('user_list.html',users=USERS)

@app.route('/vote',methods=['POST'])
def vote():
  uid = request.form.get('uid')
  USERS[uid]['count'] += 1
  return "投票成功"

@app.route('/get/vote',methods=['GET'])
def get_vote():

  return jsonify(USERS)


if __name__ == '__main__':
  app.run(threaded=True)

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    li{
      cursor: pointer;
    }
  </style>
</head>
<body>
  <ul id="userList">
    {% for key,val in users.items() %}
      <li uid="{{key}}">{{val.name}} ({{val.count}})</li>
    {% endfor %}
  </ul>

  <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
  <script>

    $(function () {
      $('#userList').on('dblclick','li',function () {
        var uid = $(this).attr('uid');
        $.ajax({
          url:'/vote',
          type:'POST',
          data:{uid:uid},
          success:function (arg) {
            console.log(arg);
          }
        })
      });

    });


    /*
    獲取投票信息
     */
    function get_vote() {
      $.ajax({
        url:'/get/vote',
        type:"GET",
        dataType:'JSON',
        success:function (arg) {
          $('#userList').empty();
          $.each(arg,function (k,v) {
            var li = document.createElement('li');
            li.setAttribute('uid',k);
            li.innerText = v.name + "(" + v.count + ')' ;
            $('#userList').append(li);
          })

        }
      })
    }


    setInterval(get_vote,3000);

  </script>
</body>
</html>

二、長(zhǎng)輪詢(xún)

views.py

from flask import Flask,render_template,request,jsonify,session
import uuid
import queue

app = Flask(__name__)
app.secret_key = 'asdfasdfasd'


USERS = {
  '1':{'name':'貝貝','count':1},
  '2':{'name':'小東北','count':0},
  '3':{'name':'何偉明','count':0},
}

QUEQUE_DICT = {
}

@app.route('/user/list')
def user_list():
  user_uuid = str(uuid.uuid4())
  QUEQUE_DICT[user_uuid] = queue.Queue()

  session['current_user_uuid'] = user_uuid
  return render_template('user_list.html',users=USERS)

@app.route('/vote',methods=['POST'])
def vote():
  uid = request.form.get('uid')
  USERS[uid]['count'] += 1
  for q in QUEQUE_DICT.values():
    q.put(USERS)
  return "投票成功"


@app.route('/get/vote',methods=['GET'])
def get_vote():
  user_uuid = session['current_user_uuid']
  q = QUEQUE_DICT[user_uuid]

  ret = {'status':True,'data':None}
  try:
    users = q.get(timeout=5)
    ret['data'] = users
  except queue.Empty:
    ret['status'] = False

  return jsonify(ret)



if __name__ == '__main__':
  app.run(threaded=True)

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    li{
      cursor: pointer;
    }
  </style>
</head>
<body>
  <ul id="userList">
    {% for key,val in users.items() %}
      <li uid="{{key}}">{{val.name}} ({{val.count}})</li>
    {% endfor %}
  </ul>

  <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
  <script>

    $(function () {
      $('#userList').on('click','li',function () {
        var uid = $(this).attr('uid');
        $.ajax({
          url:'/vote',
          type:'POST',
          data:{uid:uid},
          success:function (arg) {
            console.log(arg);
          }
        })
      });
      get_vote();
    });

    /*
    獲取投票信息
     */
    function get_vote() {
      $.ajax({
        url:'/get/vote',
        type:"GET",
        dataType:'JSON',
        success:function (arg) {
          if(arg.status){
            $('#userList').empty();
              $.each(arg.data,function (k,v) {
                var li = document.createElement('li');
                li.setAttribute('uid',k);
                li.innerText = v.name + "(" + v.count + ')' ;
                $('#userList').append(li);
              })
          }
          get_vote();

        }
      })
    }

  </script>
</body>
</html>

以上這篇python輪詢(xún)機(jī)制控制led實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 用virtualenv建立多個(gè)Python獨(dú)立虛擬開(kāi)發(fā)環(huán)境

    用virtualenv建立多個(gè)Python獨(dú)立虛擬開(kāi)發(fā)環(huán)境

    這篇文章主要為大家詳細(xì)介紹了用virtualenv建立多個(gè)Python獨(dú)立虛擬開(kāi)發(fā)環(huán)境,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • Python列表去重的幾種方法整理

    Python列表去重的幾種方法整理

    這篇文章介紹了Python列表去重的幾種方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • Python實(shí)現(xiàn)二分查找與bisect模塊詳解

    Python實(shí)現(xiàn)二分查找與bisect模塊詳解

    二分查找又叫折半查找,二分查找應(yīng)該屬于減治技術(shù)的成功應(yīng)用。python標(biāo)準(zhǔn)庫(kù)中還有一個(gè)灰常給力的模塊,那就是bisect。這個(gè)庫(kù)接受有序的序列,內(nèi)部實(shí)現(xiàn)就是二分。下面這篇文章就詳細(xì)介紹了Python如何實(shí)現(xiàn)二分查找與bisect模塊,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-01-01
  • Python 實(shí)現(xiàn)交換矩陣的行示例

    Python 實(shí)現(xiàn)交換矩陣的行示例

    今天小編就為大家分享一篇Python 實(shí)現(xiàn)交換矩陣的行示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-06-06
  • Ubuntu16.04/樹(shù)莓派Python3+opencv配置教程(分享)

    Ubuntu16.04/樹(shù)莓派Python3+opencv配置教程(分享)

    下面小編就為大家分享一篇Ubuntu16.04/樹(shù)莓派Python3+opencv配置教程。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • Python配置mysql的教程(推薦)

    Python配置mysql的教程(推薦)

    下面小編就為大家?guī)?lái)一篇Python配置mysql的教程(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-10-10
  • Python序列化與反序列化相關(guān)知識(shí)總結(jié)

    Python序列化與反序列化相關(guān)知識(shí)總結(jié)

    今天給大家?guī)?lái)關(guān)于python的相關(guān)知識(shí),文章圍繞著Python序列化與反序列展開(kāi),文中有非常詳細(xì)的介紹,需要的朋友可以參考下
    2021-06-06
  • Python實(shí)現(xiàn)賬號(hào)密碼輸錯(cuò)三次即鎖定功能簡(jiǎn)單示例

    Python實(shí)現(xiàn)賬號(hào)密碼輸錯(cuò)三次即鎖定功能簡(jiǎn)單示例

    這篇文章主要介紹了Python實(shí)現(xiàn)賬號(hào)密碼輸錯(cuò)三次即鎖定功能,結(jié)合實(shí)例形式分析了Python文件讀取、流程控制、數(shù)據(jù)判斷等相關(guān)操作技巧,需要的朋友可以參考下
    2019-03-03
  • Python中str.format()詳解

    Python中str.format()詳解

    本文主要給大家詳細(xì)介紹的是python編程中str.format()的基本語(yǔ)法和高級(jí)用法,非常的詳細(xì),并附有示例,希望大家能夠喜歡
    2017-03-03
  • 解決python中導(dǎo)入win32com.client出錯(cuò)的問(wèn)題

    解決python中導(dǎo)入win32com.client出錯(cuò)的問(wèn)題

    今天小編就為大家分享一篇解決python中導(dǎo)入win32com.client出錯(cuò)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-07-07

最新評(píng)論

夏河县| 阿拉善左旗| 镇平县| 泸定县| 汪清县| 通州市| 温州市| 上虞市| 莲花县| 通城县| 闽侯县| 洪泽县| 门源| 清河县| 昌江| 勐海县| 遂溪县| 鄄城县| 石楼县| 台东市| 宜宾县| 滨州市| 额尔古纳市| 鸡西市| 呼图壁县| 资中县| 鱼台县| 苏尼特左旗| 吉木萨尔县| 阿拉善右旗| 南郑县| 全椒县| 合江县| 大同市| 西峡县| 荔波县| 呼和浩特市| 杂多县| 霍林郭勒市| 蒙山县| 雷波县|