class BaseHandler(RequestHandler): @property def db(self): return self.application.db class TutorialHandler(BaseHandler): def _done(self, cursor, error): self.write('Results: %r' % (cursor.fetchall(), )) self.finish() @asynchronous #@gen.engine def get(self): self.db.execute("select * from dc", callback=self._done) if __name__ == '__main__': parse_command_line() application = Application([(r'/', TutorialHandler)], debug=True) application.db = momoko.Pool( dsn='dbname=sugino user=sugino password=bigbird' 'host=localhost port=5432', size=10) http_server = HTTPServer(application) http_server.listen(8888, 'localhost') IOLoop.instance().start()
(r'/js/(.+)', tornado.web.StaticFileHandler, { 'path': './static/js/' }), (r'/images/(.+)', tornado.web.StaticFileHandler, { 'path': './static/images/' }) ], **SETTINGS) if __name__ == '__main__': if application is not None: ioloop = IOLoop.instance() application.db = momoko.Pool( dsn=os.environ['DB_FQDN'], size=1, ioloop=ioloop, ) # this is a one way to run ioloop in sync future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() # raises exception on connection error server = tornado.httpserver.HTTPServer(application, max_buffer_size=10485760000) server.listen(PORT) print('Starting Tornado server on port %s' % PORT) ioloop.start() else:
print('Server Starting') if not config.DEBUG: sock = tornado.netutil.bind_sockets(config.PORT) tornado.process.fork_processes(0) ''' logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s]: %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=config.LOG_FILE_PATH, filemode='a') ''' db = momoko.Pool(dsn='dbname=%s user=%s password=%s host=%s port=%s' % (config.DBNAME, config.DBUSER, config.DBPASSWORD, config.DBHOST, config.DBPORT), size=config.DBMIN_SIZE, max_size=config.DBMAX_SIZE, ioloop=tornado.ioloop.IOLoop.instance(), setsession=("SET TIME ZONE +8", ), raise_connect_errors=False, cursor_factory=psycopg2.extras.RealDictCursor) future = db.connect() tornado.ioloop.IOLoop.instance().add_future( future, lambda f: tornado.ioloop.IOLoop.instance().stop()) tornado.ioloop.IOLoop.instance().start() rs = myredis.MyRedis(db=1) rs.flushdb() ui_modules = { "Pagination": web.modules.Pagination, } app = tornado.web.Application( [
# # http://groovematic.com/2013/03/tornado-lessons-learned/ ioloop = tornado.ioloop.IOLoop.current() # prepares the application application = tornado.web.Application([ (r'/json', JsonHandler), (r'/query/db', QueryPgHandler), (r'/query/http', QueryHttpHandler), ]) application.db = momoko.Pool( dsn='dbname=%s user=%s password=%s host=%s port=%s' % (options.db_database, options.db_user, options.db_password, options.db_host, options.db_port), size=1, max_size=3, ioloop=ioloop, setsession=('SET TIME ZONE UTC', ), raise_connect_errors=False, ) logging.info('Connecting to PostgreSQL on [%s]' % options.db_host) ioloop.run_sync(lambda: application.db.connect()) logging.info('Listening on [8888] port') application.listen(8888) # prepares the web server # srv = tornado.httpserver.HTTPServer(application, xheaders=True) # listens incoming request on port 8000
worlds = [] for i in xrange(int(queries)): random_id = randint(1, 10000) cursor = yield momoko.Op(self.application.db.execute, sql, (random_id, )) row = cursor.fetchone() worlds.append({"id": row[0], "randomNumber": row[1]}) response = json.dumps(worlds) self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(response) application = tornado.web.Application([ (r"/json", JsonSerializeTestHandler), (r"/plaintext", PlaintextHandler), (r"/db", DBTestHandler), (r"/queries", QueryTestHandler), (r"/dbraw", QueryPostgresRawTestHandler), (r"/queriesraw", MultipleQueriesPostgresRawTestHandler) ]) if __name__ == "__main__": tornado.options.parse_command_line() server = tornado.httpserver.HTTPServer(application) server.bind(options.port) server.start(0) if options.postgres: dsn = "user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world host=%s" % options.postgres application.db = momoko.Pool(dsn, size=1) else: db = motor.MotorClient(options.mongo).hello_world tornado.ioloop.IOLoop.instance().start()
(r'/(.*)', web.StaticFileHandler, { "path": "./webapp", "default_filename": "index.html" })], debug=True) logging.info("\t\tApplication routes registered") ioloop = IOLoop.instance() """ Conexión a la base de datos """ application.db = momoko.Pool( dsn="postgresql://{0}:{1}@{2}:{3}/{4}".format( os.environ["POSTGRES_USER"], os.environ["POSTGRES_PASSWORD"], os.environ["POSTGRES_HOST"], os.environ["POSTGRES_PORT"], os.environ["POSTGRES_DB"]), size=1, ioloop=ioloop, ) logging.info("\t\tDatabase defined") """ Selección de clasificador """ if args.classifier == "svm": from lib.SVMClassifier import Classifier elif args.classifier == "tree": from lib.TreeClassifier import Classifier application.clf = Classifier() application.clf.load() logging.info("\t\tClassifier loaded")
cursors = yield [db.execute(self.SQL, (randint(1, 10000),)) for _ in xrange(queries)] for cursor in cursors: row = cursor.fetchone() worlds.append({self.ID: row[0], self.RANDOM_NUMBER: row[1]}) response = json.dumps(worlds) self.finish(response) application = tornado.web.Application([ (r"/json", JsonHelloWorldHandler), (r"/plaintext", PlaintextHelloWorldHandler), (r"/db", SingleQueryHandler), (r"/queries", MultipleQueriesHandler) ], template_path="templates" ) application.ui_modules = {} if __name__ == "__main__": tornado.options.parse_command_line() server = tornado.httpserver.HTTPServer(application) server.bind(options.port, backlog=options.backlog) server.start(0) ioloop = tornado.ioloop.IOLoop.instance() dsn = "user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world host=%s" % options.postgres db = momoko.Pool(dsn, size=100, max_size=200) ioloop.run_sync(db.connect) ioloop.start()
if __name__ == "__main__": parse_command_line() dsn = "dbname=%s user=%s password=%s host=%s port=%s" % ( settings.db_name, settings.db_user, settings.db_pass, settings.db_host, settings.db_port) # a synchronous pool for database queries that should be performed # synchronously db = psycopg2.pool.SimpleConnectionPool(minconn=1, maxconn=1, dsn=dsn) # asynchronous connection pool for async queries. momoko utilizes gen to # perform queries asynchronously using tornado async_db = momoko.Pool(dsn=dsn, size=1, max_size=2, raise_connect_errors=False) dbinterface_cls = get_db_interface("PGSQL") dbinterface = dbinterface_cls(db, async_db) for statcol in settings.indexed_stats: dbinterface.add_stat_index(statcol) api_server = Application(dbinterface) api_server.listen(options.port, options.ip) logging.info("TF2Pug API Server listening on %s:%d", options.ip, options.port)
'password={} ' 'host={} ' 'port={}'.format(db_url.path[1:], db_url.username, db_url.password, db_url.hostname, db_url.port)) logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) app = web.Application(handlers=[(r'/', IndexHandler), (r'/static/(.*)', web.StaticFileHandler, { 'path': 'static/' }), (r'/v1/metrics', MetricsAPI), (r'/v1/ws', SocketHandler)], debug=True) ioloop = IOLoop.instance() app.db = momoko.Pool( dsn=dsn, size=50, ioloop=ioloop, ) future = app.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() # raises exception on database connection error server = HTTPServer(app) server.listen(int(port), host) ioloop.start()
self.write('Results: %r' % (cursor.fetchall(), )) self.finish() class TutorialHandler(BaseHandler): @asynchronous def get(self): query_string = 'SELECT "LookUp"."Description","LookUp"."Id" FROM public."LookUp";' self.db.execute(query_string, callback=self._done) #self.write('Some text here!') #self.finish() def _done(self, cursor, error): self.write('Results: %r' % (cursor.fetchall(), )) self.finish() if __name__ == '__main__': tornado.options.parse_command_line() app = tornado.web.Application( handlers=[(r'/', IndexHandler), (r'/domain', ApplyDomainPageHandler), (r'/applydomainresult', DomainPageHandler), (r'/ip', IPHandler), (r'/pys', PhysicalServerHandler)], template_path=os.path.join(os.path.dirname(__file__), "pages")) app.db = momoko.Pool(dsn='dbname=cmdbuild user=postgres password=abcd123! ' 'host=10.200.200.201 port=5432', size=1) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
import momoko import momoko_settings import tornado.ioloop # momoko_pool.py contains the momoko_db_connection which can connect to a postgres database # This will create a momoko db connection to connect to postgres using dsn, size, and ioloop # dsn : a dsn string that contains a few parameters we need to setup in order to connect to # postgres, # dbname = database name # user = username # password = password # host = hostname # port = port number # size : the minimum amount of connections for postgres # ioloop : the current ioloop instance momoko_db_connection = momoko.Pool(dsn='dbname=%s user=%s password=%s host=%s port=%s' % (momoko_settings.dbname, momoko_settings.user, momoko_settings.password, momoko_settings.host, momoko_settings.port), size=momoko_settings.num_connections, ioloop=tornado.ioloop.IOLoop.current()) # Call connect to establish connection with the momoko pool momoko_db_connection.connect()
results = { 'Q1': cursor1.fetchall(), 'Q3': cursor2.fetchall(), 'Q2': cursor3.fetchall() } self.write(json.dumps(results)) self.finish() if __name__ == '__main__': parse_command_line() application = web.Application([(r'/', MyHandler)], debug=True) ioloop = IOLoop.instance() application.db = momoko.Pool( dsn='dbname=postgis user=postgres password=postgres host=localhost', size=1, ioloop=ioloop, ) # this is a one way to run ioloop in sync future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() http_server = HTTPServer(application) http_server.listen(8888, 'localhost') ioloop.start()
from datetime import date from tornado import gen from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer import momoko from urls import application if __name__ == "__main__": application.listen(8888) _io_loop = IOLoop.instance() application.db = momoko.Pool( dsn='dbname=canary user=cognical ' 'host=localhost port=5432', size=1, ioloop=_io_loop, ) future = application.db.connect() _io_loop.add_future(future, lambda x: _io_loop.stop()) _io_loop.start() future.result() http_server = HTTPServer(application) http_server.listen(8888, 'localhost') _io_loop.start()
import json import time from Config import Config import tornado.web from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop from tornado import gen import momoko import serial.tools.list_ports import threading import csv import ast import psycopg2 ioloop = IOLoop.instance() conn = momoko.Pool(dsn=Config.pdb, size=1, ioloop=ioloop) fut = conn.connect() ioloop.add_future(fut, lambda f: ioloop.stop()) ioloop.start() try: fut.result() # raises exception on connection error except Exception as error: with open(Config.logs, "a") as logfile: logfile.write(time.strftime('%Y-%m-%d %H:%M:%S | ', time.localtime()) + "Exception in connection to db: " + str(error)) logfile.write("\n") class MyThread (threading.Thread): def __init__(self, threadID, name):
if options.USE_RC: redisConnectionPool = redis.ConnectionPool( host='localhost', port=6379, db=12 ) application.rc = redis.Redis(connection_pool=redisConnectionPool) logging.info('Using Redis') if options.FLUSH_RC: application.rc.flushdb() if options.USE_DB: application.db = momoko.Pool( dsn='dbname=exness user=ror password=rorx ' 'host=localhost port=5432', size=1, max_size=100, ioloop=ioloop, ) future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() logging.info('Using Database') if options.FILL_DB: logging.info('Filling Database') _fill_db(application.db) logging.info("Starting tornado web server") application.listen(8888)
class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): def handle_db(cursor, error): db_value = cursor.fetchone()[0] def handle_http(response): json_data = json.loads(response.body.decode()) result = db_value - json_data['value'] self.write("Result: %s" % result) self.finish() http_client = tornado.httpclient.AsyncHTTPClient() http_client.fetch('http://127.0.0.1:8000/', handle_http) self.application.db.execute( 'SELECT 42, pg_sleep(0.300)', callback=handle_db) application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": print("Serve http://127.0.0.1:8888/") application.db = momoko.Pool(dsn='dbname=al user=al', size=10) application.listen(8888) tornado.ioloop.IOLoop.instance().start()
(r"/", mainHandler), ]) url = options.url % options.token + "setWebhook?url=%s" % options.myurl files = { 'certificate': open('/usr/share/nginx/qa_bot/qa_bot_company.pem', 'rb') } set_hook = api.post(url, files=files) if set_hook.status_code != 200: logging.error("Cant set hook: %s. Quit", set_hook.text) exit(1) application.db = momoko.Pool( dsn=options.dsn, size=1, max_size=3, ioloop=ioloop, setsession=("SET TIME ZONE UTC", ), raise_connect_errors=False, ) application._db_templates = Snaql('models/', 'queries').load_queries('model.sql') future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() application.listen(options.serverport) ioloop.start()
# self.write(json.dump(allposts)) self.write({'posts': allposts}) except (psycopg2.Warning, psycopg2.Error) as e: self.set_status(400) self.write({'success': False}) print(str(e)) self.finish() if __name__ == '__main__': Options.parse_command_line() ioloop = IOLoop.instance() database = momoko.Pool( dsn=DATABASE_URL, size=1, ioloop=ioloop, ) application = web.Application([ (r'/', HomeHandler), (r'/login', LoginHandler, dict(database=database)), (r'/register', LoginHandler, dict(database=database)), (r'/post', PostHandler, dict(database=database)), (r'/feed', FeedHandler, dict(database=database)), ], debug=True) application.db = database # this is a one way to run ioloop in sync future = database.connect() ioloop.add_future(future, lambda f: ioloop.stop())
try: pass except (psycopg2.Warning, psycopg2.Error) as error: logging.warning(str(error)) if __name__ == '__main__': ioloop = IOLoop.instance() caching = CacheToPostgresql() caching.db = momoko.Pool( dsn=dns(db_name='live_chat', user='******', password='******', host='localhost', port=5432), size=1, max_size=3, ioloop=ioloop, raise_connect_errors=False, ) ioloop.start() # future = cacher.db.connect() # ioloop.add_future(future, lambda f: ioloop.stop()) # ioloop.start() # future.result()
def __init__(self, ioloop, connection_string, pool_size): self.ioloop = ioloop self.pool = momoko.Pool(dsn=connection_string, size=pool_size, ioloop=ioloop, cursor_factory=psycopg2.extras.DictCursor)
def db(self): return self.application.db class TutorialHandler(BaseHandler): @asynchronous def get(self): query_string='SELECT "LookUp"."Description","LookUp"."Id" FROM public."LookUp";' self.db.execute(query_string,callback=self._done) #self.write('Some text here!') #self.finish() def _done(self,cursor,error): self.write('Results: %r'%(cursor.fetchall(),)) self.finish() if __name__ == '__main__': parse_command_line() application = Application([ (r'/', TutorialHandler) ], debug=True) application.db = momoko.Pool( dsn='dbname=cmdbuild user=postgres password=000000 ' 'host=10.200.200.233 port=5432', size=1 ) http_server = HTTPServer(application) http_server.listen(8888, 'localhost') IOLoop.instance().start()
from foundation import const from foundation.parseConfig import load_conf load_conf('postgresql') executor = concurrent.futures.ThreadPoolExecutor(max_workers=int(process.cpu_count())) # 创建一个线程池 ioloop = IOLoop.instance() # 创建数据库连接池 dbpool = momoko.Pool( dsn='dbname={dbname} user={user} password={pwd} host={host} port={port}'.format( dbname=const.postgresql.get("dbname"), user=const.postgresql.get("user"), pwd=const.postgresql.get("password"), host=const.postgresql.get("host"), port=const.postgresql.get("port")), cursor_factory=psycopg2.extras.RealDictCursor, size=int(const.postgresql.get("size")), max_size=int(const.postgresql.get("max_size")), raise_connect_errors=True if const.postgresql.get("raise_connect_errors") == 'True' else False, reconnect_interval=int(const.postgresql.get("reconnect_interval")), auto_shrink=True if const.postgresql.get("auto_shrink") == 'True' else False, shrink_period=datetime.timedelta(seconds=1), shrink_delay=datetime.timedelta(minutes=5), ioloop=ioloop ) future = dbpool.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result()
tornado.options.define( "update_rate", default=update_rate, help="The rate at which updates are pushed (seconds)", type=float) tornado.options.parse_command_line() ioloop = tornado.ioloop.IOLoop.instance() llWebSocketServer = llWSApplication( update_rate=tornado.options.options.update_rate) llWebSocketServer.db = momoko.Pool( dsn=db_details, size=2, #minimum number of connections for the momoko pool to maintain max_size=6, #max number of conns that will be opened ) llWebSocketServer.listen(tornado.options.options.port, tornado.options.options.ip) logger.info("Websocket server listening on %s:%s", tornado.options.options.ip, tornado.options.options.port) try: ioloop.start() except: llWebSocketServer.db.close() tornado.ioloop.IOLoop.instance().stop() logger.info("Exception whilst serving. Exiting") sys.exit()
class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http_client = tornado.httpclient.AsyncHTTPClient() cursor, response = yield [ self.application.db.execute('SELECT 42, pg_sleep(0.300)'), http_client.fetch('http://127.0.0.1:8000/'), ] db_value = cursor.fetchone()[0] json_data = json.loads(response.body.decode()) result = db_value - json_data['value'] self.write("Result: %s" % result) self.finish() application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": print("Serve http://127.0.0.1:8888/") ioloop = tornado.ioloop.IOLoop.instance() application.db = momoko.Pool(dsn='dbname=al user=al password=al', size=10, ioloop=ioloop) future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() # raises exception on connection error application.listen(8888) tornado.ioloop.IOLoop.instance().start()
random_id = randint(1, 10000) cursor = yield self.application.db.execute(sql, (random_id, )) row = cursor.fetchone() worlds.append({"id": row[0], "randomNumber": row[1]}) response = json.dumps(worlds) self.set_header("Content-Type", "application/json; charset=UTF-8") self.write(response) application = tornado.web.Application([ (r"/json", JsonSerializeTestHandler), (r"/plaintext", PlaintextHandler), (r"/db", DBTestHandler), (r"/queries", QueryTestHandler), (r"/dbraw", QueryPostgresRawTestHandler), (r"/queriesraw", MultipleQueriesPostgresRawTestHandler) ]) if __name__ == "__main__": tornado.options.parse_command_line() server = tornado.httpserver.HTTPServer(application) server.bind(options.port) server.start(0) ioloop = tornado.ioloop.IOLoop.instance() if options.postgres: dsn = "user=benchmarkdbuser password=benchmarkdbpass dbname=hello_world host=%s" % options.postgres application.db = momoko.Pool(dsn, size=1, max_size=100) ioloop.run_sync(application.db.connect) else: db = motor.MotorClient(options.mongo).hello_world ioloop.start()
#!/bin/bash python # -*- coding: utf-8 -*- import psycopg2 import momoko from tornado.ioloop import IOLoop ioloop = IOLoop.instance() dsn = "user=postgres password=postgres dbname=qa_bot host=localhost port=5432" conn = momoko.Pool(dsn=dsn) future = conn.connect() ioloop.add_future(future, lambda x: ioloop.stop()) ioloop.start() future.result() # raises exception on connection error future = conn.execute("SELECT * FROM public.test_table") ioloop.add_future(future, lambda x: ioloop.stop()) ioloop.start() cursor = future.result() rows = cursor.fetchall() print(rows)
self.render('result.html', q_a=q_a, q_id=q_id) if __name__ == "__main__": parse_command_line() ioloop = IOLoop.instance() application = Application( [(r"/", QuestionnaireListHandler), (r"/cat/(\d+)", QuestionHandler), (r"/result/(\d+)", ResultHandler)], template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), cookie_secret=COOKIE_SECRET, debug=True, xsrf_cookies=True, ) application.db = momoko.Pool( dsn=DSN, size=1, ioloop=ioloop, cursor_factory=NamedTupleCursor, ) future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() http_server = HTTPServer(application) http_server.listen(8000, 'localhost') ioloop.start()
if __name__ == '__main__': parse_command_line() application = web.Application([(r'/bootstrap/css/bootstrap.min.css', New), ( r'/', TutorialHandler, ), (r'/post/(.*)', Edit), ( r'/paste', Paste, ), (r'/postman', send), (r'/sql', sql)], debug=True, **settings) ioloop = IOLoop.instance() application.db = momoko.Pool( dsn='dbname=paste user=sorgo password=123456 host=localhost port=5432', size=1, ioloop=ioloop, ) # this is a one way to run ioloop in sync future = application.db.connect() ioloop.add_future(future, lambda f: ioloop.stop()) ioloop.start() future.result() # raises exception on connection error http_server = HTTPServer(application) http_server.listen(8080, '192.168.1.116') ioloop.start()
def post(self): data = tornado.escape.json_decode(self.request.body) ioloop = IOLoop.current() self.connected = False admin = momoko.Pool( dsn='dbname=postgres user=postgres password=kolbykolby ' 'host={0} port=5432'.format(os.getenv('POSTGRESQL_SERVICE_HOST')), size=1, ioloop=ioloop, cursor_factory=psycopg2.extras.RealDictCursor, ) future = admin.connect() cursor = yield admin.execute("""SELECT u.usename AS "username", u.usesysid AS "User ID", CASE WHEN u.usesuper AND u.usecreatedb THEN CAST('superuser, create database' AS pg_catalog.text) WHEN u.usesuper THEN CAST('superuser' AS pg_catalog.text) WHEN u.usecreatedb THEN CAST('create database' AS pg_catalog.text) ELSE CAST('' AS pg_catalog.text) END AS "Attributes" FROM pg_catalog.pg_user u ORDER BY 1;""") all = cursor.fetchall() for user in all: if user['username'] == data['username']: self.write("Invalid Username") return cursor = yield admin.execute("""SELECT datname FROM pg_database WHERE datistemplate = false;""") all = cursor.fetchall() for db in all: if db['datname'] == data['database']: self.write("Invalid Database name") return try: cursor = yield admin.execute( """CREATE USER {0} WITH PASSWORD '{1}';""".format( data['username'], data['password'])) except psycopg2.Error as e: self.write(e.diag.message_primary) return try: cursor = yield admin.execute( """CREATE DATABASE {0} OWNER {1};""".format( data['database'], data['username'])) except psycopg2.Error as e: self.write(e.diag.message_primary) return self.write("User and database created")