コード例 #1
0
 async def stop_async(self, timeout=5, stop_event_loop=True):
     try:
         await self._stop_async(timeout=timeout)
     except Exception:
         self.log.error("Error while shutting down:", exc_info=True)
     # Stop the event loop
     if stop_event_loop:
         IOLoop.current().stop()
コード例 #2
0
    def __check_build_refs__(self):
        if self.refs > 0:
            return

        if self.build_id:
            logging.info("Build {0} is being released because no usages left.".format(self.build_id))

        self._remove_timeout = None
        IOLoop.current().add_callback(self.release)
コード例 #3
0
 def start(self):
     if self.subapp is not None:
         return self.subapp.start()
     AsyncIOMainLoop().install()
     loop = IOLoop.current()
     loop.add_callback(self.start_or_exit)
     try:
         loop.start()
     except KeyboardInterrupt:
         print("\nInterrupted")
コード例 #4
0
def upload_attribute_data():
    """
    data format like flow.
    {"attribute1":"value1",
     "attribute2":true, "attribute3":42.0, "attribute4":73}
    """
    gen_log.info("upload_attribute_data")
    try:
        data = {"firmware_version": "1.0.1", "serial_number": "SN-001"}
        url = url_prefix + '/v1/{}/attributes'.format(token)
        res = yield AsyncHTTPClient().fetch(url,
                                            method='POST',
                                            body=json.dumps(data),
                                            headers=headers)
        #res=requests.post(url,data=json.dumps(data),headers=headers)
        gen_log.info(res.body)
    except Exception as ex:
        gen_log.error(ex)

    IOLoop.current().add_timeout(time.time() + 1, upload_attribute_data)
コード例 #5
0
def upload_temperature_data():
    """
    curl -v -X POST -d "{\"temperature\": 25}"
     $HOST_NAME/api/v1/$ACCESS_TOKEN/telemetry 
     --header "Content-Type:application/json"

    """
    gen_log.info("upload_temperature_data")
    try:

        data = {"temperature": random.randint(20, 100)}
        url = url_prefix + '/v1/{}/telemetry'.format(token)
        res = yield AsyncHTTPClient().fetch(url,
                                            method='POST',
                                            body=json.dumps(data),
                                            headers=headers)
        #res=requests.post(url,data=json.dumps(data),headers=headers)
        gen_log.info(res.code)
    except Exception as ex:
        gen_log.error(ex)
    IOLoop.current().add_timeout(time.time() + 1, upload_temperature_data)
コード例 #6
0
def make_app():
    parse_command_line()

    gen_log.info('upload path:{0}'.format(UPLOAD_DIR))
    #db = motor_tornado.MotorClient('169.24.2.63', 27017).xlearning_job
    db = motor_tornado.MotorClient(options.mongo_host,
                                   options.mongo_port).xlearning_job
    setting = {
        "debug": True,
        "static_file": path_join('dist'),
        #"static_url_prefix": '/dist/'
    }
    handlers = [
        url(r'/', IndexHandler),
        url(r'/api/hello', HelloHandler),
        url(r'/dist/(.*)', StaticFileHandler, {"path": path_join('dist')}),
        url(r'/api/upload/model', FileUploadHandler),
        url(r'/api/job/create', JobSubmitHandler),
        url(r'/api/jobs', JobHandler),
    ]
    app = Application(handlers=handlers, **setting)
    app.db = db
    app.listen(options.port)
    IOLoop.current().start()
コード例 #7
0
def upload_telemetry_data():
    """
    In case your device is able to get the client-side timestamp, you can use following format
    {"ts":1451649600512, "values":{"key1":"value1", "key2":"value2"}}
    """
    gen_log.info("upload_telemetry_data")
    try:
        data = [{
            attr: random.randint(20, 100)
        } for attr in attributes if attr != 'temperature']
        # data={"temperature":random.randint(20,100),
        # "humidity":random.randint(20,100),
        # "other":random.randint(-60,60),
        #  "active": False}
        url = url_prefix + '/v1/{}/telemetry'.format(token)
        res = yield AsyncHTTPClient().fetch(url,
                                            method='POST',
                                            body=json.dumps(data),
                                            headers=headers)
        #res=requests.post(url,data=json.dumps(data),headers=headers)
        gen_log.info(res.code)
    except Exception as ex:
        gen_log.error(ex)
    IOLoop.current().add_timeout(time.time() + 1, upload_telemetry_data)
コード例 #8
0
ファイル: common.py プロジェクト: hulingfeng211/mywork
                    "$set": clone_dict(row, without=[])
                })

            else:
                obj = clone_dict(row)
                obj['id'] = ObjectId()
                obj['_id'] = obj['id']

                obj['create_time'] = format_datetime(datetime.now())
                obj['create_user'] = self.current_user.get('userid', '')
                yield db[self.cname].insert(obj)
        # self.write(generate_response(message="保存成功"))
        self.send_message("保存成功")


