Exemple #1
0
    def save(self, *args, **kwargs):
        "Form processor"

        profile = None

        if self.invitation:
            # Create DjangoUser
            django_user = django_auth.User(
                username=self.cleaned_data['username'], password='')
            django_user.set_password(self.cleaned_data['password'])
            django_user.save()

            # Crate profile
            try:
                profile = django_user.profile
            except:
                profile = User()
                profile.user = django_user

            profile.name = django_user.username
            profile.default_group = self.invitation.default_group
            profile.save()

            # Create contact
            try:
                contact_type = ContactType.objects.get(
                    Q(name='Person') | Q(slug='person'))
            except:
                contact_type = ContactType.objects.all()[0]

            try:
                # Check if contact has already been created (e.g. by a signals
                contact = profile.get_contact()
                if not contact:
                    contact = Contact()
            except:
                contact = Contact()

            contact.name = self.cleaned_data['name']
            contact.contact_type = contact_type
            contact.related_user = profile
            contact.save()

            # Set email
            try:
                emailfield = contact_type.fields.filter(field_type='email')[0]
                email = ContactValue(
                    value=self.invitation.email, field=emailfield, contact=contact)
                email.save()
            except:
                pass

            # Add quick start widget
            widget = Widget(user=profile,
                            perspective=profile.get_perspective(),
                            module_name='anaf.core',
                            widget_name='widget_welcome')
            widget.save()

        return profile
Exemple #2
0
def workspace_test():
	print_data('workspaces objects', br=False)

	for index in range(3):
		w = Workspace()
		w.name = 'New workspace name'
		w.description = 'Some new description'
		w.save()

	workspaces = Workspace.all()
	print_data('new objects -> model.all()', workspaces)

	w.name = 'Updated name'
	w.save()

	workspaces = Workspace.all()
	print_data('UPDATED -> model.all()', workspaces)

	workspaces = Workspace.get(id=w.id, name=w.name)
	print_data('GET -> model.get()', [workspaces])

	workspaces = Workspace.filter(name='New workspace name')
	print_data('FILTER -> model.filter()', workspaces)

	for index in range(2):
		o = Application()
		o.workspace_id = w.guid
		o.save()

	a = View()
	a.application_id = o.guid
	a.save()

	a = Resource()
	a.application_id = o.guid
	a.save()

	for index in range(3):
		o = Widget()
		o.workspace_id = w.guid
		o.save()

	for index in range(3):
		o = DataSource()
		o.workspace_id = w.guid
		o.save()

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('All objects in db', objects)

#	[w.delete() for w in Workspace.all()]
	workspaces = Workspace.all()
	print_data('cleaned', workspaces)

	workspaces = Workspace.filter(include_deleted=True)
	print_data('cleaned with deleted if exists', workspaces)

	objects = Workspace.all() + Resource.all() + Application.all() + Widget.all() + DataSource.all() + View.all()
	print_data('no objects left', objects)
Exemple #3
0
 def get(self, **kwargs): 
     admin = False 
     user =  self.current_user  
     page_id = kwargs.get('pageid')
     options_dict = {}
     try:
         pages = Page.get(user.pages)
         for p in pages:
             if p.id == page_id:
                 admin = True
                 page = p
                 widgets = Widget.all().filter('page =', page).filter('deleted = ', False).order('order')
                 options = Option.all().filter('type_reference =', page)
                 for option in options:
                     options_dict[option.name] = {'id': str(option.key().id()), 'value': option.value}
                 
     except:
         page = None
         widgets = None
         options_dict = None
     if admin:
         #page = Page.get_by_key_name(str(page_id))
         #add_app_url = 'https://www.facebook.com/add.php?api_key=a284fdd504b5191923362afabc0ea6c7&pages=1&page=141947329155355'
         upload_url = blobstore.create_upload_url('/upload')
         page_id = encrypt(page_id).encode('hex')
         self.render("app/edit.html", admin=True, page=page,upload_url=upload_url, page_id=page_id,widgets= widgets, options=options_dict) 
     else:
         self.redirect('/dashboard')
