def add_new_storage(product_id): s1 = Storage() s1.quantity = input('Unesite quantity: ') s1.product_id = product_id db.add(s1) db.commit() db.close()
def perform_command(command): """ Performs the command by name. Stores the result in `Storage()`. :param command: command name, selected by user. """ command = command.lower() routes = get_routes() command_class = routes[command] command_inst = command_class() try: storage = Storage() if len(storage.items) == 0: try: with open('data.pkl', 'rb') as fromfile: storage.items = pickle.load(fromfile) fromfile.close() except: print('no file') command_inst.perform(storage.items) except KeyError: print('Bad command, try again.') except UserExitException as ex: print(ex) raise
def action(self, option): if option == "y": Storage.add(self._tempWorker) if option == "y" or option == "n": self._tempWorker = None return ListView(Storage.all()) return None
def manage_storage(request, storageid=None, storagename=None): if storageid and storagename: storage = get_object_or_404(filter_by_access(request.user, Storage, manage=True), id=storageid) else: storage = Storage(system='local') if not storage.id: system_choices = [(s, s) for s in settings.STORAGE_SYSTEMS.keys()] else: system_choices = [(storage.system, storage.system)] class StorageForm(forms.ModelForm): system = forms.CharField(widget=forms.Select(choices=system_choices)) def clean_system(self): if not self.instance.id: return self.cleaned_data['system'] else: return self.instance.system class Meta: model = Storage fields = ('title', 'system', 'base', 'credential_id', 'credential_key', 'urlbase', 'deliverybase') if request.method == "POST": if request.POST.get('delete-storage'): if not request.user.is_superuser: raise HttpResponseForbidden() messages.add_message(request, messages.INFO, message="Storage '%s' has been deleted." % storage.title) storage.delete() return HttpResponseRedirect(reverse('storage-manage')) else: form = StorageForm(request.POST, instance=storage) if form.is_valid(): form.save() return HttpResponseRedirect( reverse('storage-manage-storage', kwargs=dict(storageid=form.instance.id, storagename=form.instance.name))) else: form = StorageForm(instance=storage) return render_to_response('storage_edit.html', { 'storage': storage, 'form': form, }, context_instance=RequestContext(request))
def test_attribute_assignment(self): # File objects can be assigned to FileField attributes, but # shouldn't get committed until the model it's attached to is # saved. obj = Storage() obj.normal = SimpleUploadedFile('assignment.txt', 'content') dirs, files = temp_storage.listdir('tests') self.assertEqual(len(dirs), 0) self.assertEqual(files, ['default.txt']) obj.save() dirs, files = temp_storage.listdir('tests') files.sort() self.assertEqual(files, ['assignment.txt', 'default.txt'])
def action(self, option): if option == "b": return ListView(Storage.all()) if option == "e": return EditView(self._model) if option == "d": self._deleting = True if self._deleting and option == "y": Storage.delete(self._model.id) return ListView(Storage.all()) if self._deleting and option == "n": self._deleting = False return None
def home(): storage = Storage() all_items = storage.items if request.method == 'POST': form = ContactForm(request.form) if form.validate(): model = BlogPostModel(form.data) all_items.append(model) storage.dump_to_json_file() form = ContactForm() else: form = ContactForm() return render_template('home.html', form=form, items=all_items)
def action(self, option): if option == "c": return DetailsView(self._model) if option == "e": self._name = None self._age = None self._edited = False if option == "s": if self._name: self._model.name = self._name if self._age: self._model.age = self._age Storage.save() return DetailsView(self._model) return None
def perform_command(command): """ Performs the command by name. Stores the result in `Storage()`. :param command: command name, selected by user. """ command = command.lower() routes = get_routes() value = None for route in routes: if route[:len(command)] == command: value = route break try: command_class = routes[value] command_inst = command_class() storage = Storage() command_inst.perform(storage.items) except KeyError: print('Bad command, try again.') except UserExitException as ex: print(ex) raise
def manage_storage(request, storageid=None, storagename=None): new_storage = False if storageid and storagename: storage = get_object_or_404(filter_by_access(request.user, Storage, manage=True), id=storageid) else: storage = Storage(system='local') new_storage = True if not storage.id: system_choices = [(s,s) for s in settings.STORAGE_SYSTEMS.keys()] else: system_choices = [(storage.system, storage.system)] class StorageForm(forms.ModelForm): system = forms.CharField(widget=forms.Select(choices=system_choices)) def clean_system(self): return self.cleaned_data['system'] if not self.instance.id else self.instance.system class Meta: model = Storage exclude = ('name', 'derivative') if request.method == "POST": if request.POST.get('delete-storage'): if not request.user.is_superuser: raise HttpResponseForbidden() request.user.message_set.create(message="Storage '%s' has been deleted." % storage.title) storage.delete() return HttpResponseRedirect(reverse('storage-manage')) else: form = StorageForm(request.POST, instance=storage) if form.is_valid(): form.save() messages.success(request, "Storage created!") return HttpResponseRedirect(reverse('storage-manage-storage', kwargs=dict( storageid=form.instance.id, storagename=form.instance.name))) else: form = StorageForm(instance=storage) return render_to_response('storage_edit.html', {'storage': storage, 'form': form, 'new': new_storage}, context_instance=RequestContext(request))
def home(): storage = Storage() if request.method == 'POST': form = BlogPostForm(request.form) if form.validate(): model = BlogPostModel(form.data) storage.appending(model.model_to_dict()) else: logger.error('Someone have submitted an incorrect form!') else: form = BlogPostForm() return render_template( 'home.html', form=form, items=storage.posts, )
def test_file_duplicate_name(self): # Save another file with the same name. obj = make_obj() obj2 = Storage() obj2.normal.save('django_test.txt', ContentFile('more content')) self.assertEqual(repr(obj2.normal), "<FieldFile: tests/django_test_1.txt>") self.assertEqual(obj2.normal.size, 12)
def test_basic_saved_file(self): # Saving a file enables full functionality. obj = Storage() obj.normal.save('django_test.txt', ContentFile('content')) self.assertEqual(repr(obj.normal), '<FieldFile: tests/django_test.txt>') self.assertEqual(obj.normal.size, 7) self.assertEqual(obj.normal.read(), 'content')
def action(self, option): if option == "q": return BaseView() if option == "1": return ListView(Storage.all()) return None
def home(): storage = Storage() all_items = storage.items if request.method == 'POST': form = ContactForm(request.form) if form.validate(): model = BlogPostModel(form.data) all_items.append(model) storage.dump_to_json_file() form = ContactForm() else: form = ContactForm() return render_template( 'home.html', form=form, items=all_items)
def test_duplicate_file_name_differentiation(self): # Multiple files with the same name get _N appended to them. objs = [Storage() for i in range(3)] for o in objs: o.normal.save('multiple_files.txt', ContentFile('Same Content')) self.assertEqual( repr([o.normal for o in objs]), "[<FieldFile: tests/multiple_files.txt>, <FieldFile: tests/multiple_files_1.txt>, <FieldFile: tests/multiple_files_2.txt>]" )
def test_default_values(self): # Default values allow an object to access a single file. obj = Storage.objects.create() self.assertEqual(repr(obj.default), "<FieldFile: tests/default.txt>") self.assertEqual(obj.default.read(), 'default content') # But it shouldn't be deleted, even if there are no more # objects using it. obj.delete() obj = Storage() self.assertEqual(obj.default.read(), 'default content')
def home(): storage = Storage() all_items = storage.items if request.method == 'POST': form = BlogPostForm(request.form) if form.validate(): model = BlogPostModel(form.data, len(all_items) + 1) all_items.append(model) storage.save() else: logger.error('Someone have submitted an incorrect form!') else: form = BlogPostForm() return render_template( 'home.html', form=form, items=all_items, )
def main(): storage = Storage() FieldCommand() PlayerCommand() while True: try: for player_id, val in enumerate(storage.players): move(player_id) except KeyboardInterrupt: break
def main(): """ Main method, works infinitelly until user runs `exit` command. Or hits `Ctrl+C` in the console. """ storage = Storage() try: with open('storage.dat', 'rb') as stor: storage.items = pickle.load(stor) except IOError: pass while True: try: command = parse_user_input() perform_command(command) except UserExitException: break except KeyboardInterrupt: print('Shutting down, bye!') break
def action(self, option): try: id = int(option) model = Storage.get(id) if not model: return None return DetailsView(model) except ValueError: if option == "b": return MainView() if option == "a": return AddView() return None
def perform_command(command): command = command.lower() routes = get_routes() try: command_class = routes[command] command_inst = command_class(command) storage = Storage() command_inst.perform(storage.items) except KeyError: print('Bad command, try again.') except UserExitException as ex: print(ex) raise
def execute(task, campaign): storage_query = Storage.all().filter('campaign =', campaign) if (storage_query.count(limit = 1)): for datum in storage_query.fetch(100): logging.info('checking for stats: %s' % datum.stats.key()) if (Histogram.has(datum.stats) and not TaskModel.has(datum.stats)): #perhaps use a pickled dictionary instead of count queries if (not TaskModel(object = datum.stats, task = 'delete histogram').put()): logging.critical('Could not create delete histogram task for %s' % datum.stats) else: datum.stat.delete() datum.delete() else: task.delete() logging.info('Nothing left in storage to clean up for campaign %s' % campaign) return True
def save_file(file, con, storage_data, input_name, upload_folder): img_obj = dict() origin_name = secure_filename(file.filename) ext = get_extension(origin_name) filename = f'{input_name}.{ext}' file_path = os.path.join(upload_folder, filename) file.save(file_path) size = os.path.getsize(file_path) system_name = hashlib.md5( origin_name.encode('utf-8') + file.content_type.encode('utf-8') + str(size).encode('utf-8')).hexdigest() has_file = [x for x in storage_data if x.system_name == system_name] if not has_file: img_obj.update({ 'name': filename, 'system_name': system_name, 'size': size, 'uploaded': datetime.datetime.now() }) with open(file_path, 'rb') as image_file: image = Image(image_file) if image.has_exif: if getattr(image, 'datetime_original', ''): created = getattr(image, 'datetime_original', '') if created: created = datetime.datetime.strptime( created, '%Y:%m:%d %H:%M:%S') img_obj.update({ 'maker': getattr(image, 'make', ''), 'model': getattr(image, 'model', ''), 'created': created, }) img = Storage(**img_obj) to_database(con, img, action='add') con.session.commit() else: # выдача ошибки о дубликате и удаление из хранилища flash('Вы пытаетесь сохранить дубликат файла', category='error')
def perform_command(command): """ Выполняет команду по имени. Сохраняет результат в `Storage ()`. : param command: имя команды, выбранное пользователем. """ command = command.lower() routes = get_routes() try: command_class = routes[command] command_inst = command_class() storage = Storage() command_inst.perform(storage.items) except KeyError: print('Bad command, try again.') except UserExitException as ex: print(ex) raise
def perform_command(command): """ Performs the command by name. Stores the result in `Storage()`. :param command: command name, selected by user. """ command = command.lower() routes = get_routes() try: command_class = routes[command] command_inst = command_class() storage = Storage() ##### command_inst.perform(storage.items) ##### except KeyError: print('Bad command, try again.') except UserExitException as ex: print(ex) raise
def show(self): print(self.header) storage = Storage() input_func = get_option_input() def get_input(): selected_option = input_func('Enter option: ') if selected_option not in self.next_menus: raise UserInputOptionException return selected_option while True: print('Starting test...') self.test(storage) print(self.options) selected_option = self.input_secure_wrap(get_input) if selected_option == '2': break
def storage_crud(): if request.method == 'POST': new_warehouse_id = request.form['warehouse_id'] new_container_id = request.form['container_number'] new_product_code = request.form['product_code'] new_quantity = float(request.form['quantity']) try: product_id = get_id_by_product_code(new_product_code) new_storage = Storage(container_id=new_container_id, product_id=product_id, quantity=new_quantity).create() return redirect('/storage_crud') except: return redirect('/storage_crud') # return 'There was an issue adding information about storage of product. \n\nPerhaps such a product is already stored in this container or there is no product with this code.' else: warehouses = get_all_warehouses() res = get_product_storage_inf() return render_template('storage.html', storages=res, warehouses=warehouses)
def add(request): #request.encoding = 'gb2312' index=request.POST['index'] air=request.POST.getlist('num_air[]') soilt=request.POST.getlist('num_soilt[]') soilm=request.POST.getlist('num_soilm[]') light=request.POST.getlist('num_light[]') coz=request.POST.getlist('num_coz[]') addr_air=request.POST.getlist('Addr_air[]') addr_soilt=request.POST.getlist('Addr_soilt[]') addr_soilm=request.POST.getlist('Addr_soilm[]') addr_light=request.POST.getlist('Addr_light[]') addr_coz=request.POST.getlist('Addr_coz[]') removeEmptyItem(air) removeEmptyItem(soilt) removeEmptyItem(soilm) removeEmptyItem(light) removeEmptyItem(coz) removeEmptyItem(addr_air) removeEmptyItem(addr_soilt) removeEmptyItem(addr_soilm) removeEmptyItem(addr_light) removeEmptyItem(addr_coz) try: Storage.objects.get(index=index) request.session['warn1'] = '该库房已存在' return redirect("/storagemanage/") except ObjectDoesNotExist: s=Storage() u=request.session.get('user', '') u1=User.objects.get(username=u) s.owner=u1 s.num_air = len(air) s.num_soilt = len(soilt) s.num_soilm = len(soilm) s.num_sunlight = len(light) s.num_coz = len(coz) s.nodeNum = s.num_air + s.num_coz + s.num_soilt + s.num_soilm + s.num_sunlight s.index = index s.save() addSensor(s.num_air, air, addr_air, 'air', s) addSensor(s.num_soilm, soilm, addr_soilm, 'soilm', s) addSensor(s.num_soilt, soilt, addr_soilt, 'soilt', s) addSensor(s.num_sunlight, light, addr_light, 'sun', s) addSensor(s.num_coz, coz, addr_coz, 'coz', s) return redirect('storagemanage')
def get_values(cls, campaign, ns, path = '', keys_only = False): query = Storage.all(keys_only = keys_only).filter('campaign = ', campaign).filter('namespace = ', ns).order('-created_on') return [datum for datum in query] # todo, paginator/generator
def test_files(self): # Attempting to access a FileField from the class raises a descriptive # error self.assertRaises(AttributeError, lambda: Storage.normal) # An object without a file has limited functionality. obj1 = Storage() self.assertEqual(obj1.normal.name, "") self.assertRaises(ValueError, lambda: obj1.normal.size) # Saving a file enables full functionality. obj1.normal.save("django_test.txt", ContentFile("content")) self.assertEqual(obj1.normal.name, "tests/django_test.txt") self.assertEqual(obj1.normal.size, 7) self.assertEqual(obj1.normal.read(), "content") obj1.normal.close() # File objects can be assigned to FileField attributes, but shouldn't # get committed until the model it's attached to is saved. obj1.normal = SimpleUploadedFile("assignment.txt", "content") dirs, files = temp_storage.listdir("tests") self.assertEqual(dirs, []) self.assertEqual(sorted(files), ["default.txt", "django_test.txt"]) obj1.save() dirs, files = temp_storage.listdir("tests") self.assertEqual( sorted(files), ["assignment.txt", "default.txt", "django_test.txt"] ) # Files can be read in a little at a time, if necessary. obj1.normal.open() self.assertEqual(obj1.normal.read(3), "con") self.assertEqual(obj1.normal.read(), "tent") self.assertEqual(list(obj1.normal.chunks(chunk_size=2)), ["co", "nt", "en", "t"]) obj1.normal.close() # Save another file with the same name. obj2 = Storage() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertEqual(obj2.normal.name, "tests/django_test_1.txt") self.assertEqual(obj2.normal.size, 12) # Push the objects into the cache to make sure they pickle properly cache.set("obj1", obj1) cache.set("obj2", obj2) self.assertEqual(cache.get("obj2").normal.name, "tests/django_test_1.txt") # Deleting an object does not delete the file it uses. obj2.delete() obj2.normal.save("django_test.txt", ContentFile("more content")) self.assertEqual(obj2.normal.name, "tests/django_test_2.txt") # Multiple files with the same name get _N appended to them. objs = [Storage() for i in range(3)] for o in objs: o.normal.save("multiple_files.txt", ContentFile("Same Content")) self.assertEqual( [o.normal.name for o in objs], ["tests/multiple_files.txt", "tests/multiple_files_1.txt", "tests/multiple_files_2.txt"] ) for o in objs: o.delete() # Default values allow an object to access a single file. obj3 = Storage.objects.create() self.assertEqual(obj3.default.name, "tests/default.txt") self.assertEqual(obj3.default.read(), "default content") obj3.default.close() # But it shouldn't be deleted, even if there are no more objects using # it. obj3.delete() obj3 = Storage() self.assertEqual(obj3.default.read(), "default content") obj3.default.close() # Verify the fix for #5655, making sure the directory is only # determined once. obj4 = Storage() obj4.random.save("random_file", ContentFile("random content")) self.assertTrue(obj4.random.name.endswith("/random_file")) # Clean up the temporary files and dir. obj1.normal.delete() obj2.normal.delete() obj3.default.delete() obj4.random.delete()
# -*- coding: utf-8 -*- import config # from flask.ext.qrcode import QRcode from flask import Flask, request, render_template from models import Storage, BlogPostModel from forms import ContactForm app = Flask(__name__, template_folder='templates') app.config.from_object(config) Storage.load_from_json_file() @app.route('/', methods=['GET', 'POST']) def home(): storage = Storage() all_items = storage.items if request.method == 'POST': form = ContactForm(request.form) if form.validate(): model = BlogPostModel(form.data) all_items.append(model) storage.dump_to_json_file() form = ContactForm() else: form = ContactForm() return render_template( 'home.html',
return render_template('home.html', form=form, items=items_to_validate, ) @app.route('/shutdown', methods=['GET']) def shutdown(): shutdown_server() storage=Storage() with open(persons_file, 'w') as _file: result_json = PostEncoder().encode(storage.items) _file.write(result_json) return 'Server shutting down...' if __name__ == '__main__': storage = Storage() persons_file = os.path.join('files', 'objects.json') with open(persons_file) as _file: models = json.load(_file, cls=PostDecoder) storage.items = models app.run()
from app.models import Order from flask import abort from flask_restful import Resource, marshal_with from models import Storage storage = Storage() storage.create_order() class OrderService(Resource): @marshal_with(Order.rest_fields) def get(self, id): order = storage.find(id) if order is None: abort(404) return order def put(self, id): pass def delete(self, id): pass class OrderListService(Resource): @marshal_with(Order.rest_fields) def post(self): order = storage.create_order() return order, 201, {'Location': '/rest/orders/' + str(order.id)} @marshal_with(Order.rest_fields)
from datetime import datetime from helpers import get_oder_class from models import Storage import json storage = Storage() orderbook = storage.orderbook def create_order(request): data_in = request.json keys = sorted(list(data_in.keys())) if keys != ['price', 'size', 'type']: output = { "error": "Missing keys", } return 400, json.dumps(output) _class = get_oder_class(data_in['type']) order = _class(data_in['price'], data_in['size']) orderbook.add_order(order) output = {"order_id": order.id} return 200, json.dumps(output) def get_order(request, id): for o in storage.orderbook.get_all_orders(): if o.id == id: order = o break
def main(): storage = Storage() storage.fill_storage() main_menu = MainMenu() main_menu.show()
from flask import abort from flask_restful import Resource, marshal_with from models import Storage, Order storage = Storage() storage.create_order() class OrderService(Resource): @marshal_with(Order.rest_fields) def get(self, id): order = storage.find(id) if order is None: abort(404) return order def put(self, id): pass def delete(self, id): pass class OrderListService(Resource): @marshal_with(Order.rest_fields) def post(self): order = storage.create_order() return order, 201, {'Location': '/rest/orders/' + str(order.id)}
# -*- coding: utf-8 -*- import config # from flask.ext.qrcode import QRcode from flask import Flask, request, render_template from models import Storage, BlogPostModel from forms import ContactForm app = Flask(__name__, template_folder='templates') app.config.from_object(config) Storage.load_from_json_file() @app.route('/', methods=['GET', 'POST']) def home(): storage = Storage() all_items = storage.items if request.method == 'POST': form = ContactForm(request.form) if form.validate(): model = BlogPostModel(form.data) all_items.append(model) storage.dump_to_json_file() form = ContactForm() else: form = ContactForm() return render_template('home.html', form=form, items=all_items)