示例#1
0
文件: baseapp.py 项目: softlog/web
    def __init__(self, app, session):

        self.menu = Menu()
        self.app = app
        self.session = session
        self.base_template = "frontend/base_onepage.html"
        self.template_folder = "templates"
        self.static_folder = "files/static"
        self.security_manager_class = SecurityManager
        self.sm = self.security_manager_class(self)
        self.indexview = IndexView
        self._add_admin_views()
        #self._add_addon_views()
        self._add_menu_permissions()
        self._add_global_filters()
        self.model_string_conexoes = SQLAInterface(StringConexoes, session)
        #session.close()

        #self._add_uris()

        if not self.app:
            for baseview in self.baseviews:
                # instantiate the views and add session
                self._check_and_init(baseview)
                # Register the views has blueprints
                self.register_blueprint(baseview)
                # Add missing permissions where needed
                self._add_permission(baseview)
示例#2
0
 def setUp(self):
     self.my_cycle_menus = CycleMenus()
     self.my_menu = Menu(menu_list[0], [], header, message, footer,
                         self.my_cycle_menus.send_choice)
     self.old_stdout = sys.stdout
     f = open(os.devnull, 'w')
     sys.stdout = f
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('date', type=date, required=True)
     parser.add_argument('meals', type=list, required=True)
     params = parser.parse_args()
     date = params['date']
     meals = params['meals']
     menu = Menu(date=date.today(),
                 meals=[{
                     "price": "something soemthing",
                     "id": 3,
                     "description": 1001
                 }, {
                     "price": "something soemthing",
                     "id": 18,
                     "description": 1002
                 }, {
                     "price": "something soemthing",
                     "id": 1,
                     "description": 1003
                 }])
     menu.addMenu()
     return {
         'menus': [{
             'id': menu.id,
             'date': menu.date,
             'meals': menu.meals
         } for menu in menus]
     }, 200
示例#4
0
    def setUp(self):
        self.app = app
        self.test_client = self.app.test_client()
        self.app_context = app.app_context()
        self.app_context.push()

        self.store = DataStruct()
        self.menu = Menu()
        self.user = Users()
        self.order = Orders()
        
        #create a user and menu item
        Menu("Hot Burgar", "served with juice & ketchup").save_menu_item()
        Users("henry henry","@hhenry","*****@*****.**","555 555 555","user").save_user()
示例#5
0
class Main(object):
    def __init__(self):
        self.STATE_MENU = 0
        self.STATE_QUIT = 1
        self.STATE_BOARD_GAME = 2
        self.current_phase = "PLANNING PHASE"
        pygame.init()
        pygame.font.init()
        pygame.mixer.init()

        self.screen = pygame.display.set_mode(Props.size)
        self.surface = pygame.Surface(self.screen.get_size())
        pygame.display.set_caption("HEXCELSIOR")

        # Our menu and game screens
        self.music = Music()
        self.menu = Menu(self.screen, self.surface, self.music)
        self.game = Game(self.screen, self.surface, self.music)

    def process_user_input(self, state):
        for event in pygame.event.get():
            if event.type == self.music.song_end:
                print("song has ended")
                self.music.play_next_song()
            if event.type == pygame.QUIT:
                state = self.STATE_QUIT
            if state == self.STATE_MENU:
                state = self.menu.process_user_input(event)
            elif state == self.STATE_BOARD_GAME:
                state = self.game.process_user_input(event)

        return state

    def refresh(self, state):
        if state == self.STATE_MENU:
            self.menu.refresh()
        elif state == self.STATE_BOARD_GAME:
            self.game.refresh()

    def run(self):
        self.music.play_first_song()
        state = self.STATE_MENU
        while state != self.STATE_QUIT:
            state = self.process_user_input(state)
            self.refresh(state)
            pygame.display.flip()