Exemple #4
0
 def get(self, **kwargs):
     page_id = self.request.get('page_id')
     try:
         page = Page.get_by_key_name(page_id)
         widgets = Widget.all().filter('page =', page).filter('deleted = ', False).order('order')
     except:
         page=None
         widgets=None
     self.render("app/fb-tab.html", page=page,widgets=widgets, method="get")
Exemple #5
0
def create_photo_widget(wid, img_url):

    w1 = Widget(type_id=3, name="Mason!", size=3)
    i1 = [
        WidgetItem(widget_id=wid,
                   color_class=random.choice(COLOR_CLASSES),
                   img_url=img_url)
    ]

    return [w1, i1]
Exemple #6
0
def create_twitter_widget():

    w1 = Widget(type_id=2, name="@webdevMason", size=5)
    i1 = [
        WidgetItem(
            widget_id=2,
            text=
            "<a class='twitter-timeline' href='https://twitter.com/webdevMason?ref_src=twsrc%5Etfw'>Tweets by webdevMason</a> <script async src='https://platform.twitter.com/widgets.js' charset='utf-8'></script>"
        )
    ]

    return [w1, i1]
Exemple #7
0
    def get_context_data(self,*args,**kwargs):
        context = super(BaseMixin,self).get_context_data(**kwargs)

        try:
            context['categories'] = Category.available_list()
            context['widgets'] = Widget.available_list()
            context['recently_posts'] = Post.get_recently_posts(RECENTLY_NUM)
            context['hot_posts'] = Post.get_hots_posts(HOT_NUM)
            context['pages'] = Page.objects.filter(status=0)
            if cache.get('online.ips')!= None:
                context['online_num'] = len(cache.get('online_ips'))
        except Exception as e:
            logger.exception(u'加载基本信息出错[%s]',e)

        return context
