def create_app( frigate_config, database: SqliteDatabase, stats_tracking, detected_frames_processor, mqtt_client, ): app = Flask(__name__) sockets = Sockets(app) @app.before_request def _db_connect(): database.connect() @app.teardown_request def _db_close(exc): if not database.is_closed(): database.close() app.frigate_config = frigate_config app.stats_tracking = stats_tracking app.detected_frames_processor = detected_frames_processor app.register_blueprint(bp) sockets.register_blueprint(ws) app.mqtt_backend = MqttBackend(mqtt_client, frigate_config.mqtt.topic_prefix) app.mqtt_backend.start() return app
def create_app(self, testing): self.app = Flask("fastlane") self.testing = testing self.app.testing = testing self.app.config.from_object(rq_dashboard.default_settings) self.app.error_handlers = [] for key in self.config.items.keys(): self.app.config[key] = self.config[key] self.app.config.DEBUG = self.config.DEBUG self.app.config.ENV = self.config.ENV self.app.original_config = self.config self.app.log_level = self.log_level self.configure_logging() self.connect_redis() self.connect_queue() self.connect_db() self.load_executor() self.load_error_handlers() metrics.init_app(self.app) self.app.register_blueprint(metrics.bp) self.app.register_blueprint(healthcheck) self.app.register_blueprint(enqueue) self.app.register_blueprint(task_api) self.app.register_blueprint(status) self.app.register_blueprint(gzipped.bp) gzipped.init_app(self.app) sockets = Sockets(self.app) sockets.register_blueprint(stream)
def init_websockets(sockets: Sockets): # ip 访问频率限制(防破解) # TODO 这个好像没用,大概是因为这边的路由并不是由 app 处理的? limiter.limit("600/day;100/hour;1/minute;1/second")(bot_bp) # 将 flask_sockets 的 blueprint 注册到 sockets 实例 sockets.register_blueprint(bot_bp)
def create_app(test_config=None): # create and configure the app app = Flask(__name__, instance_relative_config=True) app.config.from_mapping( SECRET_KEY='dev', DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'), ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile('config.py', silent=True) else: # load the test config if passed in app.config.from_mapping(test_config) # ensure the instance folder exists try: os.makedirs(app.instance_path) except OSError: pass os.environ['GIT_TERMINAL_PROMPT'] = '0' from . import extractor app.register_blueprint(extractor.bp) sockets_app = Sockets(app) sockets_app.register_blueprint(extractor.ws) return app
def create_app(debug=False, secret_key=DEFAULT_SECRET_KEY, db_config=None) -> Flask: """Create Flask app. Args: debug (bool): Enable debug mode secret_key (str): Secret key application db_config (Union[None, dict]): Database configuration Returns: app (Flask): flask application """ app = Flask(__name__) app.debug = debug app.config["SECRET_KEY"] = secret_key # Global socket handler sockets = Sockets(app) app.register_blueprint(http, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") # Set SQLAlchemy configs global db set_database_config(app, db_config=db_config) s = app.app_context().push() db.create_all() db.session.commit() return app
def register_blueprints(app): from .handlers import front, course, admin, live, ws app.register_blueprint(front) app.register_blueprint(course) app.register_blueprint(admin) app.register_blueprint(live) sockets = Sockets(app) sockets.register_blueprint(ws)
def register_blueprints(app): app.register_blueprint(front) app.register_blueprint(course) app.register_blueprint(admin) app.register_blueprint(user) app.register_blueprint(live) sockets = Sockets(app) sockets.register_blueprint(ws)
def bootstrap(): # setup logging coloredlogs.install(level=logging.DEBUG) logger.info("Bootstrapping app...") app = Flask(__name__) cors = CORS(app, resources={"*": {"origins": "*"}}) # enable cross-origin resource sharing logger.info("Loading config...") app.config.from_object('config.default') if os.environ.get("ENV", "").upper() == "PROD": app.config.from_object('config.prod') sockets = Sockets(app) @app.route('/') def hello_world(): return 'This is BFAF' @app.errorhandler(ServiceException) def service_error(error): return jsonify({ "message": "Error from a dependent service: type={} {}" .format(error.__class__.__name__, str(error)) }), 500 # register HTTP blueprints from endpoints.rest.init import init_blueprint app.register_blueprint(init_blueprint, url_prefix='/init') from endpoints.rest.transaction import transaction_blueprint app.register_blueprint(transaction_blueprint, url_prefix='/transaction') # register WebSockets blueprints from endpoints.websockets.updates import updates_blueprint sockets.register_blueprint(updates_blueprint, url_prefix='/updates') # set up background thread @app.before_first_request def set_up_poller_thread(): logger.info("Setting up poller thread...") from endpoints.websockets.poller import NewInfoPollerThread app.poller_thread = NewInfoPollerThread(app) app.poller_thread.start() @atexit.register def close_poller_thread(): logger.warning("Exiting... cleaning up poller thread.") app.poller_thread.exit = True app.poller_thread.join(timeout=3000) logger.info("Poller thread cleaned up.") app.close_poller_thread = close_poller_thread return app
def run_ws(port): from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler current_sockets = Sockets(app) current_sockets.register_blueprint(voro_sockets) server = pywsgi.WSGIServer(('', port), app, handler_class=WebSocketHandler) server.serve_forever()
def create_app(node_id: str, debug=False, n_replica=None, test_config=None) -> Flask: """Create flask application. Args: node_id: ID used to identify this node. debug: debug mode flag. n_replica: Number of model replicas used for fault tolerance purposes. test_config: database test settings. Returns: app : Flask App instance. """ app = Flask(__name__) app.debug = debug app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", None) if app.config["SECRET_KEY"] is None: app.config["SECRET_KEY"] = DEFAULT_SECRET_KEY logging.warning( "Using default secrect key, this is not safe and should be used only for testing and development. To define a secrete key please define the environment variable SECRET_KEY." ) app.config["N_REPLICA"] = n_replica sockets = Sockets(app) # Register app blueprints from .main import main, ws, local_worker, auth, hook # set_node_id(id) local_worker.id = node_id hook.local_worker._known_workers[node_id] = local_worker local_worker.add_worker(hook.local_worker) app.register_blueprint(main, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") # Set SQLAlchemy configs set_database_config(app, test_config=test_config) s = app.app_context().push() db.create_all() db.session.commit() # Set Authentication configs app = auth.set_auth_configs(app) CORS(app) # Threads executor.init_app(app) app.config["EXECUTOR_PROPAGATE_EXCEPTIONS"] = True app.config["EXECUTOR_TYPE"] = "thread" return app
def create_app(port): sockets = Sockets(server) http_server = WSGIServer(('', port), server, handler_class=WebSocketHandler, environ=geventOpt) from robot_ws_control.controllers import server as server_ws sockets.register_blueprint(server_ws) return http_server
def register_blueprints(app): from .handlers import front, course, admin, ws, live app.register_blueprint(front) app.register_blueprint(course) app.register_blueprint(admin) app.register_blueprint(live) # flask-sockets支持为Websockets注册蓝图 sockets = Sockets(app) sockets.register_blueprint(ws)
def create_domain_app(app, args, testing=False): test_config = None if args.start_local_db: test_config = {"SQLALCHEMY_DATABASE_URI": "sqlite:///nodedatabase.db"} # Bind websocket in Flask app instance sockets = Sockets(app) # Register HTTP blueprints # Here you should add all the blueprints related to HTTP routes. app.register_blueprint(roles_blueprint, url_prefix=r"/roles") app.register_blueprint(users_blueprint, url_prefix=r"/users") app.register_blueprint(setup_blueprint, url_prefix=r"/setup/") app.register_blueprint(groups_blueprint, url_prefix=r"/groups") app.register_blueprint(dcfl_blueprint, url_prefix=r"/data-centric/") app.register_blueprint(mcfl_blueprint, url_prefix=r"/model-centric/") app.register_blueprint(root_blueprint, url_prefix=r"/") app.register_blueprint(association_requests_blueprint, url_prefix=r"/association-requests/") # Register WebSocket blueprints # Here you should add all the blueprints related to WebSocket routes. sockets.register_blueprint(ws, url_prefix=r"/") from .database import db, set_database_config, seed_db, User, Role global node node = GridDomain(name=args.name) # Set SQLAlchemy configs set_database_config(app, test_config=test_config) s = app.app_context().push() db.create_all() if not testing: if len(db.session.query(Role).all()) == 0: seed_db() role = db.session.query(Role.id).filter_by(name="Owner").first() user = User.query.filter_by(role=role.id).first() if user: signing_key = SigningKey(user.private_key.encode("utf-8"), encoder=HexEncoder) node.signing_key = signing_key node.verify_key = node.signing_key.verify_key node.root_verify_key = node.verify_key db.session.commit() app.config["EXECUTOR_PROPAGATE_EXCEPTIONS"] = True app.config["EXECUTOR_TYPE"] = "thread" executor.init_app(app) return app
def create_app(self, testing): self.app = Flask("fastlane") self.testing = testing self.app.testing = testing self.app.error_handlers = [] for key in self.config.items.keys(): self.app.config[key] = self.config[key] self.app.config["ENV"] = self.config.ENV self.app.config["DEBUG"] = self.config.DEBUG self.app.original_config = self.config self.app.log_level = self.log_level self.configure_logging() self.connect_redis() self.configure_queue() # self.connect_queue() self.config_blacklist_words_fn() self.configure_basic_auth() self.connect_db() self.load_executor() self.load_error_handlers() enable_cors = self.app.config["ENABLE_CORS"] if (isinstance(enable_cors, (str, bytes)) and enable_cors.lower() == "true") or (isinstance(enable_cors, (bool)) and enable_cors): origin = self.app.config["CORS_ORIGINS"] self.app.logger.info( f"Configured CORS to allow access from '{origin}'.") CORS(self.app) metrics.init_app(self.app) self.app.register_blueprint(metrics.bp) self.app.register_blueprint(healthcheck) self.app.register_blueprint(enqueue) self.app.register_blueprint(task_api) self.app.register_blueprint(execution_api) self.app.register_blueprint(status) self.app.register_blueprint(routes_api) self.app.register_blueprint(gzipped.bp) gzipped.init_app(self.app) sockets = Sockets(self.app) sockets.register_blueprint(stream)
def register_extensions(app): db.init_app(app) Migrate(app, db) login_manager = LoginManager() login_manager.init_app(app) sockets = Sockets(app) sockets.register_blueprint(ws) @login_manager.user_loader def user_loader(id): return User.query.get(id) login_manager.login_view = 'front.login' login_manager.login_message = '请先登录' login_manager.login_message_category = 'danger'
def register_blueprints(app): """注册蓝图 """ for bp in bp_list: app.register_blueprint(bp) # 将应用对象作为参数创建套接字对象 # 这里会调用套接字对象的 init_app 方法将应用对象的核心方法 wsgi_app # 替换成 SocketMiddleware 类的实例,该类也定义在 flask_sockets 模块中 # 当客户端的请求进来之后,会调用应用对象的 wsgi_app 方法 # 其实就是调用 SocketMiddleware 实例的 __call__ 方法 sockets = Sockets(app) # 注册蓝图,此方法会调用蓝图对象自身的 register 方法 # 通常情况下,调用蓝图自身的 register 方法时 app 参数值是应用对象 # 但这里的 register_blueprint 方法会将套接字对象作为 app 参数值 # 也就是蓝图中的视图函数会在套接字对象中备案 sockets.register_blueprint(ws)
def create_app(debug=False, secret_key=DEFAULT_SECRET_KEY, db_config=None): app = Flask(__name__) app.debug = debug app.config["SECRET_KEY"] = secret_key # Global socket handler sockets = Sockets(app) app.register_blueprint(http, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") # Set SQLAlchemy configs global db set_database_config(app, db_config=db_config) s = app.app_context().push() db.create_all() db.session.commit() return app
def create_app(node_id, debug=False, database_url=None): """ Create / Configure flask socket application instance. Args: node_id (str) : ID of Grid Node. debug (bool) : debug flag. test_config (bool) : Mock database environment. Returns: app : Flask application instance. """ app = Flask(__name__) app.debug = debug app.config["SECRET_KEY"] = "justasecretkeythatishouldputhere" # Enable persistent mode # Overwrite syft.object_storage methods to work in a persistent way # Persist models / tensors if database_url: app.config["REDISCLOUD_URL"] = database_url from .main.persistence import database, object_storage db_instance = database.set_db_instance(database_url) object_storage.set_persistent_mode(db_instance) from .main import html, ws, hook, local_worker, auth # Global socket handler sockets = Sockets(app) # set_node_id(id) local_worker.id = node_id hook.local_worker._known_workers[node_id] = local_worker local_worker.add_worker(hook.local_worker) # Register app blueprints app.register_blueprint(html, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") # Set Authentication configs app = auth.set_auth_configs(app) return app
def create_app(config_name): """ Factory function for creating and configuring a Flask object based on the provided configuration name. Raise a ConfigError exception if invalid configuration name specified. """ app = Flask('server', static_url_path='', static_folder='../webapp') try: app.config.from_object(config_lookup[config_name]) except KeyError as e: raise ConfigError(e) logging.basicConfig(level=app.config['LOGGING']) @app.route(app.static_url_path or '/') def index(): return app.send_static_file('index.html') sockets = Sockets(app) sockets.register_blueprint(realtime, url_prefix='/api/telemetry') return app
def create_app(node_id, debug=False, test_config=None): """ Create / Configure flask socket application instance. Args: node_id (str) : ID of Grid Node. debug (bool) : debug flag. test_config (bool) : Mock database environment. Returns: app : Flask application instance. """ app = Flask(__name__) app.debug = debug app.config["SECRET_KEY"] = "justasecretkeythatishouldputhere" from .main import html, ws, db, hook, local_worker, auth from .main.persistence.utils import set_database_config global db sockets = Sockets(app) # set_node_id(id) local_worker.id = node_id hook.local_worker._known_workers[node_id] = local_worker # Register app blueprints app.register_blueprint(html, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") # Set Authentication configs app = auth.set_auth_configs(app) # Set SQLAlchemy configs app = set_database_config(app, test_config=test_config) s = app.app_context().push() db.create_all() return app
def app(prefix='/jupyter', app=None): kernel = FlaskKernel.instance() app = app or Flask(__name__) @app.template_filter() def ipywidget_view(widget): from jinja2 import Markup import json return Markup( """<script type="application/vnd.jupyter.widget-view+json">%s</script>""" % json.dumps(widget.get_view_spec())) @app.template_filter() def ipywidget_state(widgets): from jinja2 import Markup from ipywidgets import embed as wembed drop_defaults = True state = wembed.dependency_state(widgets, drop_defaults=drop_defaults) from ipywidgets import Widget json_data = Widget.get_manager_state(widgets=[]) json_data['state'] = state json_data_str = json.dumps(json_data, indent=' ') snippet = wembed.snippet_template.format(load='', widget_views='', json_data=json_data_str) return Markup(snippet) @app.route('/static/<path:path>') def send_js(path): app.logger.debug("serve static file: static/{}".format(path)) return send_from_directory('static', path) sockets = Sockets(app) app.register_blueprint(http, url_prefix=prefix) sockets.register_blueprint(websocket, url_prefix=prefix) return app
from flask import Flask from flask_breadcrumbs import Breadcrumbs, default_breadcrumb_root from flask_sockets import Sockets from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler from webpsi.views import home, classic_reg, singlebit_pk app = Flask(__name__) sockets = Sockets(app) Breadcrumbs(app) default_breadcrumb_root(home.blueprint, '.') app.register_blueprint(home.blueprint) app.register_blueprint(classic_reg.blueprint, url_prefix='/classic_reg') sockets.register_blueprint(classic_reg.ws_blueprint, url_prefix='/classic_reg') app.register_blueprint(singlebit_pk.blueprint, url_prefix='/singlebit_pk') sockets.register_blueprint(singlebit_pk.ws_blueprint, url_prefix='/singlebit_pk') server = pywsgi.WSGIServer(('0.0.0.0', 58700), application=app, handler_class=WebSocketHandler) server.serve_forever() app.run(host='0.0.0.0', port=58700)
operating_system = str(platform.system()).lower() app = Flask(__name__, static_folder="static", template_folder="templates") CORS(app) # Disables caching for each flair app that uses PyWebView app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 1 # Registers webview API's under /webview/<api-name> to keep code separate and clean app.register_blueprint(server_bp, url_prefix='/server_bp') ws = Sockets(app) ws.register_blueprint(server_ws, url_prefix='/server_ws') @app.after_request def add_header(response): """ Disables caching for each flair app that uses PyWebView """ response.headers['Cache-Control'] = 'no-store' return response @app.route("/") def home(): """ Templates should be stored inside templates folder
def ApiApp(trustlines, *, enabled_apis): app = Flask(__name__) app.register_error_handler(Exception, handle_error) sockets = Sockets(app) Api(app, catch_all_404s=True) CORS(app, send_wildcard=True) api_bp = Blueprint("api", __name__, url_prefix="/api/v1") sockets_bp = Blueprint("api", __name__, url_prefix="/api/v1/streams") api = Api(api_bp) def add_resource(resource, url): api.add_resource(resource, url, resource_class_args=[trustlines]) # Always enabled api.add_resource(Version, "/version") add_resource(Block, "/blocknumber") if ApiType.STATUS in enabled_apis: add_resource(NetworkList, "/networks") add_resource(Network, "/networks/<address:network_address>") add_resource(UserList, "/networks/<address:network_address>/users") add_resource( NetworkTrustlinesList, "/networks/<address:network_address>/trustlines" ) add_resource(EventsNetwork, "/networks/<address:network_address>/events") add_resource( UserAccruedInterestList, "/networks/<address:network_address>/users/<address:user_address>/interests", ) add_resource( TrustlineAccruedInterestList, "/networks/<address:network_address>/users/<address:user_address>/" "interests/<address:counterparty_address>", ) add_resource(TransferInformation, "/transfers") add_resource(AppliedDelegationFees, "/delegation-fees/") add_resource( User, "/networks/<address:network_address>/users/<address:user_address>" ) add_resource( ContactList, "/networks/<address:network_address>/users/<address:user_address>/contacts", ) add_resource( TrustlineList, "/networks/<address:network_address>/users/<address:user_address>/trustlines", ) add_resource( Trustline, "/networks/<address:network_address>/users/<address:a_address>/trustlines/<address:b_address>", ) add_resource( TrustlineEvents, "/networks/<address:network_address>/users/<address:user_address>" "/trustlines/<address:counter_party_address>/events", ) add_resource( UserEventsNetwork, "/networks/<address:network_address>/users/<address:user_address>/events", ) add_resource(UserEvents, "/users/<address:user_address>/events") add_resource(TransactionInfos, "/users/<address:user_address>/txinfos") add_resource(Balance, "/users/<address:user_address>/balance") add_resource(UserTrustlines, "/users/<address:user_address>/trustlines") api_bp.add_url_rule( "/networks/<address:network_address>/image", view_func=GraphImage.as_view("image", trustlines), ) api_bp.add_url_rule( "/networks/<address:network_address>/dump", view_func=GraphDump.as_view("dump", trustlines), ) sockets_bp.add_url_rule( "/events", "stream", view_func=WebSocketRPCHandler(trustlines) ) if ApiType.PATHFINDING in enabled_apis: add_resource( MaxCapacityPath, "/networks/<address:network_address>/max-capacity-path-info", ) add_resource(Path, "/networks/<address:network_address>/path-info") add_resource( CloseTrustline, "/networks/<address:network_address>/close-trustline-path-info", ) if ApiType.RELAY in enabled_apis: add_resource(Relay, "/relay") add_resource( TransactionStatus, "/transactions/<string:transaction_hash>/status" ) if ApiType.DELEGATE in enabled_apis: add_resource(RelayMetaTransaction, "/relay-meta-transaction") add_resource( Status, "/identities/<address:identity_address>/meta-transactions/<string:meta_transaction_hash>/status", ) add_resource(MetaTransactionFees, "/meta-transaction-fees") add_resource(IdentityInfos, "/identities/<address:identity_address>") add_resource(Factories, "/factories") if trustlines.enable_deploy_identity: add_resource(DeployIdentity, "/identities") if ApiType.FAUCET in enabled_apis: add_resource(RequestEther, "/request-ether") if ApiType.EXCHANGE in enabled_apis: add_resource(OrderBook, "/exchange/orderbook") add_resource(Orders, "/exchange/orders") add_resource(OrderSubmission, "/exchange/order") add_resource(ExchangeAddresses, "/exchange/exchanges") add_resource(UnwEthAddresses, "/exchange/eth") add_resource(OrderDetail, "/exchange/order/<string:order_hash>") add_resource( UserEventsExchange, "/exchange/<address:exchange_address>/users/<address:user_address>/events", ) add_resource( UserEventsAllExchanges, "/exchange/users/<address:user_address>/events" ) add_resource(EventsExchange, "/exchange/<address:exchange_address>/events") add_resource(TokenAddresses, "/tokens") add_resource(EventsToken, "/tokens/<address:token_address>/events") add_resource( TokenBalance, "/tokens/<address:token_address>/users/<address:user_address>/balance", ) add_resource( UserEventsToken, "/tokens/<address:token_address>/users/<address:user_address>/events", ) if ApiType.MESSAGING in enabled_apis: add_resource(PostMessage, "/messages/<address:user_address>") sockets_bp.add_url_rule( "/messages", "stream", view_func=MessagingWebSocketRPCHandler(trustlines) ) if ApiType.PUSH_NOTIFICATION in enabled_apis: add_resource( AddClientToken, "/pushnotifications/<address:user_address>/token/<string:client_token>", ) add_resource( DeleteClientToken, "/pushnotifications/<address:user_address>/token/<string:client_token>", ) app.url_map.converters["address"] = AddressConverter app.register_blueprint(api_bp) sockets.register_blueprint(sockets_bp) return app
# -*- coding:utf-8 -*- # @Time : 12/6/19 11:35 PM # @Author : Kayb from flask import Flask from flask_sockets import Sockets app = Flask(__name__) socket_app = Sockets(app) from apps import apps_bp, ws_bp app.register_blueprint(apps_bp) socket_app.register_blueprint(ws_bp) if __name__ == '__main__': from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('0.0.0.0', 5000), app, handler_class=WebSocketHandler) print('server start') server.serve_forever()
#office #app.config['SQLALCHEMY_DATABASE_URI']= 'postgresql://*****:*****@localhost:5432/loopme' #home #app.config['SQLALCHEMY_DATABASE_URI']= 'postgresql://*****:*****@localhost:5432/postgres' #production app.config['SQLALCHEMY_DATABASE_URI']= 'postgresql://*****:*****@ec2-174-129-29-118.compute-1.amazonaws.com:5432/dfini92nqen64n' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.secret_key = 'some_secret' db = SQLAlchemy(app) print "db created" """Create Database migrations""" migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) print "db migrated" from router import router, ws app.register_blueprint(router) sockets = Sockets(app) sockets.register_blueprint(ws) #@app.route('/') #def root(): # return app.send_static_file('index.html')
import webassets.filter import operator import sys import requests import os.path import re import random _paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}') re_qid = re.compile('^(Q\d+)$') app = Flask(__name__) app.register_blueprint(matcher_blueprint) sockets = Sockets(app) sockets.register_blueprint(ws) init_pager(app) env = flask_assets.Environment(app) app.register_blueprint(social_auth) login_manager = LoginManager(app) login_manager.login_view = 'login_route' cat_to_ending = None osm_api_base = 'https://api.openstreetmap.org/api/0.6' really_save = True region = make_region().configure('dogpile.cache.pylibmc', expiration_time=3600, arguments={'url': ["127.0.0.1"]}) navbar_pages = {
def init_ws(app): sockets = Sockets(app) sockets.register_blueprint(ws_blueprint, url_prefix=r'/')
def ApiApp(trustlines): app = Flask(__name__) app.register_error_handler(Exception, handle_error) sockets = Sockets(app) Api(app, catch_all_404s=True) CORS(app, send_wildcard=True) api_bp = Blueprint("api", __name__, url_prefix="/api/v1") sockets_bp = Blueprint("api", __name__, url_prefix="/api/v1/streams") api = Api(api_bp) def add_resource(resource, url): api.add_resource(resource, url, resource_class_args=[trustlines]) api.add_resource(Version, "/version") add_resource(NetworkList, "/networks") add_resource(Network, "/networks/<address:network_address>") add_resource(UserList, "/networks/<address:network_address>/users") add_resource(EventsNetwork, "/networks/<address:network_address>/events") add_resource( User, "/networks/<address:network_address>/users/<address:user_address>") add_resource( ContactList, "/networks/<address:network_address>/users/<address:user_address>/contacts", ) add_resource( TrustlineList, "/networks/<address:network_address>/users/<address:user_address>/trustlines", ) add_resource( Trustline, "/networks/<address:network_address>/users/<address:a_address>/trustlines/<address:b_address>", ) add_resource(MaxCapacityPath, "/networks/<address:network_address>/max-capacity-path-info") add_resource( UserEventsNetwork, "/networks/<address:network_address>/users/<address:user_address>/events", ) add_resource(Path, "/networks/<address:network_address>/path-info") add_resource( CloseTrustline, "/networks/<address:network_address>/close-trustline-path-info") add_resource(UserEvents, "/users/<address:user_address>/events") add_resource(TransactionInfos, "/users/<address:user_address>/txinfos") add_resource(Balance, "/users/<address:user_address>/balance") add_resource(Block, "/blocknumber") add_resource(Relay, "/relay") if trustlines.enable_relay_meta_transaction: add_resource(RelayMetaTransaction, "/relay-meta-transaction") add_resource(MetaTransactionFees, "/meta-transaction-fees") if trustlines.enable_ether_faucet: add_resource(RequestEther, "/request-ether") if trustlines.enable_deploy_identity: add_resource(DeployIdentity, "/identities") add_resource(IdentityInfos, "/identities/<address:identity_address>") add_resource(Factories, "/factories") add_resource(OrderBook, "/exchange/orderbook") add_resource(Orders, "/exchange/orders") add_resource(OrderSubmission, "/exchange/order") add_resource(ExchangeAddresses, "/exchange/exchanges") add_resource(UnwEthAddresses, "/exchange/eth") add_resource(OrderDetail, "/exchange/order/<string:order_hash>") add_resource( UserEventsExchange, "/exchange/<address:exchange_address>/users/<address:user_address>/events", ) add_resource(UserEventsAllExchanges, "/exchange/users/<address:user_address>/events") add_resource(EventsExchange, "/exchange/<address:exchange_address>/events") add_resource(TokenAddresses, "/tokens") add_resource(EventsToken, "/tokens/<address:token_address>/events") add_resource( TokenBalance, "/tokens/<address:token_address>/users/<address:user_address>/balance", ) add_resource( UserEventsToken, "/tokens/<address:token_address>/users/<address:user_address>/events", ) add_resource(PostMessage, "/messages/<address:user_address>") add_resource( AddClientToken, "/pushnotifications/<address:user_address>/token/<string:client_token>", ) add_resource( DeleteClientToken, "/pushnotifications/<address:user_address>/token/<string:client_token>", ) api_bp.add_url_rule( "/networks/<address:network_address>/image", view_func=GraphImage.as_view("image", trustlines), ) api_bp.add_url_rule( "/networks/<address:network_address>/dump", view_func=GraphDump.as_view("dump", trustlines), ) sockets_bp.add_url_rule("/events", "stream", view_func=WebSocketRPCHandler(trustlines)) sockets_bp.add_url_rule("/messages", "stream", view_func=MessagingWebSocketRPCHandler(trustlines)) app.url_map.converters["address"] = AddressConverter app.register_blueprint(api_bp) sockets.register_blueprint(sockets_bp) return app
config_file = path.join(SCRIPT_DIR, 'data', 'config.json') if path.exists(config_file): with open(config_file, 'r') as f: CONFIG.update(json.load(f)) with open(path.join(SCRIPT_DIR, 'data', 'game-types.json')) as f: game_types = json.load(f) for game_type_name, game_type_config in game_types.items(): game_type_config = json.dumps(game_type_config) game_type = GameType.query.filter_by(name=game_type_name).first() if game_type is None: game_type = GameType(name=game_type_name, config=game_type_config) db.session.add(game_type) else: game_type.config = game_type_config db.session.commit() server = pywsgi.WSGIServer((CONFIG['host'], CONFIG['port']), app, handler_class=WebSocketHandler) print('up and running') server.serve_forever() app.register_blueprint(html, url_prefix=r'/') sockets.register_blueprint(soc, url_prefix=r'/') if __name__ == '__main__': main()
@html.route("/") def hello(): return "Try and add a table id to connect to this server!" @html.route("/create-cambio-table", methods=["POST"]) def create_new_table(): pass @ws.route("/echo") def echo_socket(socket): while not socket.closed: message = socket.receive() socket.send(message) app = Flask(__name__) sockets = Sockets(app) app.register_blueprint(html, url_prefix=r"/") sockets.register_blueprint(ws, url_prefix=r"/") if __name__ == "__main__": from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(("", 5000), app, handler_class=WebSocketHandler) server.serve_forever()