示例#6
0
    def __init__(self):
        self.STATE_MENU = 0
        self.STATE_QUIT = 1
        self.STATE_BOARD_GAME = 2
        self.current_phase = "PLANNING PHASE"
        pygame.init()
        pygame.font.init()
        pygame.mixer.init()

        self.screen = pygame.display.set_mode(Props.size)
        self.surface = pygame.Surface(self.screen.get_size())
        pygame.display.set_caption("HEXCELSIOR")

        # Our menu and game screens
        self.music = Music()
        self.menu = Menu(self.screen, self.surface, self.music)
        self.game = Game(self.screen, self.surface, self.music)
示例#7
0
 def test_invalid_selection_combination_is_caught(self):
     app.menu.raw_input = lambda _: '4'
     self.my_cycle_menus.this_menu = Menu(menu_list[1],
                                          self.my_cycle_menus.chosen,
                                          header, message, footer,
                                          self.my_cycle_menus.send_choice)
     self.my_cycle_menus.this_menu.read()
     self.my_cycle_menus.this_menu.get_selection()
     self.my_cycle_menus.this_menu.validate_selection()
     self.assertFalse(self.my_cycle_menus.this_menu.good_combination())
示例#8
0
 def setUp(self):
     self.old_stdout = sys.stdout
     f = open(os.devnull, 'w')
     sys.stdout = f
     self.my_cycle_menus = CycleMenus()
     app.menu.raw_input = lambda _: '5'
     self.my_cycle_menus.this_menu = Menu(menu_list[0],
                                          self.my_cycle_menus.chosen,
                                          header, message, footer,
                                          self.my_cycle_menus.send_choice)
     self.my_cycle_menus.this_menu.run()
示例#9
0
    def __init__(self):
        self.current_phase = "PLANNING PHASE"
        pygame.init()
        pygame.font.init()
        pygame.mixer.init()

        self.screen = pygame.display.set_mode(Props.size)
        self.surface = pygame.Surface(self.screen.get_size())
        pygame.display.set_caption("HEXCELSIOR")

        # Our menu and game screens
        self.music = Music()
        States.MENU = Menu(self.screen, self.surface, self.music)
        self.game = None
示例#10
0
文件: app.py 项目: CamClrt/FoodChoice
 def start(self):
     """Launch the DB connection + invite user to log in, sign in or quit"""
     with Database() as database:
         print(
             " Bienvenue dans l'application FoodChoice ".center(102, "*"),
             "\n",
         )
         cnx = True
         while cnx:
             print(" Connection ".center(102, "#"))
             menu = Menu(database)
             menu.cnx_menu()
             menu.main_menu()
示例#11
0
class TestMenu(object):
    def setUp(self):
        data = json.load(open('data/hipstercoffee.json'))
        self.price_data = data[0]['prices'][0]
        self.menu = Menu('data/hipstercoffee.json')

    def test_view_menu_returns_the_menu(self):
        eq_(self.menu.view_menu(), self.price_data)

    def test_price_returns_the_price_of_item_requested(self):
        eq_(self.menu.price('Cafe Latte'), self.price_data['Cafe Latte'])

    @raises(NotInMenuError)
    def test_price_raises_exception_if_item_is_not_in_menu(self):
        self.menu.price('item not in menu')

    @raises(NotInMenuError)
    def test_verify_in_menu_raises_NotInMenuError_if_item_is_not_in_menu(self):
        self.menu.verify_in_menu('item not in menu')
示例#12
0
class TestMenu(object):
    def setUp(self):
        data = json.load(open('data/hipstercoffee.json'))
        self.price_data = data[0]['prices'][0]
        self.menu = Menu('data/hipstercoffee.json')

    def test_view_menu_returns_the_menu(self):
        eq_(self.menu.view_menu(), self.price_data)

    def test_price_returns_the_price_of_item_requested(self):
        eq_(self.menu.price('Cafe Latte'), self.price_data['Cafe Latte'])

    @raises(NotInMenuError)
    def test_price_raises_exception_if_item_is_not_in_menu(self):
        self.menu.price('item not in menu')

    @raises(NotInMenuError)
    def test_verify_in_menu_raises_NotInMenuError_if_item_is_not_in_menu(self):
        self.menu.verify_in_menu('item not in menu')
