def main(): options.logging = None parse_command_line() options.subpath = options.subpath.strip('/') if options.subpath: options.subpath = '/' + options.subpath # Connect to mongodb io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop, username=config.DB_USER, password=config.DB_PWD) # Star application from application import app if options.unix_socket: server = tornado.httpserver.HTTPServer(app) socket = tornado.netutil.bind_unix_socket(options.unix_socket, 0o666) server.add_socket(socket) print('Server is running at %s' % options.unix_socket) print('Quit the server with Control-C') else: http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print('Server is running at http://127.0.0.1:%s%s' % (options.port, options.subpath)) print('Quit the server with Control-C') io_loop.start()
def main(): options.logging = None parse_command_line() io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) if options.unix_socket: server = tornado.httpserver.HTTPServer(app) socket = tornado.netutil.bind_unix_socket(options.unix_socket, 0o666) server.add_socket(socket) print('Server is running at %s' % options.unix_socket) print('Quit the server with Control-C') else: http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print('Server is running at http://127.0.0.1:%s%s' % (options.port, options.subpath)) print('Quit the server with Control-C') io_loop.start()
def after_start(cls, application, io_loop=None, *args, **kw): databases = application.config.get('MONGO_DATABASES') if not databases or not isinstance(databases, (dict, )): raise RuntimeError( "MONGO_DATABASES configuration is required and should be a dictionary." ) for key, value in databases.items(): host = value['host'] port = int(value['port']) db = value['database'] username = value.get('username', None) password = value.get('password', None) conn_str = "mongodb://%s:%d/%s" % (host, port, db) if username is not None: if password is not None: conn_str = "mongodb://%s:%s@%s:%d/%s" % ( username, password, host, port, db) else: conn_str = "mongodb://%s@%s:%d/%s" % (username, host, port, db) arguments = dict(host=conn_str, io_loop=io_loop) arguments['alias'] = key replica_set = arguments.get('replica_set', None) if replica_set is not None: arguments['replicaSet'] = replica_set logging.info("Connecting to mongodb at %s" % conn_str) motorengine.connect(db, **arguments)
def after_start(cls, application, io_loop=None, *args, **kw): databases = application.config.get('MONGO_DATABASES') if not databases or not isinstance(databases, (dict,)): raise RuntimeError("MONGO_DATABASES configuration is required and should be a dictionary.") for key, value in databases.items(): host = value['host'] port = int(value['port']) db = value['database'] username = value.get('username', None) password = value.get('password', None) conn_str = "mongodb://%s:%d/%s" % (host, port, db) if username is not None: if password is not None: conn_str = "mongodb://%s:%s@%s:%d/%s" % (username, password, host, port, db) else: conn_str = "mongodb://%s@%s:%d/%s" % (username, host, port, db) arguments = dict( host=conn_str, io_loop=io_loop ) arguments['alias'] = key replica_set = arguments.get('replica_set', None) if replica_set is not None: arguments['replicaSet'] = replica_set logging.info("Connecting to mongodb at %s" % conn_str) motorengine.connect(db, **arguments)
def main(): options.logging = None parse_command_line() options.subpath = options.subpath.strip('/') if options.subpath: options.subpath = '/' + options.subpath # Connect to mongodb io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) # username=config.DB_USER, password=config.DB_PWD) # Star application from application import app if options.unix_socket: server = tornado.httpserver.HTTPServer(app) socket = tornado.netutil.bind_unix_socket(options.unix_socket, 0o666) server.add_socket(socket) print('Server is running at %s' % options.unix_socket) print('Quit the server with Control-C') else: http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print('Server is running at http://127.0.0.1:%s%s' % (options.port, options.subpath)) print('Quit the server with Control-C') io_loop.start()
def test_connect_to_replica_set_with_invalid_replicaset_name(self): try: connect('test', host="localhost:27017,localhost:27018", replicaSet=0, port=27017, io_loop=self.io_loop) except ConnectionError: exc_info = sys.exc_info()[1] expect(str(exc_info)).to_include('the replicaSet keyword parameter is required') else: assert False, "Should not have gotten this far"
def main(): parse_command_line() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print 'Server is running at http://127.0.0.1:%s/' % options.port print 'Quit the server with Control-C' io_loop = tornado.ioloop.IOLoop.instance() connect("local", host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) io_loop.start()
def run_app(port): db = motor.MotorClient('mongodb://localhost:27017').test_db app = tornado.web.Application([(r"/", MainHandler), (r"/api/devices", DeviceHandler), (r"/api/patients", PatientHandler), (r"/api/assignment", AssignDeviceHandler)], db=db) app.listen(port=port) io_loop = tornado.ioloop.IOLoop.instance() connect('test_db', host='mongodb://localhost:27017', io_loop=io_loop) tornado.ioloop.IOLoop.current().start()
def main(): """Construct and serve the tornado application.""" application = Application([ (r"/projects", Project), ], debug=True) io_loop = IOLoop.instance() motorengine.connect("test", host="localhost", port=27017, io_loop=io_loop) http_server = HTTPServer(application) http_server.listen(options.port) print('Listening on http://localhost:%i' % options.port) IOLoop.current().start()
def test_connect_to_replica_set_with_invalid_replicaset_name(self): try: connect('test', host="localhost:27017,localhost:27018", replicaSet=0, port=4445, io_loop=self.io_loop) except ConnectionError: exc_info = sys.exc_info()[1] expect(str(exc_info)).to_include( 'the replicaSet keyword parameter is required') else: assert False, "Should not have gotten this far"
def main(): os.environ['PST_MAIL_SUBJECT'] = u"[PST Server][log]" import pservers from motorengine import connect import pst.manlog logger = pst.manlog.logger logger.info("Starting PServer....") io_loop = tornado.ioloop.IOLoop.instance() connect('pst', io_loop=io_loop) tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(PServerApp(get_routes(pservers))) http_server.listen(options.port) io_loop.start()
def setUp(self, auto_connect=True): super(AsyncTestCase, self).setUp() if auto_connect: self.db = connect("test", host="localhost", port=4445, io_loop=self.io_loop)
def test_database_returns_collection_when_asked_for_a_name(self): db = connect("test", host="localhost", port=27017, io_loop=self.io_loop) expect(db.something).to_be_instance_of(motor.MotorCollection)
def test_database_ping(self): db = connect("test", host="localhost", port=27017, io_loop=self.io_loop) args, kwargs = self.exec_async(db.ping) ping_result = args[0]['ok'] expect(ping_result).to_equal(1.0) disconnect()
def setUp(self, auto_connect=True): super(AsyncTestCase, self).setUp() if auto_connect: self.db = motorengine.connect("test", host="localhost", port=27017, io_loop=self.io_loop) mongoengine.connect("test", host="localhost", port=27017)
def test_database_ping(self): db = connect("test", host="localhost", port=4445, io_loop=self.io_loop) args, kwargs = self.exec_async(db.ping) ping_result = args[0]['ok'] expect(ping_result).to_equal(1.0) disconnect()
def connect_db(io_loop=None): def create_host(config): port = '' host = 'mongodb://' credentials = '' if 'password' in config and config['password']: credentials = ':' + config['password'] if 'username' in config and config['username']: credentials = config['username'] + credentials + '@' if 'port' in config and config['port']: port = ':' + str(config['port']) return host + credentials + config['host'] + port + '/' + config['db'] io_loop = tornado.ioloop.IOLoop.instance() if io_loop is None else io_loop default = DATABASE['default'] connect(default['db'], host=create_host(default), io_loop=io_loop) return io_loop
def test_can_connect_to_a_database(self): db = connect('test', host="localhost", port=27017, io_loop=self.io_loop) args, kwargs = self.exec_async(db.ping) ping_result = args[0]['ok'] expect(ping_result).to_equal(1.0)
def test_connect_to_replica_set(self): db = connect('test', host="localhost:27017,localhost:27018", replicaSet="rs0", port=27017, io_loop=self.io_loop) args, kwargs = self.exec_async(db.ping) ping_result = args[0]['ok'] expect(ping_result).to_equal(1.0)
def main(): parse_command_line() # connect to mongodb io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) # start the application from application import app http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print('Server is running at http://127.0.0.1:{}'.format(options.port)) print('Quit the server with Control-C') # start the ioloop io_loop.start()
def setUp(self): super(BenchmarkTest, self).setUp() self.db = motorengine.connect("test", host="localhost", port=27017, io_loop=self.io_loop) mongoengine.connect("test", host="localhost", port=27017) self.motor = motor.MotorClient('localhost', 27017, io_loop=self.io_loop, max_concurrent=500).open_sync()
def main(): db_name = os.environ.get('DB_NAME', 'test') db_host = os.environ.get('DB_HOST', '10.200.10.1') db_port = os.environ.get('DB_PORT', '27017') db_user = os.environ.get('DB_USER', '') db_password = os.environ.get('DB_PASSWORD', '') credentials = None if not db_user else '{0}:{1}@'.format( db_user, db_password) if credentials is not None: db_url = 'mongodb://{0}{1}:{2}/{3}'.format(credentials, db_host, db_port, db_name) else: db_url = 'mongodb://{0}:{1}/'.format(db_host, db_port) app = tornado.web.Application([ (r"/", MainHandler), ]) app.listen(8003) io_loop = tornado.ioloop.IOLoop.current() motorengine.connect(db_name, host=db_url, io_loop=io_loop) io_loop.start()
def __init__(self, settings): handlers = routes.get_routes() + [ tornado.web.URLSpec( r'/login/google', GoogleLoginHandler, name='login_google'), tornado.web.URLSpec(r'/', MainHandler, name='home'), tornado.web.URLSpec(r'/(.*)', tornado.web.StaticFileHandler, {'path': os.path.join(PRJ_ROOT, 'static')}, name='homestatic'), tornado.web.URLSpec(r'/login/', LoginHandler, name='login'), tornado.web.URLSpec(r'/login/facebook', FacebookLoginHandler, name='login_facebook'), tornado.web.URLSpec( r'/login/twitter', TwitterLoginHandler, name='login_twitter'), tornado.web.URLSpec(r'/logout', AuthLogoutHandler, name='logout'), #(r'/static/(.*)', tornado.web.StaticFileHandler, # {'path': os.path.join(PRJ_ROOT, 'static')}), ] if not settings['db_uri'].startswith('mongodb://'): settings['db_connection'] = connect(settings['db_uri']) else: #_tmp_db = settings['db_uri'][10:] #_tmp_db_name = _tmp_db.split('/')[1] #host="localhost", port=27017 #settings['db_connection'] = connect(_tmp_db_name, host="localhost", port=27017) pass template_dirs = [] jinja2_env = None if settings.get('template_path'): template_dirs.append(settings['template_path']) assets_env = AssetsEnvironment(settings['static_path'], '/') settings['jinja2_env'] = Jinja2Environment( loader=FileSystemLoader(template_dirs), extensions=[AssetsExtension]) settings['jinja2_env'].assets_environment = assets_env tornado.web.Application.__init__(self, handlers, **settings)
from tornado import httpserver, ioloop from tornado.options import define, options from tornado.web import StaticFileHandler from handlers import (CallbackHandler, GzippedContentHandler, IndexHandler, LogoutHandler, PointHandler, TournamentHandler) from motorengine import connect define("port", default=8080, help="run on given port", type=int) # Initializing the environmental variables. mongo_host = os.environ.get("MONGO_HOST_ENV", "mongodb://localhost:27017/toradar") if __name__ == "__main__": tornado.options.parse_command_line() connect('toradar', host=mongo_host) app = tornado.web.Application( handlers=[(r'/', IndexHandler), (r'/callback', CallbackHandler), (r'/logout', LogoutHandler), (r'/tournament', TournamentHandler), (r'/tournament/(?P<tid>.*?)/?$', TournamentHandler), (r'/static/(.*)', GzippedContentHandler, { "path": os.path.join(os.path.dirname(__file__), "../build") }), (r'/assets/(.*)', StaticFileHandler, { "path": os.path.join(os.path.dirname(__file__), "../assets") }), (r'/point', PointHandler)], template_path=os.path.join(os.path.dirname(__file__), "../templates"), gzip=True,
def setMotorEngine(): io_loop = tornado.ioloop.IOLoop.instance() motorengine.connect("xacesite", host="192.168.1.21", port=27017, io_loop=io_loop)
self.finish() class MongoEngineInsertHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): result = MongoDocument.objects.create( field1="whatever", field2=10 ) self.write(str(result.id)) self.finish() def get_app(): return tornado.web.Application([ ('/motor/insert', MotorEngineInsertHandler), ('/mongo/insert', MongoEngineInsertHandler) ]) if __name__ == "__main__": application = get_app() application.listen(8888) io_loop = tornado.ioloop.IOLoop.instance() motorengine.connect("test", host="localhost", port=27017, io_loop=io_loop) mongoengine.connect("test", host="localhost", port=27017) io_loop.start()
@gen.coroutine def create_schools(): schools = [ {'name': u'广州大学', 'verifier': u''}, {'name': u'中山大学', 'verifier': u''}, {'name': u'华南理工大学', 'verifier': u''}, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) #username=config.DB_USER, password=config.DB_PWD) io_loop.add_timeout(1, init_db) io_loop.start()
db = jsonapi.motorengine.Database() # Create the API api = jsonapi.tornado.TornadoAPI("/api", db) api.add_type(user_schema) api.add_type(post_schema) return api def create_app(): """ Creates the tornado application. """ app = tornado.web.Application(autoreload=True, debug=True) api = create_api() api.init_app(app) return app if __name__ == "__main__": tornado.platform.asyncio.AsyncIOMainLoop().install() app = create_app() motorengine.connect("py-jsonapi-test") http_server = tornado.httpserver.HTTPServer(app) http_server.listen(5000) loop = asyncio.get_event_loop() loop.run_forever()
# Роутинг handlers = [ # Index (r"/_/logout", system.handler.LogoutHandler), (r"/_/login", system.handler.LoginHandler), # Kanban (r"/_/boards", handlers.kanban.BoardListHandler), (r"/_/board", handlers.kanban.BoardItemHandler), (r"/_/board/([\w-]+)", handlers.kanban.BoardItemHandler), (r"/_/list", handlers.kanban.ListCardsHandler), (r"/_/list/([\w-]+)", handlers.kanban.ListCardsHandler), (r"/_/card", handlers.kanban.CardHandler), (r"/_/card/([\w-]+)", handlers.kanban.CardHandler), ] # Настройки подключения к базе данных MongoDB DB_HOST = "localhost" DB_PORT = 27017 DB_NAME = "kanban" motorengine.connect(db=DB_NAME, host=DB_HOST, port=DB_PORT) # Настройки приложения - доступны внутри хендлеров через self.settings settings = { "cookie_secret": "__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__", "login_url": "/login", }
}, { 'name': u'华南理工大学', 'verifier': u'' }, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop, username=config.DB_USER, password=config.DB_PWD) io_loop.add_timeout(1, init_db) io_loop.start()
def setMotorEngine(): io_loop = tornado.ioloop.IOLoop.instance() motorengine.connect("xacesite", host="192.168.1.21", port=27017, io_loop=io_loop) return io_loop
from data.collections import School @gen.coroutine def create_schools(): schools = [ {'name': u'广州大学', 'verifier': u''}, {'name': u'中山大学', 'verifier': u''}, {'name': u'华南理工大学', 'verifier': u''}, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect("local", host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) io_loop.add_timeout(1, init_db) io_loop.start()
import multiprocessing import os.path import Queue import shutil from StringIO import StringIO import zipfile from motorengine import connect import requests import tornado from tse_api import models log = logging.getLogger(__name__) io_loop = tornado.ioloop.IOLoop.instance() connect("tse_api", host="localhost", port=27017, io_loop=io_loop) class CandidateBot(object): def get_candidate_list(self): work_queue = multiprocessing.Queue() states_list = ['AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MG', 'MS', 'MT', 'PA', 'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO'] states_list = ['RS'] # for year in [1994, 1996, 1998, 2000, 2002, 2004, 2006, 2008, 2010, 2012, 2014]: for year in [2014]:
import motorengine from datetime import datetime from mongomock import gridfs gridfs.enable_gridfs_integration() motorengine.connect("graphene-motorengine-test", host="mongomock://localhost", alias="default") # motorengine.connect('graphene-motorengine-test', host='mongodb://localhost/graphene-motorengine-dev') class Publisher(motorengine.Document): meta = {"collection": "test_publisher"} name = motorengine.StringField() @property def legal_name(self): return self.name + " Inc." def bad_field(self): return None class Editor(motorengine.Document): """ An Editor of a publication. """ meta = {"collection": "test_editor"} id = motorengine.StringField(primary_key=True)
'verifier': u'' }, { 'name': u'中山大学', 'verifier': u'' }, { 'name': u'华南理工大学', 'verifier': u'' }, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect("local", host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) io_loop.add_timeout(1, init_db) io_loop.start()
self.finish() class MongoEngineInsertHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): result = MongoDocument.objects.create( field1="whatever", field2=10 ) self.write(str(result.id)) self.finish() def get_app(): return tornado.web.Application([ ('/motor/insert', MotorEngineInsertHandler), ('/mongo/insert', MongoEngineInsertHandler) ]) if __name__ == "__main__": application = get_app() application.listen(8888) io_loop = tornado.ioloop.IOLoop.instance() motorengine.connect("test", host="localhost", port=4445, io_loop=io_loop) mongoengine.connect("test", host="localhost", port=4445) io_loop.start()
async def init_message_media(): for media in MediaEnum: await NotifyMedia(code=media.name, name=media.value).save() async def init_third_part_platform(): for platform in ThirdPartyPlatformEnum: await ThirdPartyPlatform(code=platform.name, name=platform.value).save() async def init_db(): # await init_event_status() # await init_event_level() await init_message_media() await init_message_schedule() await init_third_part_platform() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect(MONGODB.name, host=MONGODB.host, port=MONGODB.port, io_loop=io_loop) io_loop.add_timeout(1, init_db) io_loop.start()
@gen.coroutine def create_schools(): schools = [ {'name': u'广州大学', 'verifier': u''}, {'name': u'中山大学', 'verifier': u''}, {'name': u'华南理工大学', 'verifier': u''}, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop, username=config.DB_USER, password=config.DB_PWD) io_loop.add_timeout(1, init_db) io_loop.start()
def setUp(self, auto_connect=True): super(AsyncTestCase, self).setUp() if auto_connect: self.db = motorengine.connect("test", host="localhost", port=4445, io_loop=self.io_loop) mongoengine.connect("test", host="localhost", port=4445)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import asyncio import uvloop import falcon import falcon_jsonify from tornado import ioloop from motorengine import connect from middlewares.error import ErrorHandler asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) api = falcon.API(middleware=[ falcon_jsonify.Middleware( help_messages=True), # show helpful debug messages ErrorHandler() ]) connect("py-api", host="localhost", port=27017, io_loop=ioloop.IOLoop.instance())
def setUp(self, auto_connect=True): super(AsyncTestCase, self).setUp() if auto_connect: self.db = connect("test", host="localhost", port=27017, io_loop=self.io_loop)
'verifier': u'' }, { 'name': u'华南理工大学', 'verifier': u'' }, ] # School.objects.delete() for school in schools: yield School(**school).save() @gen.coroutine def init_db(): yield create_schools() io_loop.stop() if __name__ == '__main__': io_loop = ioloop.IOLoop.instance() connect(config.DB_NAME, host=config.DB_HOST, port=config.DB_PORT, io_loop=io_loop) #username=config.DB_USER, password=config.DB_PWD) io_loop.add_timeout(1, init_db) io_loop.start()
def setUp(self): super(BenchmarkTest, self).setUp() self.db = motorengine.connect("test", host="localhost", port=4445, io_loop=self.io_loop) mongoengine.connect("test", host="localhost", port=4445) self.motor = motor.MotorClient('localhost', 4445, io_loop=self.io_loop, max_concurrent=500).open_sync()
email = StringField(required=True) name = StringField(required=True) password = StringField(required=True) admin = BooleanField(default=False) created_at = StringField(default=datetime.datetime.now().isoformat) token = StringField(default=lambda: token_urlsafe(16)) def is_admin(self): return self.admin if __name__ == '__main__': import tornado import tornado.ioloop from motorengine import connect connect('pst') io_loop = tornado.ioloop.IOLoop.current() def create_testbox(): tsb = TestBox(hostname='tbox1', box_id=1) tsb.save(handle_testbox_saved) def handle_testbox_saved(tsb): try: assert tsb is not None assert tsb.box_id == 1 finally: io_loop.stop() def create_user(): user = User(name='zexi', email='*****@*****.**', admin=True, password='******')