def main(debug=False, tj=False): """ main loop for tornado server sets all needed information for running :param bool debug: run server in debug or production modes """ config = configobj.ConfigObj('config.ini') global slog, alog, redisdb engine = create_engine('{}{}:{}'.format(config['crate']['protocol'], config['crate']['host'], config['crate']['port'])) # models.init_db(engine) connection = scoped_session(sessionmaker(bind=engine)) models.init_db(engine) urls = [ (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": "./static"}), (r"/favicon.ico", tornado.web.StaticFileHandler, {"path": "./static/"}), (r"/favicon", tornado.web.StaticFileHandler, {"path": "./static/"}), (r"/", MainHandler), (r"/search/([^/]+)", SearchHandler) ] base_dir = os.path.dirname(__file__) app = tornado.web.Application(urls, cookie_secret="sopadeletrinhas123", **{"login_url": "/login", "logout_url": "/logout", "debug": False, "compress_response": True, 'template_path': os.path.join(base_dir, "templates"), 'static_path': os.path.join(base_dir, "static"), "xsrf_cookies": False, } ) app.db = connection loglevel = [logging.INFO, logging.DEBUG] slog = utils.setup_logger('tornado_oauthlib', './log/oauthdebug.log', loglevel[debug]) alog = utils.setup_logger('access_log', './log/access.log', logging.INFO, '%(asctime)s|%(message)s') if not debug: # server configuration for production print("Server Production Starting") server = HTTPServer(app) server.bind(int(config['tornado']['port'])) server.start(int(config['tornado']['sockets'])) main_loop = tornado.ioloop.IOLoop.instance() main_loop.start() else: # server configuration for develop print("Server Develop Starting") app.settings['debug'] = True app.listen(int(config['tornado']['port'])) main_loop = tornado.ioloop.IOLoop.instance() IOLoop.instance().start()
def __init__(self, app, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.app = app import os if not os.path.exists('data/cocoqq.db'): import models models.init_db() self.init_ui() # 其他ui界面的初始化工作 import login # 这里必须将这个LoginHandler的实例保存起来,不然被析构掉后,槽就没有了 self.login_handler = login.LoginHandler(self) import libqq self.coco = libqq.Coco() import mainpanel self.main_panel_handler = mainpanel.MainHandler(self) self.init_event() self.init_connect() # 长连接 import thread thread.start_new_thread(self.poll, ()) # 心跳 thread.start_new_thread(self.coco.get_msg_tip, ()) # 调试用 self.login_btn.click()
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), url(r'/login',LoginHandler, name='login'), url(r'/register',RegisterHandler, name='register'), url(r'/main',MainHandler, name='main'), url(r'/test',TestHandler,name='test'), url(r'/out',OutHandler,name='out'), url(r'/user',UserHandler,name='user'), url(r'/chats',ChatHandler,name="chats"), url(r'/chat',SocketHandler,name = "chat") ] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), 'templates'), xsrf_cookies=True, # TODO Change this to a random string cookie_secret="nzjxcjasduuqwheazmu293nsadhaslzkci9023nsadnua9sdads/Vo=", login_url="/login", ui_modules=uimodules, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def create_app(): app = Flask(__name__) app.config['CELERY_BROKER_URL'] = CELERY_BROKER_URL app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' celery.conf.update(app.config) bootstrap = Bootstrap(app) app.config['SECRET_KEY'] = 'hard to guess string' app.config['UPLOAD_FOLDER'] = '/tmp/submissions/' app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024 app.config['ALLOWED_EXTENSIONS'] = set(['apk']) if not os.path.exists(app.config['UPLOAD_FOLDER']): os.makedirs(app.config['UPLOAD_FOLDER']) import views app.register_blueprint(views.status) app.register_blueprint(views.uploadbp) models.init_db() emu_manager.init_emulators() limiter = Limiter(app, default_limits=["1/second"], key_func=get_remote_address) limiter.limit("20/hour")(views.uploadbp) return app, limiter
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), url(r'/index', IndexHandler, name='index2'), url(r'/about', AboutHandler, name='about'), url(r'/code', CodeHandler, name='code'), url(r'/resume', ResumeHandler, name='resume'), url(r'/blog', BlogHandler, name='blog'), ] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "../static"), template_path=os.path.join(os.path.dirname(__file__), '../views'), xsrf_cookies=True, # TODO Change this to a random string cookie_secret= "nzjxcjasduuqwheazmu293nsadhaslzkci9023nsadnua9sdads/Vo=", ui_modules=uimodules, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def update_letv(): models.init_db() session = models.Session() movies = session.query(models.OnLineMovies) ret = letv.get_all() for one in ret: one = json.loads(one) movie = movies.filter_by(title=one["title"]).first() if not movie: movie = models.OnLineMovies() movie.title = one["title"] movie.url = one["url"] movie.language = one["language"] movie.director = one["director"] movie.img = one["img"] movie.description = one["description"] movie.actors = one["actors"] movie.duration = one["duration"] movie.rating = int(float(one["rating"]))*10 movie.subCategoryName = one["subCategoryName"] movie.releaseDate = one["releaseDate"] movie.ctime = one["ctime"] movie.area = one["area"] movie.tag = one["tag"] movie.subname = one["subname"] session.add(movie) session.commit()
def get_page_links1(webUrl): ''' Description: get images' first layer links ''' init_db() htmlContent = requests.get(webUrl, headers=headers) soup = BeautifulSoup(htmlContent.text, "html.parser") wp_page_numbers_div = soup.find("div", {"id":"wp_page_numbers"}) endPageTag = wp_page_numbers_div.find_all("a")[-1] endPageLink = endPageTag.get('href') if endPageLink: regex = r"(\D+\d+\D+)(\d+)(\D+)" m = re.match(regex, endPageLink) if m: pageNumber = int(m.groups()[1]) #get page number for index in xrange(1, pageNumber+1): pageLink = "%s"*4 %(webUrl, m.group(1), index, m.group(3)) #pageLinks.append(pageLink) page_link1_queue.put(pageLink) query = session.query(FirstLevelLinks) query_result = query.filter(FirstLevelLinks.url==pageLink).first() if query_result: continue else: first_level_links = FirstLevelLinks(url=pageLink) session.add(first_level_links) session.flush() session.commit() return page_link1_queue else: return None
def init_application(app, config): app.config.from_object(config) cqlengine = CQLEngine(app) init_db() user_datastore = CQLEngineUserDatastore(cqlengine, Users, Role) security = Security(app, user_datastore) app.logger.debug("Flask Application initialized")
def run_app(): app.config['SQLALCHEMY_DATABASE_URI'] = esi_config.database_url app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False with app.app_context(): db.init_app(app) init_db() initDbForE2e(wipe=False) app.run(host='localhost', port='8080')
def look_up(query): models.init_db() try: result = models.EnglishEntry.get(models.EnglishEntry.word == query.lower()) return result except: pass return None
def create_app(): app = Flask(__name__, static_folder=str(DIST_PATH / 'static'), template_folder=str(DIST_PATH)) cofigure_app(app) init_db(app) return app
def main(): init_db() for ranking in recent_rankings_for_entry("ユリカ"): print( ranking.rank, ranking.entry.name, ranking.ranking_log.created.isoformat(timespec='seconds'), )
def set_db(config): Base, db_session, engine = create_connection(config) Package, InstallMethod = register_models(Base) init_db(Base, engine) return Base, db_session, Package, InstallMethod @app.teardown_appcontext def shutdown_session(exception=None): db_session.remove()
def create_app(config_name='default'): app = Flask(__name__) app.config.from_object(config.config[config_name]) config.config[config_name].init_app(app) init_job(app) init_db(app) init_router(app) return app
def __init__(self, handlers=None, default_host='', transforms=None, **settings): engine = create_engine(options.db_url, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine)) self.googlemaps = google.AsyncClient(key=options.google_maps_api_key) super(Application, self).__init__( handlers=handlers, default_host=default_host, transforms=transforms, **settings)
def check_update(): checktime() stat = search("world") try: reques.worldstat() if reques.worldstat()["total_cases"] != stat[1]: init_db() except: print("Статистика не прийшла. ИСПРАВИТЬ НА ЛОГГИРОВАНИЕ") time.sleep(1800) check_update()
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), ] settings = dict(debug=options.debug, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def create_app(config): new_app = Flask(__name__) new_app.config.from_object(config) init_error_handler(new_app) init_db(new_app) init_jwt(new_app) register_config(new_app) register_users(new_app) register_folders(new_app) register_files(new_app) return new_app
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), ] settings = dict( debug=options.debug, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine( options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def main(do_states, do_countries): dbhost = os.getenv('POSTGRES_SERVICE_HOST', '127.0.0.1') dbuser = os.getenv('POSTGRES_USER', 'covid') dbpass = os.getenv('POSTGRES_PASSWORD', '') init_db(dbhost, dbuser, dbpass) db_session = session() if do_states: load_states(db_session) if do_countries: load_countries(db_session)
def main(): """ Main Entry function """ # Initialize the DB and delete any existing data models.init_db() utils.clear_dbs() utils.populate_inventory() # Gevent wsgi server with bottle as the wsgi app app.debug = True gevent.pywsgi.WSGIServer(('', 8088), app).serve_forever()
def __init__(self): handlers = [(r"/", UrlFetcher), (r"/admin/", WordsAdmin)] options = dict(static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), 'templates'), xsrf_cookies=True) tornado.web.Application.__init__(self, handlers, **options) engine = sa.create_engine(settings.SQLALCHEMY_DATABASE_URI, convert_unicode=True, echo=False) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def __init__(self): handlers = [url(r"/", IndexHandler, name="index")] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), "templates"), xsrf_cookies=True, # TODO Change this to a random string cookie_secret="nzjxcjasduuqwheazmu293nsadhaslzkci9023nsadnua9sdads/Vo=", ui_modules=uimodules, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def init_record(): init_db() init_record() # mnews.get_info() # crawl_news("http://www.solidot.org/story?sid=40747") # pool.wait() print "my source" News_source_m.print_all() print "error page" UnparsePage_m.print_all()
def __init__(self, handlers=None, default_host='', transforms=None, **settings): engine = create_engine(options.db_url, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine)) self.googlemaps = google.AsyncClient(key=options.google_maps_api_key) super(Application, self).__init__(handlers=handlers, default_host=default_host, transforms=transforms, **settings)
def add(): init_db() c1 = Customer('Anna', 'Smith', '*****@*****.**', datetime.datetime(1990, 5, 1)) c2 = Customer('John', 'Brown', '*****@*****.**', datetime.datetime(1992, 5, 1)) print(c1) a1 = Account(c1) a2 = Account(c2) db = DBSession().get() db.add(c1) db.add(c2) db.add(a1) db.add(a2) db.commit()
def main(): parse_command_line() app = tornado.web.Application( [ (r"/", MainHandler), (r"/migrate", MigrateHandler), (r"/predictions", RealtimeDepartureHandler), ], template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), ) app.listen(options.port) engine = create_engine(options.postgres_url, echo=False) app.Session = sessionmaker(bind=engine) tornado.ioloop.IOLoop.instance().start() models.init_db(engine)
def update_netease(): models.init_db() session = models.Session() news= session.query(models.EntertainmentNews) ret = netease.news(90) for one in ret: one = json.loads(one) new = news.filter_by(digest=one["digest"]).first() if not new: new = models.EntertainmentNews() new.title = one["title"] new.content = one["content"] new.photo = one["smallimg"] new.digest = one["digest"] new.time = one["time"] session.add(new) session.commit()
def look_up(query): models.init_db() try: result = models.EsperantoEntry.get(models.EsperantoEntry.word == query.lower()) return result except: pass try: result = models.EsperantoEntry.get(models.EsperantoEntry.word == get_root(query).lower()) return result except: pass try: result = models.EsperantoEntry.get(models.EsperantoEntry.word == get_infinitive(query).lower()) return result except: pass return None
def main(): loop = asyncio.get_event_loop() args = parse_args() setup_logging(args.debug) db = init_db(args.drop) app = init_app(db, loop=loop) logging.info('Starting app on port {}...'.format(settings.PORT)) web.run_app(app, port=settings.PORT) logging.info('Stopped.')
def database(): db = init_db(TestConfig) # Don't use `with db:` here. It opens a new transaction # which interferes with transactions in the actual code. with db.connection_context(): create_tables() yield db drop_tables()
def create(): origin_path = os.getcwd() try: tag = save_ma() tag.read() except: pass save_path = raw_input( "input you machine's save path (Example: /home/user/Document/) :") tag.save(save_path) try: os.makedirs(save_path) except OSError as e: if e.errno == 17: print('File exists, please continue') print('initialization is completed, put your dict.txt in %s' % save_path) models.init_db(save_path, origin_path) crawl()
def __init__(self): handlers = [ tornado.web.url(r'/jobs', JobsHandler, name='jobs'), ] settings = dict( debug=tornado.options.options.debug ) tornado.web.Application.__init__(self, handlers, **settings) # Configure the database engine = create_engine(tornado.options.options.db_path, convert_unicode=True, echo=tornado.options.options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine)) # Configure the scheduler scheduler = apscheduler.schedulers.tornado.TornadoScheduler(jobstores=JOBSTORES) # scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) scheduler.start() self.schdlr = scheduler
def __init__(self, dbname, host='localhost', port='5432', user='******', password='******'): self.student_id = init_db(dbname=dbname, host=host, port=port, user=user, password=password)
def make_app(): # Setup module-level logging log = logging.getLogger(__name__) # Allow log to show debug level messages logging.basicConfig(level=logging.DEBUG) # Create database object (see SQLAlchemy website for more information) engine = create_engine('sqlite:///:memory:', echo=False) # If you want to see messages in terminal, set "echo=True" init_db(engine) session = sessionmaker(bind=engine) db = session() # Create application object. Database and log are added as an argument in each handler to give it the option of # using it. In this project, they are not all used in each handler. return tornado.web.Application([ (r"/", MainHandler, dict(log=log, db=db)), (r"/login", LoginHandler, dict(log=log, db=db)), (r"/logout", LogoutHandler, dict(log=log, db=db)), (r"/login/google", GoogleLoginHandler, dict(log=log, db=db)), (r"/(.*)", MainHandler, dict(log=log, db=db)) ], **settings)
def make_app(): # Setup module-level logging log = logging.getLogger(__name__) # Allow log to show debug level messages logging.basicConfig(level=logging.DEBUG) # Create database object (see SQLAlchemy website for more information) engine = create_engine( 'sqlite:///:memory:', echo=False) # If you want to see messages in terminal, set "echo=True" init_db(engine) session = sessionmaker(bind=engine) db = session() # Create application object. Database and log are added as an argument in each handler to give it the option of # using it. In this project, they are not all used in each handler. return tornado.web.Application( [(r"/", MainHandler, dict(log=log, db=db)), (r"/login", LoginHandler, dict(log=log, db=db)), (r"/logout", LogoutHandler, dict(log=log, db=db)), (r"/login/google", GoogleLoginHandler, dict(log=log, db=db)), (r"/(.*)", MainHandler, dict(log=log, db=db))], **settings)
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), url(r'/index', IndexHandler, name='index2'), url(r'/about', AboutHandler, name='about'), url(r'/code', CodeHandler, name='code'), url(r'/resume', ResumeHandler, name='resume'), url(r'/blog', BlogHandler, name='blog'), ] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "../static"), template_path=os.path.join(os.path.dirname(__file__), '../views'), xsrf_cookies=True, # TODO Change this to a random string cookie_secret="nzjxcjasduuqwheazmu293nsadhaslzkci9023nsadnua9sdads/Vo=", ui_modules=uimodules, ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def __init__(self): handlers = [ url(r'/', IndexHandler, name='index'), url(r'/api/routes/([^/]+)/', APIRouteDetailsHandler, name='api:details') ] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), 'templates'), xsrf_cookies=False, cookie_secret="zGy9csABfiWpdsjxG2zJNMauaZMDyq", ui_modules=uimodules, ) tornado.web.Application.__init__(self, handlers, **settings) db_path = 'postgresql+psycopg2://%(db_user)s@localhost:%(db_port)s/%(db_name)s' % { 'db_user': options.db_user, 'db_name': options.db_name, 'db_port': options.db_port, } engine = create_engine(db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def create_app(): app = Flask(__name__) app.config.from_object(Config) app.jinja_env.globals['Category'] = Category app.jinja_env.globals['GETCATELIST'] = getCateList app.jinja_env.globals['GETFIDCATE'] = getFidCate app.jinja_env.globals['GETREARTICLE'] = getReArticle app.jinja_env.globals['GETCLICKARTICLE'] = getClickArticle '''blog模板''' app.register_blueprint(bdp) app.add_url_rule('/', endpoint='index') '''admin模块''' app.register_blueprint(adp) '''db数据库''' init_db(app) @app.errorhandler(404) def page_not_found(error): return render_template('admin/error.html'), 404 return app
def create_app(): """Create the Flask app instance that is used throughout the application. Returns: Application object (instance of flask.Flask). """ # Setup the Flask app and load the config. app = Flask(__name__) app.config[u'DEBUG'] = True app.config[u'SQLALCHEMY_DATABASE_URI'] = u'' # Setup the database. configure_engine(app.config[u'SQLALCHEMY_DATABASE_URI']) init_db() # Register blueprints. Blueprints are a way to organize Flask applications. # For more information: http://flask.pocoo.org/docs/latest/blueprints/ app.register_blueprint(turbineweb_views) # Setup CSRF protection for the whole application CsrfProtect(app) return app
def create_app(app_type, *args): app = Flask(__name__.split(".")[0]) if app_type == 'develop': app.config.from_object('config.DevelopmentConfig') elif app_type == 'test': app.config.from_object('config.TestingConfig') else: app.config.from_object('config.ProductionConfig') # Configure the DB to config file just loades import models models.init_db(app) # register the blueprints to the app import config for bp in config.REGISTERED_BLUEPRINTS: app.register_blueprint(bp) return app
def create_app(app_type): app = Flask(__name__.split(".")[0]) if app_type == 'develop': app.config.from_object('app.settings.DevelopmentConfig') elif app_type == 'test': app.config.from_object('app.settings.TestingConfig') else: app.config.from_object('app.settings.ProductionConfig') # Configure the DB to config file just loades import models models.init_db(app) # register the blueprints to the app from home import homebp app.register_blueprint(homebp) # from books import bookbp # app.register_blueprint(bookbp) return app
def __init__(self): handlers = [ url(r"/", IndexHandler, name='index'), url(r"/locations", LocationHandler, name='locations'), url(r"/locations/setup", LocationSetupHandler, name='location_setup'), url(r"/locations/add", LocationAddHandler, name='location_add'), url(r"/locations/remove", LocationRemoveHandler, name='location_remove'), url(r"/statistics", StatisticsHandler, name='statistics'), url(r"/demo", DemoHandler, name='demo'), url(r"/auth/create", AuthCreateHandler), url(r"/auth/login", AuthLoginHandler), url(r"/auth/logout", AuthLogoutHandler), url(r"/auth/profile", AuthProfileHandler), url(r'/ws', SocketHandler), url(r'/api', ApiHandler), ] settings = dict( debug=options.debug, static_path=os.path.join(os.path.dirname(__file__), "static"), template_path=os.path.join(os.path.dirname(__file__), 'templates'), xsrf_cookies=False, # TODO Change this to a random string cookie_secret="nzjxcjasduuqwheazmu=", ui_modules=uimodules, login_url="/auth/login", ) tornado.web.Application.__init__(self, handlers, **settings) engine = create_engine(options.db_path, convert_unicode=True, echo=options.debug) models.init_db(engine) self.db = scoped_session(sessionmaker(bind=engine))
def create_app(): app = Flask(__name__) app.config[ "SQLALCHEMY_DATABASE_URI"] = "mysql://*****:*****@localhost/flask_app" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True @app.route("/") def it_works(): if (environ["FLASK_ENV"] == "development"): return "<h1>It works!</h1>" else: abort(404) app.register_blueprint(user_blueprint, url_prefix="/api/users") app.register_blueprint(address_blueprint, url_prefix="/api/addresses") return init_db(app)
def main(): parser = ArgumentParser(description="Convert google books unigram list to database.") parser.add_argument( "--drivername", choices=[ "mysql", "postgresql", "sqlite", "access", "mssql", "oracle", "sybase", "drizzle", "firebird", "informix", "maxdb", ], default="sqlite", help="select database backend", ) parser.add_argument("--database", type=unicode, default=None, help="name of database") parser.add_argument("--host", type=unicode, default=None) parser.add_argument("--user", type=unicode, default=None) parser.add_argument("--password", type=unicode, default=None) parser.add_argument("--frequency", type=unicode, default=None, required=True, help="googlebooks 1-gram file") parser.add_argument("--total", type=unicode, default=None, required=True, help="googlebooks totalcounts") parser.add_argument("--port", type=int, default=0) parser.add_argument("--buffer", type=int, default=1024, help="number of lines processed at once") options = parser.parse_args() fname = options.frequency tname = options.total database = init_db(options) google_buffer_size = options.buffer cc = DatabaseConverter(UnigramFile(fname, google_buffer_size), TotalcountFile(tname), database) cc.convert()
bot.send_message(chat_id=user.telegram_id, text=f'Твой никнейм в телеграме: {message.from_user.username}') bot.send_message(chat_id=user.telegram_id, text=f'И ты утверждаешь, что тебя зовут {message.text}') bot.send_message(chat_id=user.telegram_id, text='Все верно?', reply_markup=register_keyboards) User.update(name=message.text).where(User.telegram_id == user_id).execute() @bot.callback_query_handler(func=lambda call: call.data == register_callbacks.get('OK')) def complete_register(call): user_id = call.message.chat.id user = User.get(telegram_id=user_id) user.update(reg_status=reg_statuses.get('complete')).execute() bot.send_message(chat_id=user.telegram_id, text='Вот и познакомились. Смотри что я умею!') @bot.callback_query_handler(func=lambda call: call.data == register_callbacks.get('NO')) def restart_register(call): user_id = call.message.chat.id user = User.get(telegram_id=user_id) user.update(name='') bot.send_message(chat_id=user.telegram_id, text='Как тебя зовут?') if __name__ == '__main__': init_db() bot.polling(none_stop=True)
# -*- coding: utf-8 -*- from flask import Flask, jsonify, request, render_template, abort, redirect from flask.ext.login import LoginManager, login_required from models import init_db, Guest app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://*****:*****@127.0.0.1:3306/ei" app.config['TRAP_BAD_REQUEST_ERRORS'] = True init_db(app) app.config.from_pyfile('config.py', silent=True) @app.route('/invite/<string:domain>/', methods=['GET', 'POST']) def index(domain): if not domain: abort(400) current_url = "http://{host}/invite/{domain}/".format(host=request.host, domain=domain) guest = Guest.query.filter_by(domain=domain).first() if not guest: return "没有找到这个叫{domain}的人".format(domain = domain) guest.scan = 1 guest.commit() return render_template('index.html', current_url=current_url, guest=guest, host=request.host)
def __init__(self): self.engine = create_engine('mysql://*****:*****@localhost:3306/dataservice?charset=utf8', convert_unicode=True, echo=True, pool_recycle=7200) self.engine.connect() models.init_db(self.engine)
#!/usr/bin/env python import os from flask import Flask, jsonify from flask.views import MethodView from mimerender_flask import mimerender from models import Parliamentary, init_db from lib.xmlutils import dict2xml app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(app.instance_path, 'api.db') app.debug=True db = init_db(app) class ParliamentariesAPI(MethodView): @mimerender( default='json', json=jsonify, xml=dict2xml, ) def get(self, **kwargs): return {'parliamentaries': map(Parliamentary.to_dict, Parliamentary.query.filter_by(**kwargs).all())} # def put(self, id, name): # p = Parliamentary(id=id, name=name) # db.session.add(p) # db.session.commit() # return "OK"
import requests from cStringIO import StringIO from datetime import datetime import pytz import time import os import models as m from session import session_scope from sqlalchemy.orm.exc import NoResultFound app = Flask(__name__) m.init_db() @app.route('/register-events', methods=["POST"]) def register_events(): """ Accepts new event data to be stored in the database, awaiting scheduling. """ data = request.get_json(force=True) # Save new event details and times to database with session_scope() as dbsession: conflicts = [ dbsession.query(m.EventTime) .filter(m.EventTime.key == tm['serverKey']).first()
from utils import * from models import init_db from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker if __name__ == "__main__": DB_CONNECT_STRING = 'mysql+pymysql://root:hillstone@localhost:3306/film?charset=utf8' engine = create_engine(DB_CONNECT_STRING, echo=True) init_db(engine) DB_Session = sessionmaker(bind=engine) session = DB_Session() url = "http://www.dy2018.com/i/98729.html" response = do_request(url) film = extract_details1(response, url) session.add(film) session.commit()
App init module """ from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask_wtf.csrf import CsrfProtect # Define global flask app object app = Flask(__name__) # Load values from config.py app.config.from_object('config') # Setup CSRF csrf = CsrfProtect() csrf.init_app(app) # Define global DB object db = SQLAlchemy(app) # Regster routes from views import mod_root app.register_blueprint(mod_root) # Create the DB models db.create_all() # Add default data from models import init_db init_db()
app.config['FLASKY_MAIL_SENDER'] = 'Prof. Sol Famida' print(app.config['SQLALCHEMY_DATABASE_URI']) from mail import init_mail mail = init_mail(app) from flask_bootstrap import Bootstrap Bootstrap(app) from admin import init_admin admin = init_admin(app) # ORM - Object Relational Mapping -Magico que se conecta a casi cualquiera base de datos. from models import init_db, User db = init_db(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) from flask_login import LoginManager login_manager = LoginManager() # Creando el objeto de la clase Login login_manager.init_app(app) # Asociando el login a la app login_manager.login_view = 'login' # Donde voy si no estoy loggeado @login_manager.user_loader def load_user(user_id): return User.query.get( user_id) # flask_login no tiene porque saber de la base de datos.
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker import models import time db_path = 'mysql://*****:*****@localhost:3306/dataservice?charset=utf8' engine = create_engine(db_path, convert_unicode=True, pool_recycle=7200) models.init_db(engine) engine.connect() db = scoped_session(sessionmaker(bind=engine)) def transfer_data(db,num): query = db.query(models.ListenLog) results = [] query_results = query.filter(models.ListenLog.song == None) for item in query_results[:num]: results.append(models.Listenlog_null(time = item.time, stationId = item.stationId, fingerPrint = item.fingurePrint)) db.add_all(results) db.commit() def transfer_data_op(db,num): query = db.query(models.ListenLog) query_results = query.filter(models.ListenLog.song == None) print "transfer_data start" count = 1 while True: print count t = time.time() results = [] for item in query_results[num*(count-1):num*count]: results.append(models.Listenlog_null(time = item.time, stationId = item.stationId, fingerPrint = item.fingurePrint)) db.add_all(results)
import json from flask import Flask, render_template, request, abort, jsonify, Response from flask_cache import Cache from models import init_db, User, Image, db import settings app = Flask(__name__) app.config.from_object(settings.Config) # 初始化db init_db(app) # 创建Cache对象 cache = Cache(app, config={ "CACHE_TYPE": 'redis', "CACHE_REDIS_HOST": '10.35.163.38', 'CACHE_REDIS_PORT': '6379', 'CACHE_REDIS_DB': 3, 'CACHE_KEY_PREFIX': 'music_cache' }) @app.before_request def descrapy(): print('---请求前---', request.url, request.remote_addr) print('浏览器名称:', request.user_agent) # 客户端代理器 print('请求资源:', request.path)
return jsonify(error="No user logged in on device {}".format(identifier)), 400 user = User.query.get(device.user_id) if not user.is_checked_in: user_images = user.images() recognizer.update(np.asarray(user_images), np.asarray(len(user_images) * [user.id])) user.is_checked_in = True db.session.commit() return jsonify(error=None,email=user.email), 200 @app.route('/recognize', methods=['POST']) def recognize(): temp = tempfile.NamedTemporaryFile(suffix='.jpg') request.files['capture.jpg'].save(temp) temp.flush() image = cv2.imread(temp.name, cv2.CV_LOAD_IMAGE_GRAYSCALE) face = faceutil.largest_face(image)[0] if face.size: prediction = recognizer.predict(cv2.resize(face, app.config['TRAIN_SIZE'])) return jsonify(email=User.query.get(prediction[0]).email, confidence=prediction[1], error=None), 200 else: return jsonify(email=None, confidence=None, error="No face detected in image"), 400 if __name__ == '__main__': import os if not os.path.exists(app.config['DATA_DIR']): from models import init_db with app.app_context(): init_db(traindir=app.config['TRAIN_DIR']) app.run(host='0.0.0.0')