示例#13
0
文件: main.py 项目: c-seale/sodoku
def main():
    os.environ['SDL_VIDEO_CENTERED'] = '1'  # App opens centered on screen

    # Init pygame
    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.init()

    # Init game window
    display = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('cseale\'s Sudoku!')
    sever_tick = pygame.time.Clock()

    display.fill(BACKGROUND_COLOR)
    pygame.display.update()

    board_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT - 100))
    board = Board(board_surface, load_level(1)[0].rstrip())

    menu_surface = pygame.Surface((SCREEN_WIDTH, 100))
    menu = Menu(menu_surface)

    # Init music
    # TODO: Setup background music

    running = True
    while running:
        # Get active input
        pressed_keys = pygame.key.get_pressed()

        # Handle events
        for event in pygame.event.get():
            if event.type == pygame.QUIT \
                    or (event.type == pygame.KEYDOWN and event.key == pygame.K_F4
                        and (pressed_keys[pygame.K_LALT] or pressed_keys[pygame.K_RALT])):
                running = False
                break
            if event.type == pygame.KEYUP:
                cell_val_input = None
                if event.key in [pygame.K_1, pygame.K_KP1]:
                    cell_val_input = 1
                if event.key in [pygame.K_2, pygame.K_KP2]:
                    cell_val_input = 2
                if event.key in [pygame.K_3, pygame.K_KP3]:
                    cell_val_input = 3
                if event.key in [pygame.K_4, pygame.K_KP4]:
                    cell_val_input = 4
                if event.key in [pygame.K_5, pygame.K_KP5]:
                    cell_val_input = 5
                if event.key in [pygame.K_6, pygame.K_KP6]:
                    cell_val_input = 6
                if event.key in [pygame.K_7, pygame.K_KP7]:
                    cell_val_input = 7
                if event.key in [pygame.K_8, pygame.K_KP8]:
                    cell_val_input = 8
                if event.key in [pygame.K_9, pygame.K_KP9]:
                    cell_val_input = 9
                if event.key in [
                        pygame.K_BACKSPACE, pygame.K_DELETE, pygame.K_0,
                        pygame.K_KP0
                ]:
                    cell_val_input = 0
                if cell_val_input is not None:
                    board.update_selected_cell(cell_val_input)
            if event.type == pygame.MOUSEBUTTONUP:
                # TODO: Clicking seems weird -- colliderect is true no matter where on screen you click.
                #       However, it's currently working well enough. Should investigate this behavior in the future
                mouse_pos = pygame.mouse.get_pos()
                mouse_rect = pygame.Rect(mouse_pos, (1, 1))
                if board.rect.colliderect(mouse_rect):
                    board.click(mouse_pos)
                if menu.rect.colliderect(menu.rect):
                    menu_option = menu.click(
                        (mouse_pos[0], SCREEN_HEIGHT - mouse_pos[1]))
                    if menu_option == menu.BTN_CHECK_SOLUTION:
                        if check_solution(board.board_state):
                            print(
                                'Solved!'
                            )  # TODO: Some kind of victory screen that leads to next level?
                        else:
                            print('Try Harder')

        board.update()
        display.blit(board_surface, (0, 0))

        menu.update()
        display.blit(menu_surface, (0, SCREEN_HEIGHT - 100))

        pygame.display.update()
        sever_tick.tick(FRAMERATE_LIMIT)
示例#14
0
 def setUp(self):
     data = json.load(open('data/hipstercoffee.json'))
     self.price_data = data[0]['prices'][0]
     self.menu = Menu('data/hipstercoffee.json')