if __name__ == "__main__":
    from tornado.gen import IOLoop, coroutine
    import motor

    client = motor.MotorClient()
    db = client['test']


    @coroutine
    def f():
        yield db['servers'].insert({'a': 'b'})


    ioloop = IOLoop.current()
    ioloop.run_sync(f)
コード例 #9
0
	def get(self,*args,**kwargs):
		self.render('index.html')
		#self.write('hello,text')

class PageHandler(RequestHandler):
	#(r"/(P?<nickname>.*)/article/details/(P?<postid>.*)", MainHandler),
	def get(self,*args):
		#self.write(args[0])
		self.render('jquery-weui-demos/%s'%args[0])
		pass

						

settings = {
	'debug':True,
	'static_path':os.path.join(os.path.dirname(__file__),'static'),
	'template_path':os.path.join(os.path.dirname(__file__),'template'),

}


if __name__=='__main__':
	app=Application(handlers=[
		url(r'/',IndexHandler),
		#url(r'/2',Index2Handler),
		#(r"/(P?<nickname>.*)/article/details/(P?<postid>.*)", MainHandler),
		url(r'/(.*)',PageHandler),
		],**settings)
	app.listen(11108)
	IOLoop.current().start()
コード例 #10
0
import routes
from common import settings 
from tornado.web import Application
from tornado.gen import IOLoop
from tornado.log import gen_log
from tornado.options import define,options ,parse_command_line

from motor.motor_tornado import MotorClient

define('port',default=11108,type=int,help='listen port')
define('debug',default=True,type=bool,help='running at debug mode?')

import logging
logging.basicConfig(level=logging.DEBUG)


if __name__ == '__main__':
	parse_command_line()

	client = MotorClient(host='192.168.2.14',port=27017)
	db=client['smscenter']

	handlers=[]
	handlers.extend(routes.routes)
	app = Application(handlers=handlers,**settings)
	app.db=db
	
	gen_log.info('server listening at '+str(options.port))
	app.listen(options.port)
	IOLoop.current().start()
コード例 #11
0
ファイル: cookiejar.py プロジェクト: quasiben/dask-gateway
 def __init__(self, loop=None):
     self._loop = loop or IOLoop.current()
     self._cookies = defaultdict(SimpleCookie)
     self._host_only_cookies = set()
     self._next_expiration = ceil(self._loop.time())
     self._expirations = {}
コード例 #12
0
     --header "Content-Type:application/json"

    """
    gen_log.info("upload_temperature_data")
    try:

        data = {"temperature": random.randint(20, 100)}
        url = url_prefix + '/v1/{}/telemetry'.format(token)
        res = yield AsyncHTTPClient().fetch(url,
                                            method='POST',
                                            body=json.dumps(data),
                                            headers=headers)
        #res=requests.post(url,data=json.dumps(data),headers=headers)
        gen_log.info(res.code)
    except Exception as ex:
        gen_log.error(ex)
    IOLoop.current().add_timeout(time.time() + 1, upload_temperature_data)


if __name__ == '__main__':
    parse_command_line()
    token = options.token
    if token is None:
        gen_log.error('device access token can not None')
        sys.exit(1)

    IOLoop.current().add_callback(upload_temperature_data)
    IOLoop.current().add_callback(upload_telemetry_data)
    IOLoop.current().add_callback(upload_attribute_data)
    IOLoop.current().start()
コード例 #13
0
from tornado.web import Application, RequestHandler
from loguru import logger
from pathlib import Path
from grouple.backend.cache import CacheManager
# from models.manga_downloader import Downloader, PicDownloader
# from models.NER import load_names_model
# from models.face_detection import AnimeFaceDetectionModel
from grouple.backend.http_utils.handlers.tag_characters_handler import TagCharactersHandler
from grouple.backend.http_utils.handlers.manga_info_handler import MangaInfoHandler


class MainHandler(RequestHandler):
    def get(self):
        self.write({'status': 'ok'})


def make_app(cache):
    args = dict(cache=cache)
    urls = [(r'/main', MainHandler), (r'/manga_info', MangaInfoHandler, args),
            (r'/tag_characters', TagCharactersHandler, args)]
    return Application(urls)


if __name__ == "__main__":
    cache = CacheManager(
        Path('C:/may/ML/GroupLe/grouple/data/backend/cache/cachied'))
    app = make_app(cache)
    app.listen(5022)
    logger.info('Server started')
    IOLoop.instance().start()