def test_get_instance_does_not_override_anything(self): environment = "production" config = ApplicationConfig.get_instance(environment) config2 = ApplicationConfig.get_instance() self.assertEqual(id(config), id(config2)) self.assertEqual(environment, config2.environment)
def test_incorrect_environment_error(self): expected_error_msg = "environment has to be one of {}".format(ApplicationConfig.ALLOWED_ENVS) with self.assertRaises(ValueError) as config: ApplicationConfig("foo") self.assertEqual(expected_error_msg, str(config.exception))
import sys import traceback from json import loads, dumps from json.decoder import JSONDecodeError from os import getenv import pika from config import ApplicationConfig from logger import get_logger from providers import trello_app PROPERTIES_URL = getenv('PROPERTIES_URL') logger = get_logger(__name__) config = ApplicationConfig(PROPERTIES_URL) def on_message(channel, method_frame, header_frame, body): try: body = loads(body.decode('utf8')) if body.get("type") in ("trello", None): trello_app.push_card(config.trello_api_key, config.trello_token, body) else: raise NotImplementedError except JSONDecodeError as e: channel.basic_publish( exchange=config.rabbitmq_exchange_name, routing_key=config.rabbitmq_dead_letter_queue_key, body=dumps({ "body":
import os from dotenv import load_dotenv from flask import Flask, request from flask_orator import Orator, jsonify from config import ApplicationConfig if __name__ == "__main__": from controllers.api import ApiController load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) environment = os.environ.get("ENV", os.getenv("ENV", "development")) application_config = ApplicationConfig.get_instance(environment=environment) # Flask application app = Flask(__name__) app.config["APPLICATION_CONFIG"] = application_config app.config["ORATOR_DATABASES"] = { "default": environment, environment: application_config.database_config() } if environment is not "production": app.config["ORATOR_DATABASES"]["test"] = application_config.database_config_for_env("test") # Orator db db = Orator(app) if __name__ == "__main__": # controllers
Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url import super_cool.bewsito.views as view from config import ApplicationConfig import django urlpatterns = [ url(r'^bewsito/', view.mainpage), url(r'^js/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('js')}, name='JS'), url(r'^css/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('css')}, name='CSS'), url(r'^images/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('image')}, name='IMG'), ]
Generated by 'django-admin startproject' using Django 1.9.2. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os from config import ApplicationConfig # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HTML_DIR = ApplicationConfig.get_source('html') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(dr96^@b_8vt741o5oyn3__j7*l0cxv!_t=z_69u8j31oc4r2=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition
import os from dotenv import load_dotenv from flask import Flask, request from flask_orator import Orator, jsonify from config import ApplicationConfig if __name__ == "__main__": from controllers.api import ApiController load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) environment = os.environ.get("ENV", os.getenv("ENV", "development")) application_config = ApplicationConfig.get_instance(environment=environment) # Flask application app = Flask(__name__) app.config["APPLICATION_CONFIG"] = application_config app.config["ORATOR_DATABASES"] = { "default": environment, environment: application_config.database_config() } if environment is not "production": app.config["ORATOR_DATABASES"][ "test"] = application_config.database_config_for_env("test") # Orator db db = Orator(app) if __name__ == "__main__":
class ZookeeperRegistry(Registry): _app_config = ApplicationConfig('default_app') _connect_state = 'UNCONNECT' def __init__(self, zk_hosts, application_config=None): if application_config: self._app_config = application_config self.__zk = KazooClient(hosts=zk_hosts) self.__zk.add_listener(self.__state_listener) self.__zk.start() def __state_listener(self, state): if state == KazooState.LOST: # Register somewhere that the session was lost self._connect_state = state elif state == KazooState.SUSPENDED: # Handle being disconnected from Zookeeper # print 'disconnect from zookeeper' self._connect_state = state else: # Handle being connected/reconnected to Zookeeper # print 'connected' self._connect_state = state def __unquote(self, origin_nodes): return (urllib.parse.unquote(child_node) for child_node in origin_nodes if child_node) #decode('utf8') def _do_event(self, event): # event.path 是类似/dubbo/com.ofpay.demo.api.UserProvider/providers 这样的 # 如果要删除,必须先把/dubbo/和最后的/providers去掉 # 将zookeeper中查询到的服务节点列表加入到一个dict中 # zookeeper中保持的节点url类似如下 provide_name = event.path[7:event.path.rfind('/')] if event.state == 'CONNECTED': children = self.__zk.get_children(event.path, watch=self.event_listener) self._compare_swap_nodes(provide_name, self.__unquote(children)) if event.state == 'DELETED': children = self.__zk.get_children(event.path, watch=self.event_listener) self._compare_swap_nodes(provide_name, self.__unquote(children)) def register(self, interface, **kwargs): ip = self.__zk._connection._socket.getsockname()[0] params = { 'interface': interface, 'application': self._app_config.name, 'application.version': self._app_config.version, 'category': 'consumer', 'dubbo': 'dubbo-client-py-1.0.0', 'environment': self._app_config.environment, 'method': '', 'owner': self._app_config.owner, 'side': 'consumer', 'pid': os.getpid(), 'version': '1.0' } url = 'consumer://{0}/{1}?{2}'.format(ip, interface, urllib.parse.urlencode(params)) # print urllib.quote(url, safe='') consumer_path = '{0}/{1}/{2}'.format('dubbo', interface, 'consumers') self.__zk.ensure_path(consumer_path) if not self.__zk.exists(consumer_path + '/' + urllib.parse.quote(url, safe='')): self.__zk.create(consumer_path + '/' + urllib.parse.quote(url, safe=''), ephemeral=True) def subscribe(self, interface, **kwargs): """ 监听注册中心的服务上下线 :param interface: 类似com.ofpay.demo.api.UserProvider这样的服务名 :return: 无返回 """ version = kwargs.get('version', '') group = kwargs.get('group', '') children = self.__zk.get_children('{0}/{1}/{2}'.format( 'dubbo', interface, 'providers'), watch=self.event_listener) # 全部重新添加 self._compare_swap_nodes(interface, self.__unquote(children))
def tearDown(self): ApplicationConfig.reset_instance()
def test_debug_mode_is_enabled_in_production_environment(self): config = ApplicationConfig("production") self.assertFalse(config.debug_mode_is_enabled())
def test_debug_mode_is_enabled_in_development_environment(self): config = ApplicationConfig("development") self.assertTrue(config.debug_mode_is_enabled())
def test_sets_environment(self): environment = "production" config = ApplicationConfig(environment) self.assertEqual(config.environment, environment)
Generated by 'django-admin startproject' using Django 1.9.2. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os from config import ApplicationConfig # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) HTML_DIR = ApplicationConfig.get_source('html') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(dr96^@b_8vt741o5oyn3__j7*l0cxv!_t=z_69u8j31oc4r2=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url import super_cool.bewsito.views as view from config import ApplicationConfig import django urlpatterns = [ url(r'^bewsito/', view.mainpage), url(r'^js/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('js')}, name='JS'), url(r'^css/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('css')}, name='CSS'), url(r'^images/(?P<path>.*)$', django.views.static.serve, {'document_root': ApplicationConfig.get_source('image')}, name='IMG'), ]