示例#15
0
文件: baseapp.py 项目: softlog/web
class AppBuilder(object):
    """
        Classe principal do Builder de Aplicação. Responsável por 
        registrar as views, inicializar base de permissões.
    """
    baseviews = []
    security_manager_class = None
    # Flask app
    app = None
    # Database Session
    session = None
    # Security Manager Class
    sm = None
    # Babel Manager Class
    bm = None
    # dict with addon name has key and intantiated class has value
    addon_managers = None
    # temporary list that hold addon_managers config key
    _addon_managers = None

    baseviews = []
    menu = None
    endpoint = None
    route_base = None
    indexview = None
    template_folder = None
    static_folder = None
    static_url_path = None

    template_filters = None

    model_string_conexoes = None

    string_conexoes = None

    uris = None

    def __init__(self, app, session):

        self.menu = Menu()
        self.app = app
        self.session = session
        self.base_template = "frontend/base_onepage.html"
        self.template_folder = "templates"
        self.static_folder = "files/static"
        self.security_manager_class = SecurityManager
        self.sm = self.security_manager_class(self)
        self.indexview = IndexView
        self._add_admin_views()
        #self._add_addon_views()
        self._add_menu_permissions()
        self._add_global_filters()
        self.model_string_conexoes = SQLAInterface(StringConexoes, session)
        #session.close()

        #self._add_uris()

        if not self.app:
            for baseview in self.baseviews:
                # instantiate the views and add session
                self._check_and_init(baseview)
                # Register the views has blueprints
                self.register_blueprint(baseview)
                # Add missing permissions where needed
                self._add_permission(baseview)

    def _check_and_init(self, baseview):
        # If class if not instantiated, instantiate it
        # and add db session from security models.
        if hasattr(baseview, 'datamodel'):
            if baseview.datamodel.session is None:
                baseview.datamodel.session = self.session
        if hasattr(baseview, '__call__'):
            baseview = baseview()
        return baseview

    def add_view(self,
                 baseview,
                 name,
                 href="",
                 icon="",
                 label="",
                 category="",
                 category_icon="",
                 category_label=""):
        """
        Add your views associated with menus using this method.

        :param baseview:
            A BaseView type class instantiated or not.
            This method will instantiate the class for you if needed.
        :param name:
            The string name that identifies the menu.
        :param href:
            Override the generated href for the menu.
            You can use an url string or an endpoint name
            if non provided default_view from view will be set as href.
        :param icon:
            Font-Awesome icon name, optional.
        :param label:
            The label that will be displayed on the menu,
            if absent param name will be used
        :param category:
            The menu category where the menu will be included,
            if non provided the view will be acessible as a top menu.
        :param category_icon:
            Font-Awesome icon name for the category, optional.
        :param category_label:
            The label that will be displayed on the menu,
            if absent param name will be used

        Examples::

            appbuilder = AppBuilder(app, db)
            # Register a view, rendering a top menu without icon.
            appbuilder.add_view(MyModelView(), "My View")
            # or not instantiated
            appbuilder.add_view(MyModelView, "My View")
            # Register a view, a submenu "Other View" from "Other" with a phone icon.
            appbuilder.add_view(MyOtherModelView, "Other View", icon='fa-phone', category="Others")
            # Register a view, with category icon and translation.
            appbuilder.add_view(YetOtherModelView(), "Other View", icon='fa-phone',
                            label=_('Other View'), category="Others", category_icon='fa-envelop',
                            category_label=_('Other View'))
            # Add a link
            appbuilder.add_link("google", href="www.google.com", icon = "fa-google-plus")
        """
        baseview = self._check_and_init(baseview)
        #log.info(LOGMSG_INF_FAB_ADD_VIEW.format(baseview.__class__.__name__, name))

        if not self._view_exists(baseview):
            baseview.appbuilder = self
            self.baseviews.append(baseview)
            #self._process_inner_views()
            if self.app:
                self.register_blueprint(baseview)
                self._add_permission(baseview)
        self.add_link(name=name,
                      href=href,
                      icon=icon,
                      label=label,
                      category=category,
                      category_icon=category_icon,
                      category_label=category_label,
                      baseview=baseview)
        return baseview

    def add_link(self,
                 name,
                 href,
                 icon="",
                 label="",
                 category="",
                 category_icon="",
                 category_label="",
                 baseview=None):
        """
            Add your own links to menu using this method

            :param name:
                The string name that identifies the menu.
            :param href:
                Override the generated href for the menu.
                You can use an url string or an endpoint name
            :param icon:
                Font-Awesome icon name, optional.
            :param label:
                The label that will be displayed on the menu,
                if absent param name will be used
            :param category:
                The menu category where the menu will be included,
                if non provided the view will be accessible as a top menu.
            :param category_icon:
                Font-Awesome icon name for the category, optional.
            :param category_label:
                The label that will be displayed on the menu,
                if absent param name will be used

        """
        self.menu.add_link(name=name,
                           href=href,
                           icon=icon,
                           label=label,
                           category=category,
                           category_icon=category_icon,
                           category_label=category_label,
                           baseview=baseview)
        if self.app:
            self._add_permissions_menu(name)
            if category:
                self._add_permissions_menu(category)

    def add_view_no_menu(self, baseview, endpoint=None, static_folder=None):
        """
            Add your views without creating a menu.

            :param baseview:
                A BaseView type class instantiated.

        """
        baseview = self._check_and_init(baseview)
        #log.info(LOGMSG_INF_FAB_ADD_VIEW.format(baseview.__class__.__name__, ""))

        if not self._view_exists(baseview):
            baseview.appbuilder = self
            self.baseviews.append(baseview)
            #self._process_inner_views()
            if self.app:
                self.register_blueprint(baseview,
                                        endpoint=endpoint,
                                        static_folder=static_folder)
                #self._add_permission(baseview)
        #else:
        #log.warning(LOGMSG_WAR_FAB_VIEW_EXISTS.format(baseview.__class__.__name__))
        return baseview

    def _view_exists(self, view):
        for baseview in self.baseviews:
            if baseview.__class__ == view.__class__:
                return True
        return False

    def register_blueprint(self, baseview, endpoint=None, static_folder=None):
        self.get_app.register_blueprint(
            baseview.create_blueprint(self,
                                      endpoint=endpoint,
                                      static_folder=static_folder))

    def _add_uris(self):
        qt, string_conexoes = self.model_string_conexoes.query()

        uris = {}
        for s in string_conexoes:
            uri = 'postgresql://%s:%s@%s:%s/%s' % (
                s.usuario.strip(), s.senha.strip(), s.host.strip(), str(
                    s.port), s.banco_dados.strip())

            uris[str(s.id_string_conexao)] = uri

    def get_uri(self, id_string_conexao):

        return self.uris.get(str(id_string_conexao))

    def _add_global_filters(self):
        self.template_filters = TemplateFilters(self.get_app, self.sm)

    @property
    def get_app(self):
        """
            Get current or configured flask app

            :return: Flask App
        """
        if self.app:
            return self.app
        else:
            return current_app

    @property
    def get_session(self):
        """
            Get the current sqlalchemy session.

            :return: SQLAlchemy Session
        """
        return self.session

    @property
    def app_name(self):
        """
            Get the App name

            :return: String with app name
        """
        return self.get_app.config['APP_NAME']

    @property
    def app_theme(self):
        """
            Get the App theme name

            :return: String app theme name
        """
        return self.get_app.config['APP_THEME']

    @property
    def app_icon(self):
        """
            Get the App icon location

            :return: String with relative app icon location
        """
        return self.get_app.config['APP_ICON']

    @property
    def languages(self):
        return self.get_app.config['LANGUAGES']

    @property
    def version(self):
        """
            Get the current F.A.B. version

            :return: String with the current F.A.B. version
        """
        return VERSION_STRING

    def _add_admin_views(self):
        """
            Registers indexview, utilview (back function), babel views and Security views.
        """
        self.indexview = self._check_and_init(self.indexview)
        self.add_view_no_menu(self.indexview)
        self.add_view_no_menu(UtilView())
        #self.bm.register_views()
        self.sm.register_views()

    @property
    def get_url_for_index(self):
        return url_for('%s.%s' %
                       (self.indexview.endpoint, self.indexview.default_view))

    @property
    def get_url_for_userinfo(self):
        return url_for('%s.%s' % (self.sm.user_view.endpoint, 'userinfo'))

    def _add_permission(self, baseview):
        self.sm.add_permissions_view(baseview.base_permissions,
                                     baseview.__class__.__name__)
        try:
            pass
            #self.sm.add_permissions_view(baseview.base_permissions, baseview.__class__.__name__)
        except Exception as e:
            log.error(LOGMSG_ERR_FAB_ADD_PERMISSION_VIEW.format(str(e)))

    def _add_permissions_menu(self, name):
        try:
            self.sm.add_permissions_menu(name)
        except Exception as e:
            log.error(LOGMSG_ERR_FAB_ADD_PERMISSION_MENU.format(str(e)))

    def _add_menu_permissions(self):
        for category in self.menu.get_list():
            self._add_permissions_menu(category.name)
            for item in category.childs:
                #dont add permission for menu separator
                if item.name != '-':
                    self._add_permissions_menu(item.name)
