예제 #1
0
파일: app.py 프로젝트: robee/Connoisseur
    def post(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return

        message = self.request.get("doc")
        logging.info(str(self.request))
        logging.info(message)
        rest_id = self.request.get("restaurant_id")
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.headers.add_header(
            "Access-Control-Allow-Headers",
            "X-Requested-With, Content-Type, Access-Control-Allow-Headers Origin, Access-Control-Allow-Origin, Access-Control-All",
        )

        if message == "":
            menu_id = Menu.get_menus_by_rest_id(rest_id)[0].menu_id
            doc = DocFromModels(rest_id, menu_id)
            logging.info(doc)
            self.response.out.write(doc)
        elif ModelsFromDoc(message, rest_id):
            menu_id = Menu.get_menus_by_rest_id(rest_id)[0].menu_id
            doc = DocFromModels(rest_id, menu_id)
            self.response.out.write(doc)
        else:
            self.response.out.write("ERROR: Incomplete or Malformed doc")
예제 #2
0
def parse_page(request):
	url = "http://services.housing.berkeley.edu/FoodPro/dining/static/todaysentrees.asp"
	br = mechanize.Browser()
	data = br.open(url).get_data()
	lists = list(br.links(text_regex=re.compile("")))
	counter = 0
	name_counter = 0
	for lst in lists:
		food = []
		if lst.text != "Click To View[IMG]Menu Details" and lst.text != "[IMG]" and lst.text != "sitemap" and lst.text != "dc tabling" and lst.text != "jobs" and lst.text != "comment cards" and lst.text != "contact us" and lst.text != "*****@*****.**" and lst.text != "Nutritive Analysis" and lst.text != "" and lst.text != "cal club" and lst.text != "cal care packs" and lst.text != "student meal plans" and lst.text != "faculty/staff meal plans":
			location_name = lst.attrs[0][1].split('&')
			counter = 0
			name_counter = 0
			for name in location_name:
				if counter == 1:
					name_counter = 0
					name = name.split('=')
					for n in name:
						if name_counter == 1:
							place = n.replace('+', '')
							if place in place_list:
								food = place_list[place]
								food.append(lst.text)
								place_list[place] = food
							else:
								food.append(lst.text)
								place_list[place] = food
						name_counter += 1
				counter += 1
	for k, foods in place_list.items():
		for food in foods:
			f = Menu(food=food)
			f.save()
    def SetUp_Gdrive_Directory(self):
        if self.data['Create_directory'] == "False" :
            db.create_all()
            ### Public Folder
            for i in self.data['Public_Folder']:
                _id , name , Link = self.Create_directory(self.data,i,Type='Public')
                new_folder = Menu(name = name , uri = Link , file_id = _id)
                db.session.add(new_folder)
                db.session.commit()
                print('create {}'.format(i))
                for j in self.data['Subfolder']:
                    sub_id , sub_name , sub_Link= self.Create_subdirectory(self.data,name+"-"+j,Type='Public',parent_id=_id)
                    new_subfolder = Submenu(name = sub_name , uri = sub_Link , file_id = sub_id , menu = new_folder)
                    db.session.add(new_subfolder)
                    db.session.commit()
                    print('create {}'.format(j))

            ### Private Folder
            for i in self.data['Private_Folder']:
                _id , name , Link= self.Create_directory(self.data,i,Type='Private')
                new_folder = Menu(name = name , uri = Link , file_id = _id)
                db.session.add(new_folder)
                db.session.commit()
                print('create {}'.format(i))
                for j in self.data['Subfolder']:
                    sub_id , sub_name , sub_Link = self.Create_subdirectory(self.data,name+"-"+j,Type='Private',parent_id=_id)
                    new_subfolder = Submenu(name = sub_name , uri = sub_Link , file_id = sub_id , menu = new_folder)
                    db.session.add(new_subfolder)
                    db.session.commit()
                    print('create {}'.format(j))

            self.data['Create_directory'] = "True"
        else:
            print('directory was already Create')
예제 #4
0
 def mutate_and_get_payload(cls, input, context, info):
     menu = Menu(
         availability_start_time=input.get('availability_start_time'),
         availability_end_time=input.get('availability_end_time'),
         quantity=input.get('quantity'),
         food=Food.objects.get(name=input.get('food')))
     menu.save()
     return NewMenu(menu=menu)
예제 #5
0
def load_fixtures():
    with db_session:
        main = Menu(name='MagicMenu', global_=True, parent=1)

    with db_session:
        Menu(name='Create menu', global_=True, parent=main.id)
        Menu(name='Update menu', global_=True, parent=main.id)
        Menu(name='Delete menu', global_=True, parent=main.id)
예제 #6
0
def step_impl(context):
    """
    :type context: behave.runner.Context
    """

    with db_session:
        menu = Menu[1]
        Menu(name='Create a menu', global_=True, parent=menu.id)
        Menu(name='Update a menu', global_=True, parent=menu.id)
        Menu(name='Delete a menu', global_=True, parent=menu.id)
예제 #7
0
파일: views.py 프로젝트: zhquan/PFG
def home(request):
    json_data = open('/home/quan/Proyecto/restaurante/static/menu.json')
    data1 = json.load(json_data)
    json_data.close()
    for a in data1[0]['postre']:
        try:
            T_Menu = Menu.objects.get(plato = a)
        except Menu.DoesNotExist:
            T_Menu = Menu(tipo = 'postre', plato = a)
            T_Menu.save()
    for b in data1[0]['entrante']:
        try:
            T_Menu = Menu.objects.get(plato = b)
        except Menu.DoesNotExist:
            T_Menu = Menu(tipo = 'entrante', plato = b)
            T_Menu.save()
    for c in data1[0]['carne']: 
        try:
            T_Menu = Menu.objects.get(plato = c)
        except Menu.DoesNotExist:
            T_Menu = Menu(tipo = 'carne', plato = c)
            T_Menu.save()
    
#    return HttpResponse("Save go to <a href=http://localhost:8800/index.html>GranChino.com</a>")
#def index(request):
    return render_to_response('index.html')
예제 #8
0
class MenuParser(Parser):
    def __init__(self, parent, metadata):
        self.parent = parent
        self.menu = Menu(metadata)
        self.indent = None

        self.choice = None

    def parse_metadata(self, metadata, stack):
        if self.indent is None:
            self.indent = metadata.indent

        if metadata.indent < self.indent:
            self.close(metadata, stack)
            return

        self.parse_choice(metadata, stack) or \
        self.parse_description(metadata, stack)

    def parse_description(self, metadata, stack):
        match = regex_description.match(metadata.line)
        if match:
            description = match["description"]
            self.menu.description = description
            return True
        return False

    def parse_choice(self, metadata, stack):
        from .ContextParser import ContextParser
        match = regex_choice.match(metadata.line)
        if match:
            description = match["choice"]
            choice = Choice(description, metadata)
            self.choice = choice
            self.menu.add_choice(choice)
            parser = ContextParser(self, metadata)
            stack.push(parser)
            return True
        return False

    def close(self, metadata, stack):
        stack.pop()
        stack.parse_metadata(metadata)

    def on_child_pop(self, child):
        self.choice.context = child.model
        self.choice = None

    @property
    def model(self):
        return self.menu
예제 #9
0
def create_menu():
    if not request.json:
        abort(404)
    menu = Menu()
    db.session.add(menu)
    menu.load(request.json)
    db.session.commit()
    for meal in request.json['meals']:
        meal['menu_id'] = menu.id
        mm = MenuMeal()
        mm.load(meal)
        db.session.add(mm)
    db.session.commit()
    return jsonify({'menu': menu.serialize}), 201
예제 #10
0
def save_menu(request):
	label = request.REQUEST["label"]
	icon = request.REQUEST["icon"]
	tooltip = request.REQUEST["tooltip"]
	command = request.REQUEST["command"]
	pid = request.REQUEST["parent"]
	id = request.REQUEST["id"]
	if pid == "-1":
		parent = None
	else:
		parent = Nav.objects.get(pk=int(pid))
	if id == "-1":
		menu = Nav()
		create = True
	else:
		menu = Nav.objects.get(pk=int(id))
		create = False

	menu.label = label
	menu.icon = icon
	menu.tooltip = tooltip
	menu.command = command
	menu.parent = parent
	menu.save()
	obj = {"id": menu.pk, "create": create}
	return HttpResponse(json.dumps(obj))
예제 #11
0
파일: api.py 프로젝트: mattzshum/picco
    def create_menu(restaurant_id):
        body = request.get_json()

        new_tod_menu = body.get('tod_menu', None)
        new_name = body.get('name', None)
        try:
            menu = Menu(tod_menu=new_tod_menu, name=new_name)
            Menu.insert(menu)

            return jsonify({
                'success':True,
                'created':menu.id
            })
        except Exception as E:
            abort(422)
예제 #12
0
파일: app.py 프로젝트: robee/Connoisseur
def DocFromModels(rest_id, menu_id):
    # try:
    rest = Restaurant.get_by_id(rest_id)
    menu = Menu.get_by_id(menu_id)
    ui_profile = UIProfile.get_by_menu(menu)
    menuitems = MenuItem.get_by_menu(menu)

    grab_vars = lambda item: deepcopy(vars(item)["_entity"])

    obj = {}
    obj["menu_id"] = menu.menu_id
    obj["restaurant_id"] = rest.restaurant_id
    obj["restaurant_name"] = rest.name
    obj["menu_name"] = menu.name
    obj["ui_profile"] = grab_vars(ui_profile)
    obj["ui_profile"]["menu"] = "null"
    obj["menuitems"] = {}

    for menuitem in menuitems:
        category = menuitem.category
        menu_item_dict = grab_vars(menuitem)
        menu_item_dict["menu"] = "null"
        if obj["menuitems"].has_key(category):
            obj["menuitems"][category].append(menu_item_dict)
        else:
            obj["menuitems"][category] = [menu_item_dict]

    return json.dumps(obj)
예제 #13
0
def add_menu():
    print("--------------------------------------------------+++++++++++++++++++++++++++++")
    # 从前端Ajax请求中获取数据
    name = request.json.get('name', None)
    enname = request.json.get('enname', None)
    fid = request.json.get('fid', None)
    url = request.json.get('url', None)
    icon = request.json.get('icon', None)
    component = request.json.get('component', None)
    status = request.json.get('status', None)
    type = request.json.get('type', None)
    order = request.json.get('order', None)

    print(".........................................")
    print(name)

    menu = Menu(name=name, en_name=enname, fid=fid, url=url, component=component, icon=icon,
                status=status, type=type, order=order)

    status_code = None

    try:
        db.session.add(menu)
        db.session.commit()
        status_code = 200
    except Exception as err:
        print(err)
        status_code = 500

    return jsonify(), status_code
예제 #14
0
    def test_add_custom_menu_entry(self):
        assert self.is_only_for_admins('/menu/0/add_custom_menu_entry/',
                                       method='post')

        self.login_as_admin()

        menu = Menu(name='My name')
        db.session.add(menu)
        db.session.commit()

        response = self.client.post(
            '/menu/%s/add_custom_menu_entry/' % menu.id,
            data={
                'title': 'ActiveDriverDB repository',
                'url': 'https://github.com/reimandlab/ActiveDriverDB'
            },
            follow_redirects=True)
        assert response.status_code == 200

        entries = CustomMenuEntry.query.filter_by(menu_id=menu.id).all()
        assert len(entries) == 1
        assert entries[0].title == 'ActiveDriverDB repository'
        assert entries[0].url == 'https://github.com/reimandlab/ActiveDriverDB'

        self.logout()
예제 #15
0
def reindex_all_menus():
    g.cache.clear()
    menus = Menu.query().fetch()
    for m in menus:
        m.put()

    return "done"
예제 #16
0
    def add_menu(self):
        try:
            name = request.form['name']

            if not name:
                raise ValidationError('Menu name is required')

            menu = Menu(name=name)
            db.session.add(menu)
            db.session.commit()

            flash('Added new menu: ' + menu.name, 'success')

        except ValidationError as error:
            flash(error.message, 'warning')

        except IntegrityError:
            db.session.rollback()
            flash(
                'Menu with name: ' + menu.name + ' already exists.' +
                ' Please, change the name and try again.',
                'danger'
            )

        return redirect(url_for('ContentManagementSystem:list_menus'))
예제 #17
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def menu_settings(self, menu_id=0):
     if request.method == 'GET':
         itemTmpl = ''
         try:
             itemTmpl = Menu.get(id=menu_id).template
         except Menu.DoesNotExist, e:
             print 'Error while loading item template, %s' % e
         return itemTmpl
예제 #18
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def menu_settings(self, menu_id=0):
     if request.method == 'GET':
         itemTmpl = ''
         try:
             itemTmpl = Menu.get(id=menu_id).template
         except Menu.DoesNotExist, e:
             print 'Error while loading item template, %s' % e
         return itemTmpl
예제 #19
0
def createMenu(Id, Menutext, Menulink = None, Target = None, Confirm = None):
  m = Menu.get_or_insert('%s' % (Id))
  m.Id = Id
  m.Menutext = Menutext
  m.Menulink = Menulink
  m.Target = Target
  m.Confirm = Confirm
  return m
예제 #20
0
파일: app.py 프로젝트: robee/Connoisseur
 def get(self):
     if AUTH_ENABLED and not verifyMessage(self.request):
         self.response.out.write("AUTH FAILED")
         return
     rest_id = self.request.get("restaurant_id")
     menu_id = menu_id = Menu.get_menus_by_rest_id(rest_id)[0].menu_id
     self.response.headers["Access-Control-Allow-Origin"] = "*"
     self.response.out.write(DocFromModels(rest_id, menu_id))
예제 #21
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def index(self):
     menu = Menu.select()
     g_m = GeneralMeta.get_or_create(id=1)
     form = MetaDataForm(obj=g_m)
     categories = Category.select()
     return self.render('admin/index.html',
                        categories=categories,
                        menu=menu,
                        meta_form=form)
예제 #22
0
def Main():
    mission_factory = MissionFactory()
    # missions = mission_factory.create_missions(mission_data)
    dispatcher = DroneDispatcher()
    library = MissionLibrary()
    menu_methods = {
        "ls": library.get_mission_names,
        "load": mission_factory.create_missions_from_file,
        "set port": dispatcher.set_port,
        "set host": dispatcher.set_host,
        "get port": dispatcher.get_port,
        "get host": dispatcher.get_host,
        "get mission": lambda name: library.get_mission(name),
        "save missions": lambda missions: library.add_missions(missions),
        "mission": dispatcher.send_drone_on_mission,
    }
    menu = Menu(menu_methods)
    menu.display_menu()
예제 #23
0
def main():
    path = Path()
    menu = Menu()
    menu.instructions()
    while True:
        # menu.de_entrada()
        try:
            excel_filename = input("Ingresa el nombre del archivo de excel: ")
            excel_exists = path.check_existence(excel_filename)
            if excel_exists:

                # File found notification for the user.
                menu.file_found()

                # Tras haber verificado que el archivo existe, se crea el path para cargar el libro con openpyxl.
                excel_file_path = path.book_path(excel_filename)

                # Book settings
                book = Book(excel_file_path)
                book_headers = book.get_headers()
                book_rows = book.get_list_of_rows()

                app_name = input(
                    "Ingresa el nombre del app de tu proyecto Django: ")
                model_name = input("Ingresa el nombre del modelo de tu app: ")

                fx = Fixture(
                    app=app_name,
                    model=model_name,
                    headers=book_headers,
                    list_of_fields=book_rows,
                )
                fx.create_objects()
                fx.create_json_file(path.json_dir)

                menu.task_completed()
                break
            else:
                menu.file_not_found()

        except ValueError:
            print("Ingresa el nombre del archivo.")
            print("")
            pass
예제 #24
0
def loaddir(directory, clear=False):
    if clear:
        MenuItem.objects.all().delete()
        Menu.objects.all().delete()
    def _parse_children(parent, parent_obj):
        if 'children' not in parent:
            return
        for ch in parent['children']:
            child = MenuItem(name=ch['name'], url=ch['url'], title=ch.get('title', None), parent=parent_obj)
            child.save()
            _parse_children(ch, child)
    for menufile in os.listdir(directory):
        if menufile[0] == '.': continue
        for menu in yaml.load_all(file(path.join(directory,menufile))):
            fake_root = MenuItem(name='<fake-root>', url='fake-root-you-shouldnt-be-seeing-this-bro')
            fake_root.save()
            menu_obj = Menu(name=menu['name'], fake_root=fake_root)
            menu_obj.save()
            _parse_children(menu, fake_root)
예제 #25
0
파일: app.py 프로젝트: robee/Connoisseur
 def post(self):
     if AUTH_ENABLED and not verifyMessage(self.request):
         self.response.out.write("AUTH FAILED")
         return
     menu_id = self.request.get("menu_id")
     self.response.headers["Access-Control-Allow-Origin"] = "*"
     if Menu.delete_by_id(menu_id):
         self.response.out.write("Menu Successfully Deleted")
     else:
         self.response.out.write("ERROR: Could not delete")
예제 #26
0
파일: main.py 프로젝트: hafsjold/snvrepos
 def get(self):
     try:
         menu_count = Menu.all().count()
     except:
         menu_count = 0
     if menu_count == 0:
         deleteMenuAndUserGroup()
         createMenuAndUserGroup()
         memcache.flush_all()
     self.redirect("/adm")
예제 #27
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def index(self):
 	menu = Menu.select()
     g_m = GeneralMeta.get_or_create(id=1)
     form = MetaDataForm(obj=g_m)
 	categories = Category.select()
     return self.render(
         'admin/index.html',
         categories=categories,
         menu=menu,
         meta_form = form
     )
예제 #28
0
def add_menu():
    if request.method == 'GET':
        menu = Menu.query.filter_by(parent='root').all()
        return render_template("admin/add-menu.html", main_menu=menu)

    if request.method == 'POST':
        name = request.form['name']
        parent_id = int(request.form['secondary'])
        if parent_id != 0:
            parent = Menu.query.filter_by(id=parent_id).first()
            parent = parent.name
        else:
            parent = 'root'
        menu = Menu(name, parent)
        menu.save()

        main_menu = Menu.query.filter_by(parent='root').all()
        secondary_menu = {}
        for item in main_menu:
            secondary_menu[item.id] = Menu.query.filter_by(parent=item.name).all()
        return render_template('admin/list.html', main_menu=main_menu, secondary_menu=secondary_menu)
예제 #29
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def new_menu_item(self):
     form = request.form
     itemTitle = form.get('itemTitle', None)
     itemUrl = form.get('itemUrl', None)
     itemTemplate = form.get('itemTemplate', None)
     itemUtilityTemplate = form.get('itemUtilityTemplate', None)
     itemSlug = form.get('itemSlug', None)
     menu = Menu()
     menu.title = itemTitle
     menu.url = itemUrl
     menu.template = itemTemplate
     menu.utility_template = itemUtilityTemplate
     menu.slug = itemSlug
     status = None
     try:
         status = menu.utility_template
         menu.save()
     except Exception, e:
         status = u'Помилка під час зберігання'
예제 #30
0
파일: app.py 프로젝트: robee/Connoisseur
    def post(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return
        rest_id = self.request.get("restaurant_id")
        menu_name = self.request.get("menu_name")

        rest = Restaurant.get_by_id(rest_id)
        if not rest:
            self.response.out.write("Invalid restaurant_id")
            return

        if Menu.get_menus_by_rest_id(rest_id):
            self.resonse.out.write("Cant create another menu for this restaurant.  It already has one")
            return

        menu = Menu.create(menu_name, rest)
        uiProfile = UIProfile.create(menu)
        menu_item_1 = MenuItem.create("Starter Item 1", menu, 10.00, "Appy", "This is a sample menu Item")
        menu_item_2 = MenuItem.create("Starter Item 2", menu, 11.00, "Drink", "This is a sample menu Item")
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.headers.add_header("Access-Control-Allow-Headers", "X-Requested-With")
        self.response.out.write(DocFromModels(rest_id, menu.menu_id))
예제 #31
0
    def test_remove_menu(self):
        assert self.is_only_for_admins('/remove_menu/0')

        menu = Menu(name='Some menu')
        db.session.add(menu)
        db.session.commit()

        self.login_as_admin()

        m_id = menu.id
        assert Menu.query.get(m_id) == menu
        self.client.get('/remove_menu/%s' % m_id)
        assert Menu.query.get(m_id) is None

        self.logout()
예제 #32
0
파일: app.py 프로젝트: robee/Connoisseur
    def post(self):
        auth_code = self.request.get("auth_code")
        if auth_code != PASSCODE and AUTH_ENABLED:
            self.response.out.write("AUTH FAILED")
            return

        rest = Restaurant.create(self.request.get("name"))
        return_obj = {"secret_key": rest.secret_key, "restaurant_id": rest.restaurant_id}

        menu = Menu.create("menu", rest)
        uiProfile = UIProfile.create(menu)
        menu_item_1 = MenuItem.create("Starter Item 1", menu, 10.00, "Appy", "This is a sample menu Item")
        menu_item_2 = MenuItem.create("Starter Item 2", menu, 11.00, "Drink", "This is a sample menu Item")

        self.response.headers["Access-Control-Allow-Origin"] = "*"
        self.response.out.write(json.dumps(return_obj))
예제 #33
0
def deleteMenuAndUserGroup():
  try:
    for m in MenuMenuLink.all():
      m.delete()
  except:
    pass
  try:  
    for m in Menu.all():
      m.delete()
  except:
    pass
  try:
    for m in UserGroup.all():
      m.delete()
  except:
    pass
예제 #34
0
def crawl():
    # make web request
    soup = http_get(BASE_URL + MENU_URL)
    # locate html data
    html = soup.body.contents[-2].table.tbody.contents[3].td.table.contents

    # stores food that has already been added to the table
    food_cache = {}

    # extract data
    for MEAL in MEALS:
        meal_index = MEALS[MEAL]
        meal_data = html[meal_index]

        for DINING_COMMON in DINING_COMMONS:
            dc_index = DINING_COMMONS[DINING_COMMON]
            if len(meal_data.contents) <= dc_index:
                break
            meal_dc_data = meal_data.contents[dc_index]

            for entry in meal_dc_data.find_all('a'):
                meal_name = entry.contents[0].string
                meal_name, gluten_free = truncate_meal_name(meal_name)

                # skip the "Nutritive Analysis" link
                if 'nutritive analysis' in meal_name.lower():
                    continue

                # create database models object
                if meal_name in food_cache:
                    food_obj = food_cache[meal_name]
                else:  # food is not located in local cache
                    # check if food is in database
                    food_obj = Food.query.filter_by(name=meal_name).first()
                    # not found in database, crawl page
                    if food_obj is None:
                        food_obj = extract_food_info(entry)
                        db.session.add(food_obj)

                        # add food to the cache
                    food_cache[meal_name] = food_obj

                menu_obj = Menu(date = get_date(), location = LOCATION_TO_ENUM[DINING_COMMON], \
                meal = MEAL_TO_ENUM[MEAL], food = food_obj)

                db.session.add(menu_obj)
    db.session.commit()
예제 #35
0
파일: app.py 프로젝트: robee/Connoisseur
def ModelsFromDoc(jsonString, rest_id):
    try:
        obj = json.loads(jsonString)

        profile_id = obj["ui_profile"]["profile_id"]

        # Create or Update Rest
        rest = Restaurant.get_by_id(rest_id)
        rest.name = obj["restaurant_name"]

        # Create or Update Menu
        menu = Menu.get_menus_by_rest_id(rest_id)[0]

        menu.name = obj["menu_name"]
        menu.resturant = rest

        # Create or Update UI Profile
        UIProfile.delete_by_menu(menu)
        ui_profile = UIProfile.create(menu)
        ui_profile.template = obj["ui_profile"]["template"]
        ui_profile.color = obj["ui_profile"]["color"]
        ui_profile.font = obj["ui_profile"]["font"]
        ui_profile.logo_url = obj["ui_profile"]["logo_url"]
        # logging.info(str(obj))
        # Create or Update menuitems

        MenuItem.delete_by_menu(menu)
        menu_items_dict = obj["menuitems"]
        logging.info(type(menu_items_dict))
        for category in menu_items_dict.keys():
            category_list = menu_items_dict[category]
            for menu_item_dict in category_list:
                menuitem = MenuItem.create(
                    menu_item_dict["name"],
                    menu,
                    menu_item_dict["price"],
                    category,
                    menu_item_dict["image"],
                    menu_item_dict["description"],
                )
                menuitem.put()
        ui_profile.put()
        menu.put()
        rest.put()
        return True
    except:
        return False
예제 #36
0
파일: views.py 프로젝트: skhaz/positagrill
    def post(self):
        upload = self.request.get('file')

        workbook = xlrd.open_workbook(file_contents=upload)
        worksheet = workbook.sheet_by_name(self.SHEET_NAME)
        rows = worksheet.nrows - 1
        columns = worksheet.ncols - 1
        current_column = 0

        while current_column < columns - 1:
            current_column += 1
            current_row = self.START_OFFSET
            while current_row < rows:
                foods = []
                date = None
                for row in xrange(current_row, current_row + self.ROW_OFFSET):
                    cell_type = worksheet.cell_type(row, current_column)
                    cell_value = worksheet.cell_value(row, current_column)

                    if cell_type == 3: # datetime
                        date = datetime(*xlrd.xldate_as_tuple(cell_value, workbook.datemode)).date()
                    else:
                        foods.append(cell_value)
                try:
                    menu = Menu.all() \
                        .filter('day =', int(date.day)) \
                        .filter('month =', int(date.month)) \
                        .filter('year =', int(date.year)) \
                        .get()

                    if menu is None:
                        menu = Menu()
                        menu.day = date.day
                        menu.month = date.month
                        menu.year = date.year

                    menu.foods = foods
                    menu.save()
                except:
                    pass

                current_row += self.ROW_OFFSET
        self.response.write('Ok')
예제 #37
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def new_menu_item(self):
     form = request.form
     itemTitle = form.get('itemTitle', None)
     itemUrl = form.get('itemUrl', None)
     itemTemplate = form.get('itemTemplate', None)
     itemUtilityTemplate = form.get('itemUtilityTemplate', None)
     itemSlug = form.get('itemSlug', None)
     menu = Menu()
     menu.title = itemTitle
     menu.url = itemUrl
     menu.template = itemTemplate
     menu.utility_template = itemUtilityTemplate
     menu.slug = itemSlug
     status = None
     try:
         status = menu.utility_template
         menu.save()
     except Exception, e:
         status = u'Помилка під час зберігання'
예제 #38
0
def add_inventory():
    incoming = request.get_json()
    if incoming is None:
        return jsonify(error=True), 403
    if request.method == 'POST':
        sp = {}
        query = db.session.query(Menu).filter_by(item=incoming['name']).all()
        if len(query) > 0:
            return jsonify(item = None, error='Item already exists'), 200
        item = incoming['name']
        description = incoming['description']
        category = incoming['category']
        definition = incoming['definition']
        if incoming['noSize'] is not None:
            sp['No Size'] = incoming['noSize']
        if incoming['oneSize'] is not None:
            sp['One Size'] = incoming['oneSize']
        if incoming['smallSize'] is not None:
            sp['Small'] = incoming['smallSize']
        if incoming['largeSize'] is not None:
            sp['Large'] = incoming['largeSize']
        for i in range(0, len(sp)):
            for size in sp:
                price = sp[size]
                try:
                    float(price)
                except:
                    return jsonify(item=None, error="Price is not in correct format"), 200
                new_item = Menu (
                    item = item,
                    price = price,
                    description = description,
                    definition = definition,
                    size = size,
                    availability = True,
                    category = category
                )
                try:
                    db.session.add(new_item)
                    db.session.commit()
                except Exception as e:
                    return jsonify(error=True), 408
        return jsonify(item='Added', error=None), 201
    else:
        return jsonify(error=True), 405
예제 #39
0
def get_ingredient(week):
    menu = Menu.select(
        MealkitIngredient.sku,
        Ingredients.name,
        Ingredients.price,
        Value(0).alias('Volume'),
        fn.SUM(MealkitIngredient.qty_needed),
        Mealkit.slot
    )\
        .join(Mealkit)\
        .join(MealkitIngredient)\
        .join(Ingredients)\
        .where(
        (Menu.version == 2) & (Menu.week == '2018-W29')).group_by(Mealkit.slot).tuples()
    for m in menu:
        print(m)
    print(menu.__len__())
    print('done')
예제 #40
0
    def test_add_page_menu_entry(self):
        assert self.is_only_for_admins('/menu/0/add_page_menu_entry/',
                                       method='post')

        menu = Menu(name='My name')
        page = Page(title='My page', address='my_address')
        db.session.add_all([menu, page])
        db.session.commit()

        self.login_as_admin()

        self.client.post('/menu/%s/add_page_menu_entry/' % menu.id,
                         data={'page_id': page.id},
                         follow_redirects=True)

        entries = PageMenuEntry.query.filter_by(menu_id=menu.id).all()
        assert len(entries) == 1
        assert entries[0].page == page

        self.logout()
예제 #41
0
파일: app.py 프로젝트: robee/Connoisseur
    def get(self):
        if AUTH_ENABLED and not verifyMessage(self.request):
            self.response.out.write("AUTH FAILED")
            return

        rest_id = self.request.get("restaurant_id")
        rest = Restaurant.get_by_id(rest_id)
        if not rest:
            self.response.out.write("Restaurant does not exist")
            return

        menu_id = Menu.get_menus_by_rest_id(rest_id)[0].menu_id
        doc = DocFromModels(rest_id, menu_id)
        logging.info(doc)
        doc_obj = json.loads(doc)
        self.response.headers.add_header("Access-Control-Allow-Origin", "*")
        self.response.headers.add_header(
            "Access-Control-Allow-Headers",
            "X-Requested-With, Content-Type, Access-Control-Allow-Headers Origin, Access-Control-Allow-Origin, Access-Control-All",
        )
        self.response.out.write(template.render("templates/index.html", doc_obj))
예제 #42
0
def create_menu(res_id):
    if not current_user.is_authenticated:
        flash('Please login.', 'danger')
        return redirect(url_for('login'))
        form = CreateMenuForm()
        form.res_id.data = res_id  # pre-populates res_id box of the form.
        if form.validate_on_submit():
            # NOTE: picture=form.picture_url.data; "picture" is a field in the database "class Menu", while "picture_url" is a field
            #       in the "wtform_fields.py" under the "class CreateMenuForm(FlaskForm)"
            menus = Menu(menu_name=form.menu_name.data,
                         address=form.address.data,
                         phone=form.phone.data,
                         price=form.price.data,
                         picture=form.picture_url.data,
                         res_id=form.res_id.data)
            db.session.add(menus)
            db.session.commit()
            flash('Menu and contact details added successfully')
            return redirect(url_for('display_restaurant',
                                    restaurant_id=res_id))
            # return redirect(url_for('display_menus'))
        return render_template('create_menu.html', form=form, res_id=res_id)
def create_menu(res_id):
    if not current_user.is_authenticated:
        flash('Please login.', 'danger')
        return redirect(url_for('login'))
    form = CreateMenuForm()
    form.res_id.data = res_id  # pre-populates res_id box of the form.
    if form.validate_on_submit():
        # https://github.com/lepture/flask-wtf/blob/534e1734b86c2f0907af131c11b981e6146ca57c/docs/form.rst#file-uploads
        f = form.uploaded_photo.data  # File upload will work without this line.
        filename = secure_filename(f.filename)  # File upload will work without this line.
        f.save(os.path.join('static/uploaded_photo', filename))  # File upload will work without this line.

        # NOTE: picture=form.picture_url.data; "picture" is a field in the database class "Menu", while "picture_url" is a field
        #       in the "wtform_fields.py" under the "class CreateMenuForm(FlaskForm)"
        #       picture=form.picture_url.data
        menus = Menu(menu_name=form.menu_name.data, address=form.address.data, phone=form.phone.data,
                     price=form.price.data, picture=form.picture_url.data, res_id=form.res_id.data)  # picture=form.picture_url.data
        db.session.add(menus)
        db.session.commit()
        flash('Menu and contact details added successfully')
        return redirect(url_for('display_restaurant', restaurant_id=res_id))
        # return redirect(url_for('display_menus'))
    return render_template('create_menu.html', form=form, res_id=res_id)
예제 #44
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
 def remove_menu_item(self, menu_id):
     try:
         Menu.get(id=menu_id).delete_instance()
         flash(u'Пункт меню видалений успішно')
     except Menu.DoesNotExist, e:
         print "Error while deleting menu item, %s" % e
예제 #45
0
	def get_menus(self):
		menus = memcache.get('menus')
		if menus is None:
			menus = Menu.query().order(Menu.order).fetch()
			memcache.set(key="menus", value=menus)
		return menus
예제 #46
0
파일: views.py 프로젝트: GeneKong/todo
# -*- coding: utf-8 -*- 
from django.http import HttpResponse
from django.shortcuts import render
import time,json, copy
from models import Task, Menu, Link

class Obj(object): pass

#进行初始化
common = Obj()
common.header = Obj()
common.header.notifications = []    #获取一些通知信息,可能需要实时获取
common.sidebar = Obj()
common.sidebar.menus = Menu.getRootMenus()
common.content = Obj()
print "Initial Test......................................."

def home(req):
    home = copy.copy(common)
    home.pageInfo = Obj()
    home.pageInfo.title = '主页'
    home.pageInfo.rsp_type = 'index'
    home.content.tasks = list(Task.objects.all())
    home.content.links = list(Link.objects.all())
    return render(req, 'base.html', home.__dict__)
예제 #47
0
 def load_menu(self):
     menu_data = self.__read_csv("menu")[0]
     self.menu = Menu()
     self.menu.keys = menu_data
예제 #48
0
파일: views.py 프로젝트: skhaz/positagrill
 def render(self, month, year):
     menu = Menu.gql('WHERE month = {} AND year = {}'.format(month, year))
     if not menu:
         return '[]'
     else:
         return json.dumps([m.to_dict() for m in menu])
예제 #49
0
def volumes(week):
    SQL_quer_numb = 'SELECT number from FORECAST WHERE week==' + str(
        '\''
    ) + week + str(
        '\''
    )  #at first I write sql queries on the forecast database to get the number and the slot of the mealkits for the given week
    SQL_quer_slot = 'SELECT slot from FORECAST WHERE week==' + str(
        '\''
    ) + week + str(
        '\''
    )  #the str('\'') was the only way i found to put '' in a string, without messing everything up
    slots = []
    volume = []
    SlotVol = []
    Menu_id_amount = []  #=data21
    Ingredient_amount = []
    response = []
    slots_dat = forecast_db.execute_sql(SQL_quer_slot)
    numbers_dat = forecast_db.execute_sql(SQL_quer_numb)
    for value, in slots_dat:
        slots += [value]
    for value, in numbers_dat:
        volume += [value]
    for i in range(len(volume)):
        SlotVol += [
            (slots[i], volume[i])
        ]  #this list is composed of tuples of the slot of the menu, and the amount of it that is forecasted
    SlotVol = SlotVol + SlotVol  #there are 20 slots for every week, but there are two versions of every mealkit (I'm not sure I understood that part though), so I had to append this list with itself
    query_idMenu = Menu.select(Menu.id).where(
        Menu.week == week
    )  #this query returns the menus of the boxes that are planned to be prepared the week of the query
    query_recipies = Mealkit.select(Mealkit.recipe).where(
        (Mealkit.menu << query_idMenu) & (Mealkit.slot << slots)
    )  #this query gets the recipes' id of the selected menus, given the corresponding slots
    recipes_id = [
        i for i, in query_recipies.tuples()
    ]  #this line simply gets the data of the query_recipes in a variable
    for i in range(
            len(recipes_id)
    ):  #the idea of the next two lines is to create a list of tuples, in order to multiply the final number of each ingredient by the number of times this recipe needs to be made
        Menu_id_amount += [
            (recipes_id[i], SlotVol[i][1])
        ]  #the id of the recipes, and the number of menus at this id (0 : recipes id, 1 : number of recipes that needs to be made)
    for i in range(
            len(recipes_id)
    ):  #the next step is to get the sku and the quantity needed from the Mealkitingredient table, given the id of the recipe
        qur_sku = MealkitIngredient.select(MealkitIngredient.sku).where(
            MealkitIngredient.mealkit == recipes_id[i]
        )  #the first request queries the sku of the ingredients needed, given that the mealkit id corresponds
        qur_quant = MealkitIngredient.select(
            MealkitIngredient.qty_needed
        ).where(
            MealkitIngredient.mealkit == recipes_id[i]
        )  #the second request queries the quantity of ingredient need for one recipe
        data_sku = [i for i, in qur_sku.tuples()
                    ]  #here I just convert the query into data
        data_quant = [i for i, in qur_quant.tuples()]  #same thing here
        for j in range(
                len(data_sku)
        ):  #since recipes can use different ingredients, I need to do a loop for each recipe, in order to get the number of ingredients needed
            Ingredient_amount += [
                (data_sku[j], data_quant[j] * Menu_id_amount[i][1])
            ]  #0 : id ingredient, 1 : number needed
    for i in range(
            len(Ingredient_amount)
    ):  #now the final part : i just need to get the name of each ingredient
        qur_name = Ingredients.select(Ingredients.name).where(
            Ingredients.id == Ingredient_amount[i][0])  #query to get the name
        data_name = [i for i, in qur_name.tuples()]  #data conversion
        name = {
            'name': data_name[0]
        }  #I then create dictionnary for each key, I'm not sure if it was necessary but it worked
        sku = {'sku': Ingredient_amount[i][0]}
        quantity = {'quantity': Ingredient_amount[i][1]}
        name.update(quantity)  #here I concatenate the tables
        name.update(sku)
        response += [
            name
        ]  #here i simply put the dictionnary in the table, once again, not sure if that was necessary but it worked
    return json.dumps(response)
예제 #50
0
def add_menu(menu_name=None):
    m = Menu(menu_name)
    db_session.add(m)
    db_session.commit()
예제 #51
0
    root.email = '*****@*****.**'
    root.password = '******'
    root.active = True
    root.roles.append(admin_role)
    db.session.add(root)
    db.session.commit()

    page = Page()
    page.title = 'Homepage'
    page.slug = 'home'
    page.content = "<h1>Bismillah</h1>"
    page.is_homepage = True
    db.session.add(page)
    db.session.commit()

    menu = Menu()
    menu.title = 'Homepage'
    menu.order = 1
    menu.page_id = page.id
    db.session.add(menu)
    db.session.commit()

    page = Page()
    page.title = 'About'
    page.slug = 'about'
    page.content = "<h1>Ini About page</h1>"
    page.is_homepage = False
    db.session.add(page)
    db.session.commit()

    menu = Menu()
예제 #52
0
def get_menu(request):
    menu = Menu.get_current_menu()

    try:
        contents = menu.attachment.menufile.read()
    except IOError:
        raise

    read_book = xlrd.open_workbook(file_contents=contents, on_demand=True, formatting_info=True)
    write_book = xlcopy(read_book)

    dp = DateParser()
    menu_date = dp.parse(str(menu.date))
    for sheet_index in range(len(write_book._Workbook__worksheets)):
        write_sheet = write_book.get_sheet(sheet_index)
        sheet_date = dp.parse(write_sheet.name)
        if sheet_date == menu_date:
            break
    else:
        raise Exception('Sheet not found!')

    orders = Order.objects.filter(menu=menu)
    ppixs = XLStructure.objects.filter(product__in=orders.values_list('product'), menu=menu)

    style = xlwt.XFStyle()
    font = xlwt.Font()
    font.bold = True
    font.height = 12*20
    font.name = 'Calibri'
    style.font = font
    borders = xlwt.Borders()
    borders.bottom = xlwt.Borders.THIN
    borders.right = xlwt.Borders.THIN
    borders.top = xlwt.Borders.THIN
    borders.left = xlwt.Borders.THIN
    style.borders = borders
    total_cell_style = xlwt.XFStyle()
    total_cell_style.font = font
    total = 0
    total_row_pos = XLStructure.objects.filter(menu=menu).order_by('-position').first().position + 1

    for ppix in ppixs:
        count = sum(order.count for order in orders.filter(product=ppix.product))
        cost = ppix.product.cost * count
        write_sheet.write(ppix.row_in_xls, 4, count, style=style)
        write_sheet.write(ppix.row_in_xls, 5, cost, style=style)
        total += cost
    write_sheet.write(total_row_pos, 5, total, style=total_cell_style)

    response = HttpResponse(content_type='application/vnd.ms-excel')
    write_book.save(response)

    menu_dt = datetime.strptime(menu_date, '%Y-%m-%dT%H:%M:%S')
    filename = menu_dt.strftime('%d.%m.%Y')

    # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/
    if u'WebKit' in request.META['HTTP_USER_AGENT']:
        # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
        filename_header = 'filename={fn}.xls'.format(fn=filename)
    elif u'MSIE' in request.META['HTTP_USER_AGENT']:
        # IE does not support internationalized filename at all.
        # It can only recognize internationalized URL, so we do the trick via routing rules.
        filename_header = ''
    else:
        # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
        filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(filename)
    response['Content-Disposition'] = 'attachment; ' + filename_header

    return response
예제 #53
0
파일: index.py 프로젝트: lpfan/Wing-M.S.
    @expose('/menu/<int:menu_id>/settings', methods=('GET', 'POST',))
    def menu_settings(self, menu_id=0):
        if request.method == 'GET':
            itemTmpl = ''
            try:
                itemTmpl = Menu.get(id=menu_id).template
            except Menu.DoesNotExist, e:
                print 'Error while loading item template, %s' % e
            return itemTmpl
        elif request.method == 'POST':
            form = request.form
            itemTitle = form.get('itemTitle', None)
            itemTemplate = form.get('itemTemplate', None)
            if itemTitle and itemTemplate:
                menu = Menu.update(title=itemTitle,template=itemTemplate).where(id=menu_id)
                menu.execute()
                flash(u'Зміни внесені успішно')
            else:
                flash(u'Під час збереження сталась помилка')
            return redirect(url_for('.index'))

    @expose('/menu/remove_menu_item/<int:menu_id>', methods=('GET',))
    def remove_menu_item(self, menu_id):
        try:
            Menu.get(id=menu_id).delete_instance()
            flash(u'Пункт меню видалений успішно')
        except Menu.DoesNotExist, e:
            print "Error while deleting menu item, %s" % e
        return redirect(url_for('.index'))