Exemple #8
0
 def test_proxy_model_included(self):
     """
     Regression for #11428 - Proxy models aren't included when you dumpdata
     """
     stdout = StringIO()
     # Create an instance of the concrete class
     Widget(name='grommet').save()
     management.call_command('dumpdata',
                             'fixtures_regress.widget',
                             'fixtures_regress.widgetproxy',
                             format='json',
                             stdout=stdout)
     self.assertEqual(
         stdout.getvalue(),
         """[{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
     )
Exemple #9
0
def get_embedly_code(args):
    id = args["id"]
    url = args["url"]
    type = args["type"]
    try:
        if url:
            response = oembed_replace(url)
            if response:  
                widget = Widget.get_by_key_name(id)
                if type == "embedly":
                    widget.embedly_code = db.Text(response)
                if type == "googlemaps":
                    widget.googlemaps_code = db.Text(response)
                widget.put()
    except:
        logging.info("Embedly Error")
        logging.info(args)
Exemple #10
0
    def get_context_data(self, *args, **kwargs):
        if 'object' in kwargs or 'query' in kwargs:
            context = super(BaseMixin, self).get_context_data(**kwargs)
        else:
            context = {}

        try:
            context['categories'] = Category.available_list()
            context['widgets'] = Widget.available_list()
            context['recently_posts'] = Post.get_recently_posts(RECENTLY_NUM)
            context['hot_posts'] = Post.get_hots_posts(HOT_NUM)
            context['tag_lists'] = Post.gather_tags()
            context['like_most_posts'] = Post.get_most_like_posts(LIKE_MOST_NUM)
            context['pages'] = Page.objects.filter(status=0)
        except Exception as e:
            logger.exception(u'加载基本信息出错[%s]!', e)

        return context
Exemple #11
0
    def get_context_data(self, *args, **kwargs):
        if 'object' in kwargs or 'query' in kwargs:
            context = super(BaseMixin, self).get_context_data(**kwargs)
        else:
            context = {}

        try:
            context['categories'] = Category.available_list()
            context['widgets'] = Widget.available_list()
            context['recently_posts'] = Post.get_recently_posts(RECENTLY_NUM)
            context['hot_posts'] = Post.get_hots_posts(HOT_NUM)
            context['tag_lists'] = Post.gather_tags()
            context['like_most_posts'] = Post.get_most_like_posts(
                LIKE_MOST_NUM)
            context['pages'] = Page.objects.filter(status=0)
        except Exception as e:
            logger.exception(u'加载基本信息出错[%s]!', e)

        return context
Exemple #12
0
    def post(self, **kwargs):
        #logging.info(self.request)
        signed_request = facebook.parse_signed_request(self.request.get('signed_request'),self.get_config('facebook','app_secret'))
        #logging.info(signed_request)
        try:
          user_id = signed_request['user_id']
        except:
          user_id = None
        page_id = signed_request['page']['id']
        liked = signed_request['page']['liked']
        admin = signed_request['page']['admin']
        options_dict = {}
        status = 'True'
        try:
          page = Page.get_by_key_name(page_id)
          #check active account or for expired account.
          if page.upgraded != '1':

            expire_date = page.created + datetime.timedelta(days=14)
            min_expire_date = datetime.datetime(2011,5,1)
        
            if (expire_date < min_expire_date):
              expire_date = min_expire_date

            if expire_date < datetime.datetime.now():
              status = 'False'

          
          
          widgets = Widget.all().filter('page =', page).filter('deleted = ', False).order('order')
          options = Option.all().filter('type_reference =', page)
          for option in options:
              options_dict[option.name] = {'id': str(option.key().id()), 'value': option.value}
        except:
          page=None
          widgets=None
          options_dict = None
        self.render("app/fb-tab.html", page=page,widgets=widgets, method="post",options=options_dict,admin=admin,status=status)



        
Exemple #13
0
 def add_context_data(self, **kwargs):
     # 这里重载了ListView的get_context_data方法
     context = super(BaseMixin, self).get_context_data(**kwargs)
     try:
         context['categories'] = Category.available_list()
         context['widgets'] = Widget.available_list()
         context['recently_posts'] = Post.get_recently_posts(
             settings.RECENTLY_NUM)
         context['hot_posts'] = Post.get_hots_posts(settings.HOT_NUM)
         context['pages'] = Page.objects.filter(status=0)
         if not context.has_key('title'):
             context['title'] = ''
         context['title'] += 'Younfor'
         context['desc'] = 'python,c,c++,java,linux,生活感悟,工作笔记,心情驿站'
         context['keywords'] = 'python,c,c++,java,linux,生活感悟,工作笔记,心情驿站'
         context['author'] = 'younfor'
         context['sitename'] = 'Younfor\'s BLOG'
         context['blogdesc'] = '悄悄是别离的笙箫,所谓爱情,所谓人生,所谓。'
     except Exception as e:
         print e
     return context
Exemple #14
0
 def add_context_data(self, **kwargs):
     # 这里重载了ListView的get_context_data方法
     context = super(BaseMixin, self).get_context_data(**kwargs)
     try:
         context['categories'] = Category.available_list()
         context['widgets'] = Widget.available_list()
         context['recently_posts'] = Post.get_recently_posts(
             settings.RECENTLY_NUM)
         context['hot_posts'] = Post.get_hots_posts(settings.HOT_NUM)
         context['pages'] = Page.objects.filter(status=0)
         if not context.has_key('title'):
             context['title'] = ''
         context['title'] += 'Younfor'
         context['desc'] = 'python,c,c++,java,linux,生活感悟,工作笔记,心情驿站'
         context['keywords'] = 'python,c,c++,java,linux,生活感悟,工作笔记,心情驿站'
         context['author'] = 'younfor'
         context['sitename'] = 'Younfor\'s BLOG'
         context['blogdesc'] = '悄悄是别离的笙箫,所谓爱情,所谓人生,所谓。'
     except Exception as e:
         print e
     return context
Exemple #15
0
 def get(self, **kwargs):
     user =  self.current_user
     admin = False
     method = kwargs.get('method')
     if method == 'scripturl':
         upload_url = blobstore.create_upload_url('/upload')
         
         self.response.out.write(upload_url)
     if method == 'headerimageurl':
         #pages = Page.get(user.pages)
         key_name = self.request.get("p")
         #for p in pages:
         #    if p.id == page_id:
         #        page = p
         #        admin = True
         #if admin:
         page = Page.get_by_key_name(key_name)
         if page:
             header_image_url = page.header_image_url
             
             self.response.out.write(header_image_url)
         else:
             
             self.response.out.write('')
     if method == 'getwidget':
         widget_id = self.request.get("wid")
         widget = Widget.get_by_key_name(widget_id)
         tenr = range(1,11)
         if widget:
             widget_type = widget.type
         if not widget:
             widget_type = self.request.get("wtype").lstrip('wi-')
             widget = dict(type=widget_type,
                         id=widget_id
                         )
         if widget_type:
             self.render('app/widgets/'+widget_type+".html", widget=widget,tenr=tenr)
         else:
             
             self.response.out.write("This widget cannot be found.")
Exemple #16
0
def widget_test():
	print_data('widgets objects', br=False)
	workspaces = []
	for index in range(3):
		w = Workspace()
		w.name = 'New workspace name'
		w.description = 'Some new description'
		w.save()
		workspaces.append(w)

	for index in range(3):
		w = Widget()
		w.source = '<source>some stuff</source>'
		w.workspace_id = workspaces[0].guid if index in [0, 1] else workspaces[1].guid
		w.save()

	widgets = Widget.all()
	print_data('new objects -> model.all()', widgets)

	w.source = '<b>UDPATED</b>'
	w.save()
	w.reload()

	print_data('UPDATED', [w.source])

	widgets = Widget.get(id=w.id)
	print_data('GET -> model.get()', [widgets])

	widgets = Widget.filter(source='<source>some stuff</source>')
	print_data('FILTER -> model.filter()', widgets)

	for index, w in enumerate(workspaces):
		widgets = w.widgets
		print_data('workspace %s -> workspace.widgets' % str(index), widgets)

	[w.delete() for w in Widget.all()]
	objects = Widget.all() + Workspace.all()
	print_data('cleaned', objects)

	widgets = Widget.filter(include_deleted=True)
	print_data('cleaned with deleted if exists', widgets)
from models import Workspace, Widget

widget_id = request.arguments.get('widget_id', '')
command = request.arguments.get('command', 'update')

widget = Widget.get(guid=widget_id)

if widget:
    disabled = '2' if command == 'delete' else '0'

    form = self.dialog_update.form_update
    form.title.value = widget.name
    form.title.mode = disabled

    form.workspace_id.value = widget.workspace_id
    form.widget_id.value = widget.guid
    form.command.value = command
    self.dialog_update.form_update.btn_update.label = command.title()
    form.btn_update.action("setLabel", [command.title()])
    form.btn_update.action(
        "setClass",
        ['btn btn-danger' if command == 'delete' else 'btn btn-success'])
    self.dialog_update.title = 'Widget {}'.format(command.title())
    self.dialog_update.show = '1'
	raise Exception('Workspace ID is not provided')

workspace_id = request.arguments.get('workspace_id')
command = request.arguments.get('command', u'')

workspace = Workspace.get(guid=workspace_id)

if not workspace:
	self.action('goTo', ['/main'])

elif command in ['delete', 'update']:

	if 'widget_id' not in request.arguments:
		raise Exception(u'Widget ID is not provided')
	widget_id = request.arguments['widget_id']
	widget = Widget.get(guid=widget_id, workspace_id=workspace.guid)

	if widget:
		if command == 'delete':
			widget.delete()
		else:
			title = request.arguments['title']
			if title:
				widget.name = title
				widget.save()

	self.dialog_update.action('hide', ['0'])

elif command == 'create':
	title = request.arguments['title']
	if title:
Exemple #19
0
 def post(self, **kwargs):
     user =  self.current_user
     admin = False
     method = kwargs.get('method')
     if method == 'deletewidget':
         key_name = self.request.get("wid")
         widget = Widget.get_by_key_name(key_name)
         if widget:
             widget.deleted = True
             widget.last_modified_by = user
         try:
             db.put(widget)
             self.response.out.write('True')
         except:
             self.response.out.write('False')
             
     if method == 'savepageorder':
         page_order = self.request.get('pageorder')
         page_order = page_order.split(',')
         batch = []
         for k,v in enumerate(page_order):
             widget = Widget.get_by_key_name(v)
             if widget:
                 widget.order = k
                 widget.last_modified_by = user
                 batch.append(widget)
         try:
             db.put(batch)
             self.response.out.write('True')
         except:
             self.response.out.write('False')
             
     if method == 'savewidget':
         page = Page.get_by_key_name(self.request.get('pageid'))
         key_name = self.request.get('wid')
         widget = Widget.get_by_key_name(key_name)
         if self.request.get('wtype') == 'embedly':
            fields = simplejson.loads(self.request.get('wcontents'))
            #get_embedly_code({'id':self.request.get('wid'),"url":fields['embedly_url'],"type":"embedly"})
            deferred.defer(get_embedly_code,{'id':self.request.get('wid'),"url":fields['embedly_url'],"type":"embedly"})
         if self.request.get('wtype') == 'googlemaps':
            fields = simplejson.loads(self.request.get('wcontents'))
            deferred.defer(get_embedly_code,{'id':self.request.get('wid'),"url":fields['googlemaps_link'],"type":"googlemaps"})
         if not widget:
             widget = Widget(key_name=key_name,
                             id = key_name,
                             type = self.request.get('wtype'),
                             name = self.request.get('wname'),
                             page = page,
                             contents = self.request.get('wcontents'),
                             last_modified_by = user
                            )
             fields = simplejson.loads(self.request.get('wcontents'))
             for k,v in fields.iteritems():
                 db_type = k.split('__')
                 try:
                     db_type = db_type[1]
                 except IndexError:
                     db_type = None
                 logging.info(db_type)
                 if db_type == 'text':
                     setattr(widget, k, db.Text(v))
                 else:
                     setattr(widget, k, v)
         else:
             widget.name = self.request.get('wname')
             widget.contents = self.request.get('wcontents')
             widget.last_modified_by = user
             fields = simplejson.loads(self.request.get('wcontents'))
             for k,v in fields.iteritems():
                 db_type = k.split('__')
                 try:
                     db_type = db_type[1]
                 except IndexError:
                     db_type = None
                 logging.info(db_type)
                 if db_type == 'text':
                     setattr(widget, k, db.Text(v))
                 else:
                     setattr(widget, k, v)
         
         try:
             db.put(widget)
             self.response.out.write('True')
         except:
             self.response.out.write('False')
     if method == 'saveoption':
         try:
             option = Option.get_by_id(int(self.request.get('id')))
         except:
             option = None
         if self.request.get('otype') == 'page':
             link = Page.get_by_key_name(self.request.get('opageid'))
         if not option:
             option = Option(
                             name = self.request.get('oname'),
                             value = self.request.get('ovalue'),
                             type = self.request.get('otype'),
                             type_reference = link
                            )
         else:
             option.value = self.request.get('ovalue')
             
         try:
             db.put(option)
             self.response.out.write('True')
         except:
             self.response.out.write('False')
     if method == 'upgradedowngrade':
       try:
         username = self.get_config('saasy','username')
         password = self.get_config('saasy','password')
         product = self.get_config('saasy','product')
         qty = str(self.request.get('qty'))
         basic_auth = base64.b64encode('%s:%s' % (username, password)) 
         xml_data = "<subscription><productPath>/%s</productPath><quantity>%s</quantity><no-end-date/></subscription>" % (product,qty)
         subscriber_info=simplejson.loads(self.current_user.subscriber_info)
         url = "https://api.fastspring.com/company/seedprod/subscription/%s" % subscriber_info['reference']
         response = urlfetch.fetch(url=url,payload=xml_data,headers={'Authorization': 'Basic %s' % basic_auth ,'Content-Type': 'application/xml' },method=urlfetch.PUT)
         if response.status_code == 200:
           # Update Pages
           upgraded_pages = self.request.get('pages').split(',')
           pages = Page.get(user.pages)
           batch = []
           for p in pages:
             if p.id in upgraded_pages:
               p.upgraded = '1'
               p.upgraded_by = user
             else:
               if p.upgraded_by:
                 if p.upgraded_by.id == user.id:
                   p.upgraded = '0'
                   p.upgraded_by = None
             batch.append(p)
           db.put(batch)
                        
           self.response.out.write('True')
         else:
           self.response.out.write('False')
       except:
         self.response.out.write('False')
Exemple #20
0
def create_widget_1():

    i1 = "Finish writing <b>my book</b>"
    i2 = "Make a pile of edible golden eggs, <a href='https://yhoo.it/2C6FpSm'>like these</a>"
    i3 = "Make a <b>wearable project</b> from/inspired by this book: <a href='http://amzn.to/2EsSDL2'><i>Make: Wearable Electronics</i></a>"
    i4 = "Volunteer @ Burning Man"
    i5 = "Fully document an <b>IVF cycle</b>"
    i6 = "Contribute to an open source project"
    i7 = "<b>Sky dive</b>, or something similarly terrifying"
    i8 = "<b>Teach Bert</b> to do an r/dogtraining trick of the month, e.g. <a href='http://bit.ly/2lB6GWg'>mirror me</a>"
    i9 = "Design an educational simulation"
    i10 = "Write a long-form essay"
    i11 = "Run a 5k"
    i12 = "Read <b>50 books</b> in a year"
    i13 = "Do a chin-up"
    i14 = "Write a song"
    i15 = "Grow & harvest a vegetable"
    i16 = "Throw a <b>big party</p>"
    i17 = "Complete a <b>doula training</b> course, e.g. <a href='http://bit.ly/2zXyrxc'>this one</a>"
    i18 = "Do a <b>10+ mile</b> hike"
    i19 = "Lead a training/seminar at work"
    i20 = "Make kombucha from scratch"
    i21 = "<b>Meditate</b> every day for a month"
    i22 = "<b>Repair</b> something currently too damaged to use"
    i23 = "Play D&D"
    i24 = "Attend a conference solo"
    i25 = "Design an <b>escape room</b>"
    i26 = "Attend <b>Sleep No More</b> or similar <a href='http://bit.ly/2wMtklZ'>(See: Sleep No More)</a>"
    i27 = "Host a dinner to connect interesting friends who've never met one another"
    i28 = "Write an interesting Twitter bot"
    i29 = "Finish a painting"
    i30 = "Create a <b>new recipe</b>"

    w1 = Widget(type_id=1, name="<30 Bucket List", size=4)

    i1 = WidgetItem(widget_id=1,
                    text=i1,
                    score=10,
                    color_class=select_cc(10),
                    progress=3)
    i2 = WidgetItem(widget_id=1, text=i2, score=4, color_class=select_cc(4))
    i3 = WidgetItem(widget_id=1, text=i3, score=8, color_class=select_cc(8))
    i4 = WidgetItem(widget_id=1, text=i4, score=7, color_class=select_cc(7))
    i5 = WidgetItem(widget_id=1, text=i5, score=8, color_class=select_cc(8))
    i6 = WidgetItem(widget_id=1, text=i6, score=3, color_class=select_cc(3))
    i7 = WidgetItem(widget_id=1, text=i7, score=5, color_class=select_cc(5))
    i8 = WidgetItem(widget_id=1, text=i8, score=6, color_class=select_cc(6))
    i9 = WidgetItem(widget_id=1, text=i9, score=5, color_class=select_cc(5))
    i10 = WidgetItem(widget_id=1, text=i10, score=4, color_class=select_cc(4))
    i11 = WidgetItem(widget_id=1, text=i11, score=4, color_class=select_cc(4))
    i12 = WidgetItem(widget_id=1,
                     text=i12,
                     score=10,
                     color_class=select_cc(10))
    i13 = WidgetItem(widget_id=1, text=i13, score=6, color_class=select_cc(6))
    i14 = WidgetItem(widget_id=1, text=i14, score=2, color_class=select_cc(2))
    i15 = WidgetItem(widget_id=1, text=i15, score=2, color_class=select_cc(2))
    i16 = WidgetItem(widget_id=1, text=i16, score=5, color_class=select_cc(5))
    i17 = WidgetItem(widget_id=1, text=i17, score=9, color_class=select_cc(9))
    i18 = WidgetItem(widget_id=1, text=i18, score=5, color_class=select_cc(5))
    i19 = WidgetItem(widget_id=1, text=i19, score=4, color_class=select_cc(4))
    i20 = WidgetItem(widget_id=1, text=i20, score=3, color_class=select_cc(3))
    i21 = WidgetItem(widget_id=1, text=i21, score=5, color_class=select_cc(5))
    i22 = WidgetItem(widget_id=1, text=i22, score=3, color_class=select_cc(3))
    i23 = WidgetItem(widget_id=1, text=i23, score=2, color_class=select_cc(2))
    i24 = WidgetItem(widget_id=1, text=i24, score=3, color_class=select_cc(3))
    i25 = WidgetItem(widget_id=1, text=i25, score=6, color_class=select_cc(6))
    i26 = WidgetItem(widget_id=1, text=i26, score=1, color_class=select_cc(1))
    i27 = WidgetItem(widget_id=1,
                     text=i27,
                     score=5,
                     color_class=select_cc(5),
                     progress=10)
    i28 = WidgetItem(widget_id=1,
                     text=i28,
                     score=4,
                     color_class=select_cc(4),
                     progress=100)
    i29 = WidgetItem(widget_id=1, text=i29, score=3, color_class=select_cc(3))
    i30 = WidgetItem(widget_id=1, text=i30, score=3, color_class=select_cc(3))

    i = [
        i1, i2, i3, i6, i15, i8, i4, i9, i7, i10, i11, i12, i13, i14, i16, i17,
        i18, i19, i20, i21, i22, i23, i24, i25, i26, i27, i28, i29, i5, i30
    ]

    return [w1, i]
def main(data):

    action = data.get("action", "read")
    input_data = data.get("data", {})
    result = {}

    if action == "create":
        widget = Widget()
        widget.fill_from_json(input_data)
        widget.save(b64source=input_data.get("b64source", None))
        result[widget.guid] = widget.to_json()

    elif action == "read":
        for wid_guid in input_data:
            widget = Widget.get(guid=wid_guid)
            result[wid_guid] = widget.to_json(
                include=["b64source"]) if widget else None

    elif action == "update":
        for widget_guid in input_data:
            widget = Widget.get(guid=widget_guid)
            wid_json = input_data[widget_guid]
            if widget:
                widget.fill_from_json(wid_json)
                widget.save(b64source=input_data.get("b64source", None))
                result[widget_guid] = widget.to_json(include=["b64source"])

    elif action == "delete":
        for widget_guid in input_data:
            widget = Widget.get(guid=widget_guid)
            if widget:
                widget.delete()
                result[widget_guid] = "deleted"
            else:
                result[widget_guid] = "not_found"

    write_response(result)