示例#16
0
class MenuTest(unittest.TestCase):
    def setUp(self):
        self.my_cycle_menus = CycleMenus()
        self.my_menu = Menu(menu_list[0], [], header, message, footer,
                            self.my_cycle_menus.send_choice)
        self.old_stdout = sys.stdout
        f = open(os.devnull, 'w')
        sys.stdout = f

    def tearDown(self):
        sys.stdout = self.old_stdout

    def test_enter_blank_line_is_valid_selection(self):
        self.my_menu.read()
        self.my_menu.selection = ''
        t_1 = self.my_menu.validate_selection()
        t_2 = self.my_menu.good_combination()
        self.assertTrue(t_1 and t_2)

    def test_enter_blank_line_selects_default_value(self):
        self.my_menu.read()
        self.my_menu.selection = ''
        cur_dflt = self.my_menu.get_current_default()
        self.assertEqual(cur_dflt, 7)

    def test_enter_default_values_number_selects_default_value(self):
        self.my_menu.read()
        self.my_menu.reformat_selection('7')
        self.my_menu.send_choice(self.my_menu.reformatted_selection)
        self.assertEqual(self.my_cycle_menus.chosen[0][1],
                         self.my_menu.default[0])

    def test_enter_nondefault_values_number_selects_nondefault_value(self):
        self.my_menu.read()
        self.my_menu.reformat_selection('15')
        self.my_menu.send_choice(self.my_menu.reformatted_selection)
        self.assertEqual(self.my_cycle_menus.chosen[0][1], '15')

    def test_menu_does_not_accept_out_of_range_value(self):
        self.my_menu.read()
        self.my_menu.selection = '16\n'
        is_valid = self.my_menu.validate_selection()
        self.assertFalse(is_valid)

    def test_out_of_range_value_gives_correct_error_message(self):
        self.my_menu.read()
        self.my_menu.selection = '16\n'
        self.my_menu.validate_selection()
        self.assertEqual(self.my_menu.err_msg,
                         '\n\nSorry. Value entered is out of range.')

    def test_menu_does_not_accept_non_integer_value(self):
        self.my_menu.read()
        self.my_menu.selection = 'y\n'
        is_valid = self.my_menu.validate_selection()
        self.assertFalse(is_valid)

    def test_non_integer_value_gives_correct_error_message(self):
        self.my_menu.read()
        self.my_menu.selection = 'y\n'
        self.my_menu.validate_selection()
        self.assertEqual(self.my_menu.err_msg,
                         '\n\nPlease input an integer value')
示例#17
0
from app.menu import Menu
from app.accountBuilder import AccountBuilder
from app.database import AccountDatabase

try:
    name = (input("Please provide account name: "))
    accountList = AccountDatabase()
    currentAccount = accountList.load_account_by_account_name(name)
except Exception:
    print('\n Not an account\n')
else:
    ui = Menu(currentAccount)
    ui.start_menu()

# write to json on exit
accountList.save_account_by_account_name(name, currentAccount.balance)
示例#18
0
 def setUp(self):
     data = json.load(open('data/hipstercoffee.json'))
     self.price_data = data[0]['prices'][0]
     self.menu = Menu('data/hipstercoffee.json')
示例#19
0
def run():
    admin_user = load_initial_data()
    menu = Menu(admin_user)
    menu.render()
示例#20
0
 def setUp(self):
     menu = Menu('data/hipstercoffee.json')
     self.till = Till(menu=menu)