def update(item_id): try: name = request.json['name'] loc = request.json['location'] category = request.json['category'] desc = request.json['description'] new_item = Item(name, loc, category, desc) item = db.session.query(Item).filter(Item.id == item_id).one() new_item.update_item(item) db.session.commit() db.session.close() resp = jsonify({"Action": 'Item Updated Successfully'}) resp.status_code = 200 return resp except KeyError as k: resp = jsonify({"error": k.args[0] + ' Value is missing'}) # Status Code 400 is used when the request made by the client is not understandable by the server resp.status_code = 400 return resp except SQLAlchemyError: resp = jsonify({"error": 'something went wrong'}) resp.status_code = 500 return resp
def load_levels(): for level in LEVELS: new_level = DungeonLevel( level_id=level['id'], level_name=level['name'], level_desc=level['desc'], max_room_size=level['max_room_size'], min_room_size=level['min_room_size'], max_rooms=level['max_rooms'], is_final_level=level['is_final_level'] ) new_level.save() # load any items for the level for item in level['items']: new_item = Item( level_id=level['id'], name=item['name'], description=item['desc'], ascii_char=item['ascii_char'], inventory_list=item['inventory_list'], category=item['category'], stat_mod=item['stat_mod'], operation=item['op'], value=item['value'], fgcolor=json.dumps(item['fgcolor']), bgcolor=json.dumps(item['bgcolor']) ) new_item.save() load_monsters(level)
def initialize_new_menu_item(request): context = RequestContext(request) user = request.user item_name = request.POST.get('item_name') price = request.POST.get('price') cost = request.POST.get('cost') description = request.POST.get('description') prep_category = request.POST.get('prep_category') category = request.POST.get('category') new_item = Item( name=item_name, price=int(price), cost=int(cost), description=description, prep_category=prep_category ) new_item.save() new_category = ItemCategory( item=new_item, category=category) new_category.save() return redirect('set_menu')
def add_item(target): user = User.objects.get(u_id=target.user_id) host = Host.objects.get(user=user) items = Item.objects.filter(i_id=target.id) for i in items: i.delete() if re.search('house', target.type): i_type = Item.House elif re.search('apartment', target.type): i_type = Item.Apartment else: i_type = Item.Flat item = Item( i_id=target.id, owner=host, i_type=i_type, title=target.title, album_first='static/album/{}/{}/0.jpg'.format(target.user_id, target.id), album=albums(target.user_id, target.id), desc='desc test test', address=target.address, longitude=target.longitude, latitude=target.latitude, avaliable=avai_date(), price_per_day=target.price, guest_num=target.guest_num, bedroom_num=target.bedroom_num, bed_num=target.bed_num, bathroom_num=target.bathroom_num) item.save()
def setUp(self): self.title = 'Test title' self.user = User( name='test', user_name='te-st', email='*****@*****.**', age=20) self.user.save() self.category = Category(category_name=1) self.category.save() self.item = Item(title=self.title, user=self.user, category=self.category)
def action_additem(self, user, timestamp, itemid, info): from item.models import Item i = Item.get(itemid) if i: if user not in i.users: i.add_user(user) i.update() else: i = Item.get_or_create(itemid, info) i.modified = ts2datetime(timestamp) if user not in i.users: i.add_user(user) i.update() user.clear_smart_list_cache() return True
def action_edititem(self, user, timestamp, itemid, meta): from item.models import Item i = Item.get(itemid) if not i: logger.debug('ignore edititem for unknown item %s %s', timestamp, itemid) return True if i.timestamp > timestamp: logger.debug('ignore edititem change %s %s %s', timestamp, itemid, meta) return True primary = None if 'primaryid' in meta: primary = meta['primaryid'] key = primary[0] else: keys = [k for k in meta if k in Item.id_keys] if keys: key = keys[0] primary = [key, meta[key]] if primary: if not meta[key] and i.meta.get('primaryid', [''])[0] == key: logger.debug('remove id mapping %s %s', i.id, primary) i.update_primaryid(*primary, scrape=False) i.modified = ts2datetime(timestamp) elif meta[key] and i.meta.get('primaryid') != primary: logger.debug('edit mapping %s %s', i.id, primary) i.update_primaryid(*primary, scrape=False) i.modified = ts2datetime(timestamp) else: i.update_meta(meta) i.modified = ts2datetime(timestamp) i.save() user.clear_smart_list_cache() return True
def get_icon_app(id, type_, size, callback): with db.session(): from item.models import Item item = Item.get(id) if not item: data = '' else: if type_ == 'cover' and not item.meta.get('cover'): type_ = 'preview' if type_ == 'preview' and not item.files.count(): type_ = 'cover' if size: skey = '%s:%s:%s' % (type_, id, size) key = '%s:%s' % (type_, id) data = None if size: data = icons[skey] if data: size = None if not data: data = icons[key] if not data: data = icons.black() size = None if size: data = icons[skey] = resize_image(data, size=size) data = bytes(data) or '' callback(data)
def create(): try: name = request.json['name'] loc = request.json['location'] category = request.json['category'] desc = request.json['description'] item = Item(name, loc, category, desc) db.session.add(item) db.session.commit() db.session.close() resp = jsonify({"Action": 'Item Added Successfully'}) resp.status_code = 201 return resp except KeyError as k: resp = jsonify({"error": k.args[0] + ' Value is missing'}) # Status Code 400 is used when the request made by the client is not understandable by the server resp.status_code = 400 return resp except SQLAlchemyError as e: resp = jsonify({"error": 'Something went wrong'}) resp.status_code = 500 return resp
def play_game(self): """ The main game loop """ while True: # Continue in an infinite game loop. self.game_state = 'playing' if self.player.character_state == 'alive' else None self.console_manager.main_console.clear() # Blank the console. self.render_all() self.monsters = [ m for m in (Character.select().join(DungeonLevel).where( (DungeonLevel.level_id == self.dungeon.level.level_id) & (Character.name != 'player'))) ] self.items = [ item for item in (Item.select().join(DungeonLevel).where(( DungeonLevel.level_id == self.dungeon.level.level_id))) ] if self.player.character_state == 'dead': CONSOLES['status'].drawStr(0, 4, 'You have died!') # TODO: Fix win condition # elif player.character_state == 'done': # STATUS.move(0, 4) # STATUS.printStr('CONGRADULATIONS!\n\nYou have found a Cone of Dunshire!') tdl.flush() # Update the window. self.listen_for_events()
def addMedia(request): ''' takes { id: oshash filename: string, item: string info: {} } returns { item: id, } ''' response = json_response({}) data = json.loads(request.POST['data']) oshash = data.pop('id') if not request.user.get_profile().capability('canAddItems'): response = json_response(status=403, text='permissino denied') elif models.File.objects.filter(oshash=oshash).count() > 0: f = models.File.objects.get(oshash=oshash) if f.available: response['status']['text'] = 'file exists' response['data']['item'] = f.item.itemId response['data']['itemUrl'] = request.build_absolute_uri('/%s' % f.item.itemId) else: if 'item' in data: i = Item.objects.get(itemId=data['item']) else: title = ox.parse_movie_path(os.path.splitext( data['filename'])[0])['title'] i = Item() i.data = { 'title': title, 'director': data.get('director', []), } i.user = request.user i.save() i.make_poster(True) f = models.File(oshash=oshash, item=i) f.path = data.get('filename', 'Untitled') extension = f.path.split('.') if len(extension) > 1: extension = extension[-1] else: #wafaa #extension = 'webm' extension = 'png' f.selected = True if 'info' in data and data['info']: f.info = data['info'] f.info['extension'] = extension f.parse_info() f.save() response['data']['item'] = i.itemId response['data']['itemUrl'] = request.build_absolute_uri('/%s' % i.itemId) return render_to_json_response(response)
def AddItem(): form=ProductForm() name=request.form.get('name') description=request.form.get('description') new_item=Item(name=name,description=description) db.session.add(new_item) db.session.commit() return redirect('/')
def get_context_data(self, **kwargs): item_obj = Item.objects(id=self.kwargs.get("id")).first() if not item_obj: raise Http404("该CI对象不存在") context = super(ItemDetailView, self).get_context_data(**kwargs) context["item"] = item_obj context = add_sidebar_context(context) return context
def add_item(request): add_item = True msg = None if request.method == 'POST': image_path = request.FILES.get('img', None) item_obj = Item(name=request.POST['name'], description=request.POST['desc'], price=request.POST['price'], item_image=image_path) item_obj.save() msg = f'Item - "{item_obj.name}" Added Successfully...' add_item = False items = Item.objects.filter(active='Y') return render(request, 'item/welcome.html', { 'items': items, 'add': add_item, 'msg': msg })
def get_context_data(self, **kwargs): category = ItemCategory.objects(id=self.kwargs.get("id")).first() if not category: raise Http404("该CI模型不存在") context = super(ItemWithCategoryIDListView, self).get_context_data(**kwargs) context["object_list"] = Item.objects(category=self.kwargs.get("id")) context["category"] = category context = add_sidebar_context(context) return context
def destroy(self, request, *args, **kwargs): instance = self.get_object() # 当该CI对象模型未产生任何CI对象时,可以将其删除 item_obj_set = Item.objects(category=instance) if item_obj_set: return Response({"error": "can't delete this category because it has items reserved."}, status=status.HTTP_400_BAD_REQUEST) self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT)
class TestModel(TestCase): def setUp(self): self.title = 'Test title' self.user = User( name='test', user_name='te-st', email='*****@*****.**', age=20) self.user.save() self.category = Category(category_name=1) self.category.save() self.item = Item(title=self.title, user=self.user, category=self.category) def test_item_model(self): old_item = Item.objects.count() self.item.save() new_item = Item.objects.count() self.assertNotEqual(old_item, new_item)
def index(request): limit=5 item_list = Item.objects() paginator=Paginator(item_list,limit) page=request.GET.get('page',1) print page loaded=paginator.page(page) context ={ 'items':loaded } return render(request,'index.html',context)
def action_removeitem(self, user, timestamp, itemid): from item.models import Item i = Item.get(itemid) if i: if user in i.users: i.users.remove(user) if i.users: i.update() else: i.delete() user.clear_list_cache() user.clear_smart_list_cache() return True
def remove_items(self, items): from item.models import Item for item_id in items: i = Item.get(item_id) if i in self.items: self.items.remove(i) i.update() state.db.session.add(self) state.db.session.commit() if self.user_id == settings.USER_ID and self.name != '': Changelog.record(self.user, 'removelistitems', self.name, items) self.user.clear_smart_list_cache() self.user.clear_list_cache()
def addMedia(request): ''' takes { id: oshash filename: string, item: string info: {} } returns { item: id, } ''' response = json_response({}) data = json.loads(request.POST['data']) oshash = data.pop('id') if not request.user.get_profile().capability('canAddItems'): response = json_response(status=403, text='permissino denied') elif models.File.objects.filter(oshash=oshash).count() > 0: f = models.File.objects.get(oshash=oshash) if f.available: response['status']['text'] = 'file exists' response['data']['item'] = f.item.itemId response['data']['itemUrl'] = request.build_absolute_uri('/%s' % f.item.itemId) else: if 'item' in data: i = Item.objects.get(itemId=data['item']) else: title = ox.parse_movie_path(os.path.splitext(data['filename'])[0])['title'] i = Item() i.data = { 'title': title, 'director': data.get('director', []), } i.user = request.user i.save() i.make_poster(True) f = models.File(oshash=oshash, item=i) f.path = data.get('filename', 'Untitled') extension = f.path.split('.') if len(extension) > 1: extension = extension[-1] else: extension = 'webm' f.selected = True if 'info' in data and data['info']: f.info = data['info'] f.info['extension'] = extension f.parse_info() f.save() response['data']['item'] = i.itemId response['data']['itemUrl'] = request.build_absolute_uri('/%s' % i.itemId) return render_to_json_response(response)
def insert_products(): with open(CSV_PATH_PRODUCTS) as in_file: data_reader = csv.reader(in_file) next(data_reader, None) for row in data_reader: fourth_category = row[2] title = row[3] description = row[4] price = int(row[5].replace(",", "")) labels = row[6].replace("[", "").replace("]", "").replace("'", "").split(", ") benefits = row[7].replace("[", "").replace("]", "").replace("'", "").split(", ") main_image = row[8] default_image = row[9] hover_image = row[10] if fourth_category not in FourthCategory.objects.values_list('name', flat=True): FourthCategory.objects.create(name=fourth_category) images = ItemImage.objects.create( main_url = main_image, front_url = default_image, hover_url = hover_image ) cur_item = Item( main_category = MainCategory.objects.get(name="Shop"), sub_category = SubCategory.objects.get(name="Tea Shop"), third_category = ThirdCategory.objects.get(name=row[1]), fourth_category = FourthCategory.objects.get(name=fourth_category), title = title, description = description, price = price, images = images ) cur_item.save() cur_item.set_benefits(benefits) cur_item.save() if labels[0] != "": for each_label in labels: print(each_label) ItemLabel.objects.create( label = Label.objects.get(name=each_label), item = cur_item )
def add_items(self, items): from item.models import Item for item_id in items: i = Item.get(item_id) if i: self.items.append(i) if self.user_id == settings.USER_ID: i.queue_download() i.update() state.db.session.add(self) state.db.session.commit() if self.user_id == settings.USER_ID and self.name != '': Changelog.record(self.user, 'addlistitems', self.name, items) self.user.clear_smart_list_cache() self.user.clear_list_cache()
def add_item(request): if request.method == 'GET': last_item_info = Item.objects.last() unit_list = Unit.objects.all() return render(request, 'item/add_item.html', locals()) else: item_index = request.POST.get('item_index') item_chinese_name = request.POST.get('item_chinese_name') item_english_name = request.POST.get('item_english_name') item_method = request.POST.get('item_method') item_unit = request.POST.get('item_unit') is_calc = request.POST.get('is_calc') is_use = request.POST.get('is_use') unit_info = Unit.objects.get(id=item_unit) new_item = Item(item_index=int(item_index), item_chinese_name=item_chinese_name, item_english_name=item_english_name, item_method=item_method, item_unit=unit_info, is_calc=str_to_bool(is_calc), is_use=str_to_bool(is_use)) new_item.save() return redirect('/item/item/')
def add(request, order_id, meal_id): order = get_object_or_404(Order, pk=order_id) meal = get_object_or_404(Meal, pk=meal_id) user = get_object_or_404(User, pk=request.user.id) item = Item() if not request.user.groups.filter(id=order.group.id): messages.warning(request, 'To zamówienie nie należy do Twojej grupy') return redirect('profile:index') else: item.order = order item.meal = meal item.user = user item.save() messages.success(request, 'Dodano do listy') return HttpResponseRedirect(reverse('order:details', args=[order.id]))
def addListItems(data): ''' takes { list items } ''' if data['list'] == ':': from item.models import Item for item_id in data['items']: i = Item.get(item_id) i.queue_download() i.update() elif data['list']: l = models.List.get_or_create(data['list']) if l: l.add_items(data['items']) return l.json() return {}
def addListItems(data): """ takes { list items } """ if data["list"] == ":": from item.models import Item for item_id in data["items"]: i = Item.get(item_id) i.queue_download() i.update() elif data["list"]: l = models.List.get_or_create(data["list"]) if l: l.add_items(data["items"]) return l.json() return {}
def setup(): form = SetupForm() error = "" if form.validate_on_submit(): author = Author(form.fullname.data, form.email.data, form.username.data, form.password.data, True) db.session.add(author) db.session.flush() if author.id: item = Item(form.title.data, author.id) db.session.add(item) db.session.flush() else: db.session.rollback() error = "Error creating user" if author.id and item.id: db.session.commit() flash('Item created') return redirect(url_for('admin')) else: db.session.rollback() error = "Error creating item" return render_template('item/setup.html', form=form)
def setup(self): self.movie = Movie.objects.create(item=Item(), runtime=-100, critic_score=94) self.id = Movie.objects.get(runtime=self.movie.runtime).pk
def create_item(self, name, itemType): obj = Item(name=name, itemType=itemType) obj.save()
def get_items(): return Item.get_all_list()
def validate_item_field(attr_value, attr_form): """ :param attr_value: item的属性 :param attr_form: item category的属性规则 :return: """ if not isinstance(attr_form, dict): return -1, {"error": "attr_form is not a dict."} required = attr_form.get('required') if required == 'false': return 0, {"msg": "success"} field = attr_form.get('field') if not field: return -1, {"error": "field missed."} if field == "string": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a string."} if len(attr_value) < int( attr_form["min_length"]) or len(attr_value) > int( attr_form["max_length"]): return -1, {"error": "invalid string length."} if attr_form.get('valid_rule') == "none": return 0, {"msg": "success"} elif attr_form.get('valid_rule') == "IPaddress": pattern = re.compile(r'\d+\.\d+\.\d+\.\d+') # 匹配IP地址有待改进 elif attr_form.get('valid_rule') == "email": pattern = re.compile(r'^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$') elif attr_form.get('valid_rule') == "phone": pattern = re.compile(r'^\d{11}$') else: return -1, {"error": "invalid valid_rule."} match = pattern.match(attr_value) if not match: return -1, { "error": "did not match rule: %s" % attr_form.get('valid_rule') } elif field == "text": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a string."} if len(attr_value) < int( attr_form["min_length"]) or len(attr_value) > int( attr_form["max_length"]): return -1, {"error": "invalid string length."} elif field == "select": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a dict."} if attr_value not in attr_form["choice"][1:-1].split("|"): return -1, {"error": "invalid choice."} elif field == "multiple_select": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a dict."} for each in attr_value.split("|"): if each not in attr_form["choice"][1:-1].split("|"): return -1, {"error": "invalid choice."} elif field == "integer": if not isinstance(attr_value, int): return -1, {"error": "attr_value is not a integer."} if attr_value < int(attr_form["min_value"]) or attr_value > int( attr_form["max_value"]): return -1, {"error": "invalid integer value."} elif field == "datetime": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a string."} try: date_object = datetime.datetime.strptime(attr_value, '%Y%m%d%H%M%S') except ValueError: return -1, { "error": "time data '%s' does not match format" % attr_value } elif field == "reference": if not isinstance(attr_value, str): return -1, {"error": "attr_value is not a string."} item_obj = Item.objects(id=attr_value) if not item_obj: return -1, {"error": "unknown item."} if item_obj.category.id != attr_form["reference"]: return -1, {"error": "wrong category."} return 0, {"msg": "success"}
def upload(request): print(request.body) data = request.body.decode() try: data = json.loads(data) except Exception: raise Http404("Not a valid JSON") server = get_object_or_404(Server, id = data["serverId"]) player, created = Player.objects.get_or_create( pid = int(data["playerId"]), server = server, defaults = { "name": data["playerName"] } ) # if renamed player.name = data["playerName"] player.klass = data["class"] player.race = data["race"] player.gender = data["gender"] # check this if player.race == Race.POPORI and player.gender == Gender.FEMALE: player.race = Race.ELIN player.save() # TODO gearsets gear = Gear() gear.save() player.gearsets.add(gear) for item in data["items"]: try: slot = Slot(item["slot"]) except ValueError: continue item = Item.create_from_json(item, server) gear[slot] = item gear.save() for ach in data["achievements"]: id = int(ach["id"]) completed = datetime.fromtimestamp(int(ach["completed"])) Achievement.objects.get_or_create( player = player, data = get_object_or_404(AchievementData, id = id), defaults = { "completed": completed } ) return HttpResponse("OK")
def get_item(pk): return Item.get(int(pk))
from django.test import TestCase from item.models import Item # Create your tests here. for item in Item.objects()[2]: print(item)
def update_item_cache(): Item.create_cache() Store.create_cache() ItemCompose.create_cache() CouragePointStore.create_cache() TowerStore.create_cache()
def create_item(request): try: username = request.META.get("HTTP_USERNAME") user = User.objects.get(username=username) host = Host.objects.get(user=user) data = request.data valid_address = 0 if 'address' in data: geo_response = geocoding(data['address']) if geo_response['status'] == 'OK': latitude = geo_response['results'][0]['geometry']['location'][ 'lat'] longitude = geo_response['results'][0]['geometry']['location'][ 'lng'] valid_address = 1 item = Item( owner=host, title=data['title'], desc=data['desc'], i_type=data['i_type'], price_per_day=data['price_per_day'], guest_num=data['guest_num'], bedroom_num=data['bedroom_num'], bed_num=data['bed_num'], bathroom_num=data['bathroom_num'], address=data['address'], rules=data['rules'], features=data['features'], avaliable=data['avaliable'], album='') if valid_address: item.latitude = latitude item.longitude = longitude item.save() if 'album' in data: files = set(data['album'].split(',')) if item.album == '': origin_files = set() else: origin_files = set(item.album.split(',')) files_to_add = files - origin_files files_to_delete = origin_files - files for file in files_to_add: new_album = save_image(file, user.u_id, item.i_id) if item.album == '': item.album += new_album else: item.album += ',' + new_album for file in files_to_delete: item.album = delete_image(file, item.album, user.u_id, item.i_id) clear_tmp() item.album_first = item.album.split(',')[0] item.save() result = { 'code': status.HTTP_200_OK, 'msg': 'creation successful', 'data': { 'item_id': item.i_id } } except User.DoesNotExist: result = { 'code': status.HTTP_400_BAD_REQUEST, 'msg': 'user not found', } except Host.DoesNotExist: result = { 'code': status.HTTP_400_BAD_REQUEST, 'msg': 'invalid host', } except Exception as e: result = { 'code': status.HTTP_400_BAD_REQUEST, 'msg': str(e), } return Response(result, status=result['code'])