def open(self, link_uuid): """他のCircleCoreから接続された際に呼ばれる.""" logger.debug('%s Connected from slave CircleCore', link_uuid) self.link_uuid = link_uuid self.replication_link = ReplicationLink.query.get(link_uuid) if not self.replication_link: logger.warning( 'ReplicationLink %s was not found. Connection close.', link_uuid) self.close( code=WebsocketStatusCode.NOT_FOUND.value, reason='ReplicationLink {} was not found.'.format(link_uuid)) return database = self.get_core().get_database() self.state = ReplicationState.HANDSHAKING self.sync_states = ImmutableDict( (box.uuid, SyncState(box, database.get_latest_primary_key(box))) for box in self.replication_link.message_boxes) self.syncing = False logger.debug('initial sync status: %s', self.sync_states) # messageに関するイベントを監視する self.receiver = self.get_core().make_hub_receiver(make_message_topic()) self.receiver.register_ioloop(self.on_new_message)
def client_alias(alias_name): ''' client alias repointing address ''' raw_aliases = config_var('screens.aliases', []) aliases = {} for alias in raw_aliases: aliases[alias['name']] = alias if alias_name in aliases: alias = aliases[alias_name] # This is very ugly, and could certainly be improved, # but it works for now: details = [] if alias.get('forceaspect', None): details.append(('forceaspect', alias['forceaspect'])) if alias.get('forcetop', None) != None: details.append(('forcetop', alias['forcetop'])) if alias.get('fadetime', None) != None: details.append(('fadetime', alias['fadetime'])) if alias.get('scrollspeed', None): details.append(('scrollspeed', alias['scrollspeed'])) request.args = ImmutableDict(**dict(details + request.args.items())) return screendisplay(alias['screen_type'], alias['screen_name']) else: return ('<!doctype html><html><body><h1>Screen Alias not found.</h1>' '<p>Sorry...</p><script>' 'setTimeout(function(){' ' document.location.reload(true);}, 10000);' '</script></body></html>')
class Server(flask.Flask): jinja_options = ImmutableDict(flask.Flask.jinja_options.items() + [('bytecode_cache', MemoryBytecodeCache())]) @cached_property def jinja_loader(self): return FileSystemLoaderEx(os.path.join(self.root_path, 'templates'))
def activities(self): """A immutable dict of all the user's activities by lang.""" if not hasattr(self, '_activity_cache'): self._activity_cache = d = {} activities = _UserActivity.query.filter_by(user=self).all() for activity in activities: d[activity.locale] = activity return ImmutableDict(self._activity_cache)
class FlaskWithHamlish(Flask): jinja_options = ImmutableDict( extensions = [ 'jinja2.ext.autoescape', 'jinja2.ext.with_', HamlishExtension, ] )
class Hamlisk(Flask): "Flask, but with HAMLish" jinja_options = ImmutableDict( extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_', 'hamlish_jinja.HamlishExtension'] ) def __init__(self): Flask.__init__(self, __name__)
class Config(BundleConfig): """ Default configuration options for the Babel Bundle. """ LANGUAGES = ['en'] """ The language codes supported by the app. """ BABEL_DEFAULT_LOCALE = 'en' """ The default language to use if none is specified by the client's browser. """ BABEL_DEFAULT_TIMEZONE = 'UTC' """ The default timezone to use. """ DEFAULT_DOMAIN = Domain() """ The default :class:`~flask_babelex.Domain` to use. """ DATE_FORMATS = ImmutableDict({ 'time': 'medium', 'date': 'medium', 'datetime': 'medium', 'time.short': None, 'time.medium': None, 'time.full': None, 'time.long': None, 'date.short': None, 'date.medium': None, 'date.full': None, 'date.long': None, 'datetime.short': None, 'datetime.medium': None, 'datetime.full': None, 'datetime.long': None, }) """ A dictionary of date formats. """ ENABLE_URL_LANG_CODE_PREFIX = False """
class FlaskWithHamlish(flask.Flask): jinja_options = ImmutableDict(extensions=[ 'jinja2.ext.autoescape', 'jinja2.ext.with_', 'hamlish_jinja.HamlishExtension', 'hamlish_jinja.HamlishTagExtension' ])
class FlaskWithHamlish(Flask): jinja_options = ImmutableDict(extensions=[HamlishExtension])
class Flask(_PackageBoundObject): """The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an `__init__.py` file inside) or a standard module (just a `.py` file). For more information about resource loading, see :func:`open_resource`. Usually you create a :class:`Flask` instance in your main module or in the `__init__.py` file of your package like this:: from flask import Flask app = Flask(__name__) """ #: the class that is used for request objects. See :class:`~flask.request` #: for more information. request_class = Request #: the class that is used for response objects. See #: :class:`~flask.Response` for more information. response_class = Response #: path for the static files. If you don't want to use static files #: you can set this value to `None` in which case no URL rule is added #: and the development server will no longer serve any static files. static_path = '/static' #: if a secret key is set, cryptographic components can use this to #: sign cookies and other things. Set this to a complex random value #: when you want to use the secure cookie for instance. secret_key = None #: The secure cookie uses this for the name of the session cookie session_cookie_name = 'session' #: A :class:`~datetime.timedelta` which is used to set the expiration #: date of a permanent session. The default is 31 days which makes a #: permanent session survive for roughly one month. permanent_session_lifetime = timedelta(days=31) #: options that are passed directly to the Jinja2 environment jinja_options = ImmutableDict( autoescape=True, extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'] ) def __init__(self, import_name): _PackageBoundObject.__init__(self, import_name) #: the debug flag. Set this to `True` to enable debugging of #: the application. In debug mode the debugger will kick in #: when an unhandled exception ocurrs and the integrated server #: will automatically reload the application if changes in the #: code are detected. self.debug = False #: a dictionary of all view functions registered. The keys will #: be function names which are also used to generate URLs and #: the values are the function objects themselves. #: to register a view function, use the :meth:`route` decorator. self.view_functions = {} #: a dictionary of all registered error handlers. The key is #: be the error code as integer, the value the function that #: should handle that error. #: To register a error handler, use the :meth:`errorhandler` #: decorator. self.error_handlers = {} #: a dictionary with lists of functions that should be called at the #: beginning of the request. The key of the dictionary is the name of #: the module this function is active for, `None` for all requests. #: This can for example be used to open database connections or #: getting hold of the currently logged in user. To register a #: function here, use the :meth:`before_request` decorator. self.before_request_funcs = {} #: a dictionary with lists of functions that should be called after #: each request. The key of the dictionary is the name of the module #: this function is active for, `None` for all requests. This can for #: example be used to open database connections or getting hold of the #: currently logged in user. To register a function here, use the #: :meth:`before_request` decorator. self.after_request_funcs = {} #: a dictionary with list of functions that are called without arguments #: to populate the template context. They key of the dictionary is the #: name of the module this function is active for, `None` for all #: requests. Each returns a dictionary that the template context is #: updated with. To register a function here, use the #: :meth:`context_processor` decorator. self.template_context_processors = { None: [_default_template_ctx_processor] } #: the :class:`~werkzeug.routing.Map` for this instance. You can use #: this to change the routing converters after the class was created #: but before any routes are connected. Example:: #: #: from werkzeug import BaseConverter #: #: class ListConverter(BaseConverter): #: def to_python(self, value): #: return value.split(',') #: def to_url(self, values): #: return ','.join(BaseConverter.to_url(value) #: for value in values) #: #: app = Flask(__name__) #: app.url_map.converters['list'] = ListConverter self.url_map = Map() if self.static_path is not None: self.add_url_rule(self.static_path + '/<filename>', build_only=True, endpoint='static') if pkg_resources is not None: target = (self.import_name, 'static') else: target = os.path.join(self.root_path, 'static') self.wsgi_app = SharedDataMiddleware(self.wsgi_app, { self.static_path: target }) #: the Jinja2 environment. It is created from the #: :attr:`jinja_options` and the loader that is returned #: by the :meth:`create_jinja_loader` function. self.jinja_env = Environment(loader=self.create_jinja_loader(), **self.jinja_options) self.jinja_env.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages ) self.jinja_env.filters['tojson'] = _tojson_filter def create_jinja_loader(self): """Creates the Jinja loader. By default just a package loader for the configured package is returned that looks up templates in the `templates` folder. To add other loaders it's possible to override this method. """ if pkg_resources is None: return FileSystemLoader(os.path.join(self.root_path, 'templates')) return PackageLoader(self.import_name) def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session and g into the template context. :param context: the context as a dictionary that is updated in place to add extra variables. """ funcs = self.template_context_processors[None] mod = _request_ctx_stack.top.request.module if mod is not None and mod in self.template_context_processors: funcs = chain(funcs, self.template_context_processors[mod]) for func in funcs: context.update(func()) def run(self, host='127.0.0.1', port=5000, **options): """Runs the application on a local development server. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. :param host: the hostname to listen on. set this to ``'0.0.0.0'`` to have the server available externally as well. :param port: the port of the webserver :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.run_simple` for more information. """ from werkzeug import run_simple if 'debug' in options: self.debug = options.pop('debug') options.setdefault('use_reloader', self.debug) options.setdefault('use_debugger', self.debug) return run_simple(host, port, self, **options) def test_client(self): """Creates a test client for this application. For information about unit testing head over to :ref:`testing`. """ from werkzeug import Client return Client(self, self.response_class, use_cookies=True) def open_session(self, request): """Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. :param request: an instance of :attr:`request_class`. """ key = self.secret_key if key is not None: return Session.load_cookie(request, self.session_cookie_name, secret_key=key) def save_session(self, session, response): """Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class` """ expires = None if session.permanent: expires = datetime.utcnow() + self.permanent_session_lifetime session.save_cookie(response, self.session_cookie_name, expires=expires, httponly=True) def register_module(self, module, **options): """Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the :class:`Module` class and will override the values of the module if provided. """ options.setdefault('url_prefix', module.url_prefix) state = _ModuleSetupState(self, **options) for func in module._register_events: func(state) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index .. versionchanged:: 0.2 `view_func` parameter added. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object """ if endpoint is None: assert view_func is not None, 'expected view func if endpoint ' \ 'is not provided.' endpoint = view_func.__name__ options['endpoint'] = endpoint options.setdefault('methods', ('GET',)) self.url_map.add(Rule(rule, **options)) if view_func is not None: self.view_functions[endpoint] = view_func def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. Example:: @app.route('/') def index(): return 'Hello World' Variables parts in the route can be specified with angular brackets (``/user/<username>``). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using ``<converter:name>``. Variable parts are passed to the view function as keyword arguments. The following converters are possible: =========== =========================================== `int` accepts integers `float` like `int` but for floating point values `path` like the default but also accepts slashes =========== =========================================== Here some examples:: @app.route('/') def index(): pass @app.route('/<username>') def show_user(username): pass @app.route('/post/<int:post_id>') def show_post(post_id): pass An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply: 1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached. 2. If a rule does not end with a trailing slash and the user request the page with a trailing slash, a 404 not found is raised. This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely. The :meth:`route` decorator accepts a couple of other arguments as well: :param rule: the URL rule as string :param methods: a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). :param subdomain: specifies the rule for the subdoain in case subdomain matching is in use. :param strict_slashes: can be used to disable the strict slashes setting for this rule. See above. :param options: other options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. """ def decorator(f): self.add_url_rule(rule, None, f, **options) return f return decorator def errorhandler(self, code): """A decorator that is used to register a function give a given error code. Example:: @app.errorhandler(404) def page_not_found(): return 'This page does not exist', 404 You can also register a function as error handler without using the :meth:`errorhandler` decorator. The following example is equivalent to the one above:: def page_not_found(): return 'This page does not exist', 404 app.error_handlers[404] = page_not_found :param code: the code as integer for the handler """ def decorator(f): self.error_handlers[code] = f return f return decorator def template_filter(self, name=None): """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.jinja_env.filters[name or f.__name__] = f return f return decorator def before_request(self, f): """Registers a function to run before each request.""" self.before_request_funcs.setdefault(None, []).append(f) return f def after_request(self, f): """Register a function to be run after each request.""" self.after_request_funcs.setdefault(None, []).append(f) return f def context_processor(self, f): """Registers a template context processor function.""" self.template_context_processors[None].append(f) return f def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. """ req = _request_ctx_stack.top.request try: if req.routing_exception is not None: raise req.routing_exception return self.view_functions[req.endpoint](**req.view_args) except HTTPException, e: handler = self.error_handlers.get(e.code) if handler is None: return e return handler(e) except Exception, e: handler = self.error_handlers.get(500) if self.debug or handler is None: raise return handler(e)
class Flask(_PackageBoundObject): """The flask object implements a WSGI application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an `__init__.py` file inside) or a standard module (just a `.py` file). For more information about resource loading, see :func:`open_resource`. Usually you create a :class:`Flask` instance in your main module or in the `__init__.py` file of your package like this:: from flask import Flask app = Flask(__name__) .. admonition:: About the First Parameter The idea of the first parameter is to give Flask an idea what belongs to your application. This name is used to find resources on the file system, can be used by extensions to improve debugging information and a lot more. So it's important what you provide there. If you are using a single module, `__name__` is always the correct value. If you however are using a package, it's usually recommended to hardcode the name of your package there. For example if your application is defined in `yourapplication/app.py` you should create it with one of the two versions below:: app = Flask('yourapplication') app = Flask(__name__.split('.')[0]) Why is that? The application will work even with `__name__`, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application. For example the Flask-SQLAlchemy extension will look for the code in your application that triggered an SQL query in debug mode. If the import name is not properly set up, that debugging information is lost. (For example it would only pick up SQL queries in `yourapplicaiton.app` and not `yourapplication.views.frontend`) .. versionadded:: 0.5 The `static_path` parameter was added. :param import_name: the name of the application package :param static_path: can be used to specify a different path for the static files on the web. Defaults to ``/static``. This does not affect the folder the files are served *from*. """ #: The class that is used for request objects. See :class:`~flask.Request` #: for more information. request_class = Request #: The class that is used for response objects. See #: :class:`~flask.Response` for more information. response_class = Response #: Path for the static files. If you don't want to use static files #: you can set this value to `None` in which case no URL rule is added #: and the development server will no longer serve any static files. #: #: This is the default used for application and modules unless a #: different value is passed to the constructor. static_path = '/static' #: The debug flag. Set this to `True` to enable debugging of the #: application. In debug mode the debugger will kick in when an unhandled #: exception ocurrs and the integrated server will automatically reload #: the application if changes in the code are detected. #: #: This attribute can also be configured from the config with the `DEBUG` #: configuration key. Defaults to `False`. debug = ConfigAttribute('DEBUG') #: The testing flask. Set this to `True` to enable the test mode of #: Flask extensions (and in the future probably also Flask itself). #: For example this might activate unittest helpers that have an #: additional runtime cost which should not be enabled by default. #: #: This attribute can also be configured from the config with the #: `TESTING` configuration key. Defaults to `False`. testing = ConfigAttribute('TESTING') #: If a secret key is set, cryptographic components can use this to #: sign cookies and other things. Set this to a complex random value #: when you want to use the secure cookie for instance. #: #: This attribute can also be configured from the config with the #: `SECRET_KEY` configuration key. Defaults to `None`. secret_key = ConfigAttribute('SECRET_KEY') #: The secure cookie uses this for the name of the session cookie. #: #: This attribute can also be configured from the config with the #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'`` session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME') #: A :class:`~datetime.timedelta` which is used to set the expiration #: date of a permanent session. The default is 31 days which makes a #: permanent session survive for roughly one month. #: #: This attribute can also be configured from the config with the #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to #: ``timedelta(days=31)`` permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME') #: Enable this if you want to use the X-Sendfile feature. Keep in #: mind that the server has to support this. This only affects files #: sent with the :func:`send_file` method. #: #: .. versionadded:: 0.2 #: #: This attribute can also be configured from the config with the #: `USE_X_SENDFILE` configuration key. Defaults to `False`. use_x_sendfile = ConfigAttribute('USE_X_SENDFILE') #: The name of the logger to use. By default the logger name is the #: package name passed to the constructor. #: #: .. versionadded:: 0.4 logger_name = ConfigAttribute('LOGGER_NAME') #: The logging format used for the debug logger. This is only used when #: the application is in debug mode, otherwise the attached logging #: handler does the formatting. #: #: .. versionadded:: 0.3 debug_log_format = ( '-' * 80 + '\n' + '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' + '%(message)s\n' + '-' * 80) #: Options that are passed directly to the Jinja2 environment. jinja_options = ImmutableDict( extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']) #: Default configuration parameters. default_config = ImmutableDict({ 'DEBUG': False, 'TESTING': False, 'SECRET_KEY': None, 'SESSION_COOKIE_NAME': 'session', 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': None, 'SERVER_NAME': None }) def __init__(self, import_name, static_path=None): _PackageBoundObject.__init__(self, import_name) if static_path is not None: self.static_path = static_path #: The configuration dictionary as :class:`Config`. This behaves #: exactly like a regular dictionary but supports additional methods #: to load a config from files. self.config = Config(self.root_path, self.default_config) #: Prepare the deferred setup of the logger. self._logger = None self.logger_name = self.import_name #: A dictionary of all view functions registered. The keys will #: be function names which are also used to generate URLs and #: the values are the function objects themselves. #: to register a view function, use the :meth:`route` decorator. self.view_functions = {} #: A dictionary of all registered error handlers. The key is #: be the error code as integer, the value the function that #: should handle that error. #: To register a error handler, use the :meth:`errorhandler` #: decorator. self.error_handlers = {} #: A dictionary with lists of functions that should be called at the #: beginning of the request. The key of the dictionary is the name of #: the module this function is active for, `None` for all requests. #: This can for example be used to open database connections or #: getting hold of the currently logged in user. To register a #: function here, use the :meth:`before_request` decorator. self.before_request_funcs = {} #: A dictionary with lists of functions that should be called after #: each request. The key of the dictionary is the name of the module #: this function is active for, `None` for all requests. This can for #: example be used to open database connections or getting hold of the #: currently logged in user. To register a function here, use the #: :meth:`before_request` decorator. self.after_request_funcs = {} #: A dictionary with list of functions that are called without argument #: to populate the template context. They key of the dictionary is the #: name of the module this function is active for, `None` for all #: requests. Each returns a dictionary that the template context is #: updated with. To register a function here, use the #: :meth:`context_processor` decorator. self.template_context_processors = { None: [_default_template_ctx_processor] } #: all the loaded modules in a dictionary by name. #: #: .. versionadded:: 0.5 self.modules = {} #: The :class:`~werkzeug.routing.Map` for this instance. You can use #: this to change the routing converters after the class was created #: but before any routes are connected. Example:: #: #: from werkzeug import BaseConverter #: #: class ListConverter(BaseConverter): #: def to_python(self, value): #: return value.split(',') #: def to_url(self, values): #: return ','.join(BaseConverter.to_url(value) #: for value in values) #: #: app = Flask(__name__) #: app.url_map.converters['list'] = ListConverter self.url_map = Map() # if there is a static folder, register it for the application. if self.has_static_folder: self.add_url_rule(self.static_path + '/<path:filename>', endpoint='static', view_func=self.send_static_file) #: The Jinja2 environment. It is created from the #: :attr:`jinja_options`. self.jinja_env = self.create_jinja_environment() self.init_jinja_globals() @property def logger(self): """A :class:`logging.Logger` object for this application. The default configuration is to log to stderr if the application is in debug mode. This logger can be used to (surprise) log messages. Here some examples:: app.logger.debug('A value for debugging') app.logger.warning('A warning ocurred (%d apples)', 42) app.logger.error('An error occoured') .. versionadded:: 0.3 """ if self._logger and self._logger.name == self.logger_name: return self._logger with _logger_lock: if self._logger and self._logger.name == self.logger_name: return self._logger from flask.logging import create_logger self._logger = rv = create_logger(self) return rv def create_jinja_environment(self): """Creates the Jinja2 environment based on :attr:`jinja_options` and :meth:`create_jinja_loader`. .. versionadded:: 0.5 """ options = dict(self.jinja_options) if 'autoescape' not in options: options['autoescape'] = self.select_jinja_autoescape return Environment(loader=_DispatchingJinjaLoader(self), **options) def init_jinja_globals(self): """Called directly after the environment was created to inject some defaults (like `url_for`, `get_flashed_messages` and the `tojson` filter. .. versionadded:: 0.5 """ self.jinja_env.globals.update( url_for=url_for, get_flashed_messages=get_flashed_messages) self.jinja_env.filters['tojson'] = _tojson_filter def select_jinja_autoescape(self, filename): """Returns `True` if autoescaping should be active for the given template name. .. versionadded:: 0.5 """ if filename is None: return False return filename.endswith(('.html', '.htm', '.xml', '.xhtml')) def update_template_context(self, context): """Update the template context with some commonly used variables. This injects request, session and g into the template context. :param context: the context as a dictionary that is updated in place to add extra variables. """ funcs = self.template_context_processors[None] mod = _request_ctx_stack.top.request.module if mod is not None and mod in self.template_context_processors: funcs = chain(funcs, self.template_context_processors[mod]) for func in funcs: context.update(func()) def run(self, host='127.0.0.1', port=5000, **options): """Runs the application on a local development server. If the :attr:`debug` flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. .. admonition:: Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``. Setting ``use_debugger`` to `True` without being in debug mode won't catch any exceptions because there won't be any to catch. :param host: the hostname to listen on. set this to ``'0.0.0.0'`` to have the server available externally as well. :param port: the port of the webserver :param options: the options to be forwarded to the underlying Werkzeug server. See :func:`werkzeug.run_simple` for more information. """ from werkzeug import run_simple if 'debug' in options: self.debug = options.pop('debug') options.setdefault('use_reloader', self.debug) options.setdefault('use_debugger', self.debug) return run_simple(host, port, self, **options) def test_client(self): """Creates a test client for this application. For information about unit testing head over to :ref:`testing`. The test client can be used in a `with` block to defer the closing down of the context until the end of the `with` block. This is useful if you want to access the context locals for testing:: with app.test_client() as c: rv = c.get('/?vodka=42') assert request.args['vodka'] == '42' .. versionchanged:: 0.4 added support for `with` block usage for the client. """ from flask.testing import FlaskClient return FlaskClient(self, self.response_class, use_cookies=True) def open_session(self, request): """Creates or opens a new session. Default implementation stores all session data in a signed cookie. This requires that the :attr:`secret_key` is set. :param request: an instance of :attr:`request_class`. """ key = self.secret_key if key is not None: return Session.load_cookie(request, self.session_cookie_name, secret_key=key) def save_session(self, session, response): """Saves the session if it needs updates. For the default implementation, check :meth:`open_session`. :param session: the session to be saved (a :class:`~werkzeug.contrib.securecookie.SecureCookie` object) :param response: an instance of :attr:`response_class` """ expires = domain = None if session.permanent: expires = datetime.utcnow() + self.permanent_session_lifetime if self.config['SERVER_NAME'] is not None: domain = '.' + self.config['SERVER_NAME'] session.save_cookie(response, self.session_cookie_name, expires=expires, httponly=True, domain=domain) def register_module(self, module, **options): """Registers a module with this application. The keyword argument of this function are the same as the ones for the constructor of the :class:`Module` class and will override the values of the module if provided. """ options.setdefault('url_prefix', module.url_prefix) state = _ModuleSetupState(self, **options) for func in module._register_events: func(state) def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index .. versionchanged:: 0.2 `view_func` parameter added. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object """ if endpoint is None: assert view_func is not None, 'expected view func if endpoint ' \ 'is not provided.' endpoint = view_func.__name__ options['endpoint'] = endpoint options.setdefault('methods', ('GET', )) self.url_map.add(Rule(rule, **options)) if view_func is not None: self.view_functions[endpoint] = view_func def route(self, rule, **options): """A decorator that is used to register a view function for a given URL rule. Example:: @app.route('/') def index(): return 'Hello World' Variables parts in the route can be specified with angular brackets (``/user/<username>``). By default a variable part in the URL accepts any string without a slash however a different converter can be specified as well by using ``<converter:name>``. Variable parts are passed to the view function as keyword arguments. The following converters are possible: =========== =========================================== `int` accepts integers `float` like `int` but for floating point values `path` like the default but also accepts slashes =========== =========================================== Here some examples:: @app.route('/') def index(): pass @app.route('/<username>') def show_user(username): pass @app.route('/post/<int:post_id>') def show_post(post_id): pass An important detail to keep in mind is how Flask deals with trailing slashes. The idea is to keep each URL unique so the following rules apply: 1. If a rule ends with a slash and is requested without a slash by the user, the user is automatically redirected to the same page with a trailing slash attached. 2. If a rule does not end with a trailing slash and the user request the page with a trailing slash, a 404 not found is raised. This is consistent with how web servers deal with static files. This also makes it possible to use relative link targets safely. The :meth:`route` decorator accepts a couple of other arguments as well: :param rule: the URL rule as string :param methods: a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). :param subdomain: specifies the rule for the subdomain in case subdomain matching is in use. :param strict_slashes: can be used to disable the strict slashes setting for this rule. See above. :param options: other options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. """ def decorator(f): self.add_url_rule(rule, None, f, **options) return f return decorator def errorhandler(self, code): """A decorator that is used to register a function give a given error code. Example:: @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 You can also register a function as error handler without using the :meth:`errorhandler` decorator. The following example is equivalent to the one above:: def page_not_found(error): return 'This page does not exist', 404 app.error_handlers[404] = page_not_found :param code: the code as integer for the handler """ def decorator(f): self.error_handlers[code] = f return f return decorator def template_filter(self, name=None): """A decorator that is used to register custom template filter. You can specify a name for the filter, otherwise the function name will be used. Example:: @app.template_filter() def reverse(s): return s[::-1] :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.jinja_env.filters[name or f.__name__] = f return f return decorator def before_request(self, f): """Registers a function to run before each request.""" self.before_request_funcs.setdefault(None, []).append(f) return f def after_request(self, f): """Register a function to be run after each request.""" self.after_request_funcs.setdefault(None, []).append(f) return f def context_processor(self, f): """Registers a template context processor function.""" self.template_context_processors[None].append(f) return f def handle_http_exception(self, e): """Handles an HTTP exception. By default this will invoke the registered error handlers and fall back to returning the exception as response. .. versionadded: 0.3 """ handler = self.error_handlers.get(e.code) if handler is None: return e return handler(e) def handle_exception(self, e): """Default exception handling that kicks in when an exception occours that is not catched. In debug mode the exception will be re-raised immediately, otherwise it is logged and the handler for a 500 internal server error is used. If no such handler exists, a default 500 internal server error message is displayed. .. versionadded: 0.3 """ handler = self.error_handlers.get(500) if self.debug: raise self.logger.exception('Exception on %s [%s]' % (request.path, request.method)) if handler is None: return InternalServerError() return handler(e) def dispatch_request(self): """Does the request dispatching. Matches the URL and returns the return value of the view or error handler. This does not have to be a response object. In order to convert the return value to a proper response object, call :func:`make_response`. """ req = _request_ctx_stack.top.request try: if req.routing_exception is not None: raise req.routing_exception return self.view_functions[req.endpoint](**req.view_args) except HTTPException, e: return self.handle_http_exception(e)
from pymongo import Connection from flaskext.mail import Mail, Message from flaskext.cache import Cache from flask import Flask, render_template, request, jsonify, abort, redirect, Response from datetime import datetime, date, timedelta from random import randint, choice, shuffle, randrange from hashlib import sha1 from werkzeug import ImmutableDict from bson.objectid import ObjectId from bson.code import Code from operator import itemgetter from collections import defaultdict from parltrack import default_settings Flask.jinja_options = ImmutableDict({ 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_', 'jinja2.ext.loopcontrols'] }) app = Flask(__name__) app.config.from_object(default_settings) app.config.from_envvar('PARLTRACK_SETTINGS', silent=True) cache = Cache(app) mail = Mail(app) #@app.context_processor def connect_db(): conn = Connection(app.config.get('MONGODB_HOST')) return conn[app.config.get('MONGODB_DB')]
class Babel(object): """Central controller class that can be used to configure how Flask-Babel behaves. Each application that wants to use Flask-Babel has to create, or run :meth:`init_app` on, an instance of this class after the configuration was initialized. """ default_date_formats = ImmutableDict({ 'time': 'medium', 'date': 'medium', 'datetime': 'medium', 'time.short': None, 'time.medium': None, 'time.full': None, 'time.long': None, 'date.short': None, 'date.medium': None, 'date.full': None, 'date.long': None, 'datetime.short': None, 'datetime.medium': None, 'datetime.full': None, 'datetime.long': None, }) def __init__(self, app=None, **kwargs): self._locale_cache = dict() self._default_locale = None self._default_domain = None self._default_timezone = None self._date_formats = None if app is not None: self.init_app(app, **kwargs) def init_app(self, app, default_locale='en', default_timezone='UTC', date_formats=None, configure_jinja=True, default_domain=None): """Sets up the Flask-BabelEx extension. :param app: The Flask application. :param default_locale: The default locale which should be used. :param default_timezone: The default timezone. :param date_formats: A mapping of Babel datetime format strings :param configure_jinja: If set to ``True`` some convenient jinja2 filters are being added. :param default_domain: The default translation domain. """ self._default_locale = default_locale self._default_timezone = default_timezone self._date_formats = date_formats if default_domain is None: self._default_domain = Domain() else: self._default_domain = default_domain app.babel_instance = self if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['babel'] = self self.app = app self.locale_selector_func = None self.timezone_selector_func = None app.config.setdefault('BABEL_DEFAULT_LOCALE', self._default_locale) app.config.setdefault('BABEL_DEFAULT_TIMEZONE', self._default_timezone) if self._date_formats is None: self._date_formats = self.default_date_formats.copy() #: a mapping of Babel datetime format strings that can be modified #: to change the defaults. If you invoke :func:`format_datetime` #: and do not provide any format string Flask-Babel will do the #: following things: #: #: 1. look up ``date_formats['datetime']``. By default ``'medium'`` #: is returned to enforce medium length datetime formats. #: 2. ``date_formats['datetime.medium'] (if ``'medium'`` was #: returned in step one) is looked up. If the return value #: is anything but `None` this is used as new format string. #: otherwise the default for that language is used. self.date_formats = self._date_formats if configure_jinja: app.jinja_env.filters.update( datetimeformat=format_datetime, dateformat=format_date, timeformat=format_time, timedeltaformat=format_timedelta, numberformat=format_number, decimalformat=format_decimal, currencyformat=format_currency, percentformat=format_percent, scientificformat=format_scientific, ) app.jinja_env.add_extension('jinja2.ext.i18n') app.jinja_env.install_gettext_callables( lambda x: get_domain().get_translations().ugettext(x), lambda s, p, n: get_domain().get_translations().ungettext( s, p, n), newstyle=True) def get_app(self, reference_app=None): """Helper method that implements the logic to look up an a pplication. """ if reference_app is not None: return reference_app if self.app is not None: return self.app ctx = stack.top if ctx is not None: return ctx.app raise RuntimeError('application not registered on babel ' 'instance and no application bound ' 'to current context') def localeselector(self, f): """Registers a callback function for locale selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the locale falls back to the one from the configuration. This has to return the locale as string (eg: ``'de_AT'``, ''`en_US`'') """ assert self.locale_selector_func is None, \ 'a localeselector function is already registered' self.locale_selector_func = f return f def timezoneselector(self, f): """Registers a callback function for timezone selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the timezone falls back to the one from the configuration. This has to return the timezone as string (eg: ``'Europe/Vienna'``) """ assert self.timezone_selector_func is None, \ 'a timezoneselector function is already registered' self.timezone_selector_func = f return f def list_translations(self): """Returns a list of all the locales translations exist for. The list returned will be filled with actual locale objects and not just strings. .. versionadded:: 0.6 """ app = self.get_app() dirname = os.path.join(app.root_path, 'translations') if not os.path.isdir(dirname): return [] result = [] for folder in os.listdir(dirname): locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES') if not os.path.isdir(locale_dir): continue if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)): result.append(Locale.parse(folder)) if not result: result.append(Locale.parse(self._default_locale)) return result @property def default_locale(self): """The default locale from the configuration as instance of a `babel.Locale` object. """ app = self.get_app() return self.load_locale(app.config['BABEL_DEFAULT_LOCALE']) @property def default_timezone(self): """The default timezone from the configuration as instance of a `pytz.timezone` object. """ app = self.get_app() return timezone(app.config['BABEL_DEFAULT_TIMEZONE']) def load_locale(self, locale): """Load locale by name and cache it. Returns instance of a `babel.Locale` object. """ rv = self._locale_cache.get(locale) if rv is None: self._locale_cache[locale] = rv = Locale.parse(locale) return rv
class ReplicationMasterHandler(WebSocketHandler): """スキーマを交換し、まだ相手に送っていないデータを送る. :param UUID slave_uuid: """ def open(self, link_uuid): """他のCircleCoreから接続された際に呼ばれる.""" logger.debug('%s Connected from slave CircleCore', link_uuid) self.link_uuid = link_uuid self.replication_link = ReplicationLink.query.get(link_uuid) if not self.replication_link: logger.warning( 'ReplicationLink %s was not found. Connection close.', link_uuid) self.close( code=WebsocketStatusCode.NOT_FOUND.value, reason='ReplicationLink {} was not found.'.format(link_uuid)) return database = self.get_core().get_database() self.state = ReplicationState.HANDSHAKING self.sync_states = ImmutableDict( (box.uuid, SyncState(box, database.get_latest_primary_key(box))) for box in self.replication_link.message_boxes) self.syncing = False logger.debug('initial sync status: %s', self.sync_states) # messageに関するイベントを監視する self.receiver = self.get_core().make_hub_receiver(make_message_topic()) self.receiver.register_ioloop(self.on_new_message) def get_core(self): return self.application.settings['_core'] async def on_message(self, plain_msg): """センサーからメッセージが送られてきた際に呼ばれる. {command: command from slave, ...payload} :param unicode plain_msg: """ logger.debug('message from slave: %s' % plain_msg) json_msg = json.loads(plain_msg) try: command = SlaveCommand(json_msg['command']) except ValueError: raise ReplicationError('invalid command `{}`'.format( json_msg['command'])) handler = getattr(self, 'on_slave_' + command.value) try: await handler(json_msg) except ReplicationError as exc: self.close(code=WebsocketStatusCode.VIOLATE_POLICY.value, reason=str(exc)) def on_close(self): """センサーとの接続が切れた際に呼ばれる.""" logger.debug('connection closed: %s', self) if hasattr(self, 'receiver'): # Stop passing messages to slave IOLoop.current().remove_handler(self.receiver) def check_origin(self, origin): """CORSチェック.""" # wsta等テストツールから投げる場合はTrueにしておく return True def _send_command(self, cmd, **kwargs): assert 'command' not in kwargs assert isinstance(cmd, MasterCommand) msg = kwargs.copy() msg['command'] = cmd.value raw = json.dumps(msg) return self.write_message(raw) async def on_slave_hello(self, json_msg): """hello コマンドが送られてきた""" assert self.state == ReplicationState.HANDSHAKING self.state = ReplicationState.MIGRATING # slave's cc info slave_info = json_msg['ccInfo'] slave_uuid = uuid.UUID(slave_info['uuid']) with MetaDataSession.begin(): # store slave's information if slave_uuid not in [ slave.slave_uuid for slave in self.replication_link.slaves ]: self.replication_link.slaves.append( ReplicationSlave(link_uuid=self.replication_link.uuid, slave_uuid=slave_uuid)) cc_info = CcInfo.query.get(slave_uuid) if not cc_info: cc_info = CcInfo(uuid=slave_uuid, myself=False) cc_info.update_from_json(slave_info) MetaDataSession.add(cc_info) await self.send_migrate() def send_migrate(self): """共有対象のMessageBox関連データを配る""" message_boxes = self.replication_link.message_boxes modules = set(box.module for box in message_boxes) schemas = set(box.schema for box in message_boxes) return self._send_command( MasterCommand.MIGRATE, masterInfo=CcInfo.query.filter_by(myself=True).one().to_json(), messageBoxes=dict( (str(obj.uuid), obj.to_json()) for obj in message_boxes), modules=dict((str(obj.uuid), obj.to_json()) for obj in modules), schemas=dict((str(obj.uuid), obj.to_json()) for obj in schemas), ) async def on_slave_migrated(self, json_msg): """Slave側の受け入れ準備が整ったら送られてくる headsがslaveの最新データなのでそれ以降のデータを送る""" assert self.state == ReplicationState.MIGRATING self.state = ReplicationState.SYNCING database = self.get_core().get_database() conn = database.connect() # save slave head heads = json_msg.get('heads', {}) for box in self.replication_link.message_boxes: sync_state = self.sync_states.get(box.uuid) sync_state.slave_head = ModuleMessagePrimaryKey.from_json( heads.get(str(box.uuid))) logger.debug('box: %s, slave head: %r', box.uuid, self.sync_states[box.uuid].slave_head) conn.close() self.syncing = True while True: logger.debug('syncing...') all_synced = await self.sync() if all_synced: break await asyncio.sleep(0.1) logger.debug('all synced') self.syncing = False async def sync(self): """master<>slave間で全boxを同期させようと試みる""" all_synced = True database = self.get_core().get_database() conn = database.connect() for box in self.replication_link.message_boxes: sync_state = self.sync_states[box.uuid] # logger.debug( # 'sync message box %s: from %s to %s', box.uuid, # sync_state.slave_head, # sync_state.master_head) count_messages = 0 for message in database.enum_messages( box, head=self.sync_states[box.uuid].slave_head, connection=conn): logger.debug('sync message %s', message) await self._send_command(MasterCommand.SYNC_MESSAGE, message=message.to_json()) sync_state.slave_head = message.primary_key count_messages += 1 if count_messages == 0: # messageが0個の場合... logger.debug('%r has no messages!!', box.uuid) # logger.debug(' sync to %s', sync_state.slave_head) logger.debug('%r -> is_sycned %r', box.uuid, sync_state.is_synced()) if not sync_state.is_synced(): all_synced = False conn.close() return all_synced # Hub def on_new_message(self, topic, jsonobj): """新しいメッセージを受けとった""" message = ModuleMessage.from_json(jsonobj) logger.debug('on_new_message: %s', message) if message.box_id not in self.sync_states: # not target return sync_state = self.sync_states[message.box_id] try: if not sync_state.is_synced(): # boxがまだsync中であればnew_messageは無視する。syncの方で同期されるはずなので logger.debug('skip message %s, because not synced', message) logger.debug(' master %s, slave %s', self.sync_states[message.box_id].master_head, self.sync_states[message.box_id].slave_head) else: sync_state.slave_head = message.primary_key # pass to slave logger.debug('pass message %s', message) self._send_command(MasterCommand.NEW_MESSAGE, message=message.to_json()) finally: sync_state.master_head = message.primary_key
class ICU(object): """Central controller class that can be used to configure how Flask-ICU behaves. Each application that wants to use Flask-ICU has to create, or run :meth:`init_app` on, an instance of this class after the configuration was initialized. """ messages = {} icu_date_formats = ImmutableDict({ 'short': DateFormat.SHORT, 'medium': DateFormat.MEDIUM, 'long': DateFormat.LONG, 'full': DateFormat.FULL, }) default_date_formats = ImmutableDict({ 'time': 'medium', 'date': 'medium', 'datetime': 'medium', 'time.short': None, 'time.medium': None, 'time.full': None, 'time.long': None, 'date.short': None, 'date.medium': None, 'date.full': None, 'date.long': None, 'datetime.short': None, 'datetime.medium': None, 'datetime.full': None, 'datetime.long': None, }) def __init__(self, app=None, default_locale='en', default_timezone='UTC', date_formats=None, configure_jinja=True): self._default_locale = default_locale self._default_timezone = default_timezone self._date_formats = date_formats self._configure_jinja = configure_jinja self.app = app if app is not None: self.init_app(app) def init_app(self, app): """Set up this instance for use with *app*, if no app was passed to the constructor. """ self.app = app app.icu_instance = self if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['icu'] = self app.config.setdefault('ICU_DEFAULT_LOCALE', self._default_locale) app.config.setdefault('ICU_DEFAULT_TIMEZONE', self._default_timezone) if self._date_formats is None: self._date_formats = self.default_date_formats.copy() #: A mapping of ICU datetime format strings that can be modified #: to change the defaults. If you invoke :func:`format_datetime` #: and do not provide any format string Flask-ICU will do the #: following things: #: #: 1. look up ``date_formats['datetime']``. By default ``'medium'`` #: is returned to enforce medium length datetime formats. #: 2. ``date_formats['datetime.medium'] (if ``'medium'`` was #: returned in step one) is looked up. If the return value #: is anything but `None` this is used as new format string. #: otherwise the default for that language is used. self.date_formats = self._date_formats self.locale_selector_func = None self.timezone_selector_func = None if self._configure_jinja: app.jinja_env.globals.update(format=format, format_date=format_date, format_time=format_time, format_datetime=format_datetime, format_number=format_number, format_decimal=format_decimal, format_scientific=format_scientific, format_percent=format_percent) def localeselector(self, f): """Registers a callback function for locale selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the locale falls back to the one from the configuration. This has to return the locale as string (eg: ``'de_AT'``, ''`en_US`'') """ assert self.locale_selector_func is None, \ 'a localeselector function is already registered' self.locale_selector_func = f return f def timezoneselector(self, f): """Registers a callback function for timezone selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the timezone falls back to the one from the configuration. This has to return the timezone as string (eg: ``'Europe/Vienna'``) """ assert self.timezone_selector_func is None, \ 'a timezoneselector function is already registered' self.timezone_selector_func = f return f def list_translations(self): """Returns a list of all the locales translations exist for. The list returned will be filled with actual locale objects and not just strings. """ dirname = os.path.join(self.app.root_path, TRANSLATIONS_PATH) if not os.path.isdir(dirname): return [] return [ name for name in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, name)) ] @property def default_locale(self): """The default locale from the configuration as instance of a `icu.Locale` object. """ default = self.app.config['ICU_DEFAULT_LOCALE'] if default is None: default = 'en' return Locale(default) @property def default_timezone(self): """The default timezone from the configuration as instance of a `icu.TimeZone` object. """ default = self.app.config['ICU_DEFAULT_TIMEZONE'] if default is None: default = 'UTC' return (ICUtzinfo.getInstance(default).timezone)
secrets.__file__ = os.path.expanduser(CONFIG["SECRETS_FILE"]) try: execfile(secrets.__file__, secrets.__dict__) except IOError, e: print e print "Unable to load secrets file: %s." % CONFIG["SECRETS_FILE"] print "Please copy .pystil-secrets to your home and fill it" print "Change the file location with CONFIG['SECRETS_FILE']" exit(1) else: for key in dir(secrets): CONFIG[key] = getattr(secrets, key) if not CONFIG["DB_NAME"]: CONFIG["DB_NAME"] = CONFIG["DB_USER"] CONFIG['DB_URL'] = make_db_url() CONFIG = ImmutableDict(CONFIG) FROZEN = True def make_db_url(): """Compute the database options.""" if CONFIG["DB_BACKEND"] == "sqlite": return 'sqlite:///pystil.sqlite' else: return 'postgresql+psycopg2://%s:%s@%s:%d/%s' % ( CONFIG["DB_USER"], CONFIG["DB_PASSWORD"], CONFIG["DB_HOST"], CONFIG["DB_PORT"], CONFIG["DB_NAME"])
from flask import Flask, Request, g, Blueprint from flask.ext.cache import Cache from flask.ext.mail import Mail from simplekv.fs import FilesystemStore from flask.ext.kvsession import KVSessionExtension from edacc import config, models, utils try: os.makedirs(config.TEMP_DIR) except OSError: pass Flask.jinja_options = ImmutableDict({ 'extensions': ['jinja2.ext.autoescape', 'jinja2.ext.with_'], 'bytecode_cache': FileSystemBytecodeCache(config.TEMP_DIR), 'trim_blocks': True }) app = Flask(__name__) app.Debug = config.DEBUG cache = Cache() mail = Mail() #session_store = FilesystemStore(config.TEMP_DIR, perm=0600) if config.LOGGING: # set up logging if configured import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler(config.LOG_FILE)
class Babel(object): """Central controller class that can be used to configure how Flask-Babel behaves. Each application that wants to use Flask-Babel has to create, or run :meth:`init_app` on, an instance of this class after the configuration was initialized. """ default_date_formats = ImmutableDict({ 'time': 'medium', 'date': 'medium', 'datetime': 'medium', 'time.short': None, 'time.medium': None, 'time.full': None, 'time.long': None, 'date.short': None, 'date.medium': None, 'date.full': None, 'date.long': None, 'datetime.short': None, 'datetime.medium': None, 'datetime.full': None, 'datetime.long': None, }) def __init__(self, app=None, default_locale='en', default_timezone='UTC', date_formats=None, configure_jinja=True): self._default_locale = default_locale self._default_timezone = default_timezone self._date_formats = date_formats self._configure_jinja = configure_jinja self.app = app self.locale_selector_func = None self.timezone_selector_func = None if app is not None: self.init_app(app) def init_app(self, app): """Set up this instance for use with *app*, if no app was passed to the constructor. """ self.app = app app.babel_instance = self if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['babel'] = self app.config.setdefault('BABEL_DEFAULT_LOCALE', self._default_locale) app.config.setdefault('BABEL_DEFAULT_TIMEZONE', self._default_timezone) if self._date_formats is None: self._date_formats = self.default_date_formats.copy() #: a mapping of Babel datetime format strings that can be modified #: to change the defaults. If you invoke :func:`format_datetime` #: and do not provide any format string Flask-Babel will do the #: following things: #: #: 1. look up ``date_formats['datetime']``. By default ``'medium'`` #: is returned to enforce medium length datetime formats. #: 2. ``date_formats['datetime.medium'] (if ``'medium'`` was #: returned in step one) is looked up. If the return value #: is anything but `None` this is used as new format string. #: otherwise the default for that language is used. self.date_formats = self._date_formats if self._configure_jinja: app.jinja_env.filters.update( datetimeformat=format_datetime, dateformat=format_date, timeformat=format_time, timedeltaformat=format_timedelta, numberformat=format_number, decimalformat=format_decimal, currencyformat=format_currency, percentformat=format_percent, scientificformat=format_scientific, ) app.jinja_env.add_extension('jinja2.ext.i18n') app.jinja_env.install_gettext_callables( lambda x: get_translations().ugettext(x), lambda s, p, n: get_translations().ungettext(s, p, n), newstyle=True) def localeselector(self, f): """Registers a callback function for locale selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the locale falls back to the one from the configuration. This has to return the locale as string (eg: ``'de_AT'``, ''`en_US`'') """ assert self.locale_selector_func is None, \ 'a localeselector function is already registered' self.locale_selector_func = f return f def timezoneselector(self, f): """Registers a callback function for timezone selection. The default behaves as if a function was registered that returns `None` all the time. If `None` is returned, the timezone falls back to the one from the configuration. This has to return the timezone as string (eg: ``'Europe/Vienna'``) """ assert self.timezone_selector_func is None, \ 'a timezoneselector function is already registered' self.timezone_selector_func = f return f def list_translations(self): """Returns a list of all the locales translations exist for. The list returned will be filled with actual locale objects and not just strings. .. versionadded:: 0.6 """ result = [] for dirname in self.translation_directories: if not os.path.isdir(dirname): continue for folder in os.listdir(dirname): locale_dir = os.path.join(dirname, folder, 'LC_MESSAGES') if not os.path.isdir(locale_dir): continue if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)): result.append(Locale.parse(folder)) # If not other translations are found, add the default locale. if not result: result.append(Locale.parse(self._default_locale)) return result @property def default_locale(self): """The default locale from the configuration as instance of a `babel.Locale` object. """ return Locale.parse(self.app.config['BABEL_DEFAULT_LOCALE']) @property def default_timezone(self): """The default timezone from the configuration as instance of a `pytz.timezone` object. """ return timezone(self.app.config['BABEL_DEFAULT_TIMEZONE']) @property def translation_directories(self): directories = self.app.config.get('BABEL_TRANSLATION_DIRECTORIES', 'translations').split(';') for path in directories: if os.path.isabs(path): yield path else: yield os.path.join(self.app.root_path, path)
flask_babelplus.constants ~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains the constants that are used in this extension. :copyright: (c) 2013 by Armin Ronacher, Daniel Neuhäuser and contributors. :license: BSD, see LICENSE for more details. """ from werkzeug import ImmutableDict DEFAULT_LOCALE = "en" DEFAULT_TIMEZONE = "UTC" DEFAULT_DATE_FORMATS = ImmutableDict({ 'time': 'medium', 'date': 'medium', 'datetime': 'medium', 'time.short': None, 'time.medium': None, 'time.full': None, 'time.long': None, 'date.short': None, 'date.medium': None, 'date.full': None, 'date.long': None, 'datetime.short': None, 'datetime.medium': None, 'datetime.full': None, 'datetime.long': None, })