예제 #1
0
 def form_valid(self, form):
     name = form.cleaned_data['name']
     theme_color = form.cleaned_data['theme_color']
     background_image = form.cleaned_data['background_image']
     theme = Theme(name=name,
                   theme_color=theme_color,
                   background_image=background_image)
     theme.save()
예제 #2
0
def import_theme(zipfp, theme=None):
    """
    If a theme is informed, it assumes and theme imported fields are ignored
    """
    # Initializes the working area
    dir_name = ''.join([random.choice('abcdefghijklmnopqrstuvwxyz') for n in range(20)])
    work_dir = os.path.join('/tmp/', dir_name)
    os.makedirs(work_dir)
    os.chdir(work_dir)

    # Opens and extracts the zip file
    zipf = zipfile.ZipFile(zipfp)
    zipf.extractall()

    # Loads driver JSON file
    json_fp = file('details.json')
    json = simplejson.loads(json_fp.read())
    json_fp.close()

    # Doesn't allow import existing theme (must delete before)
    if not theme and Theme.query().filter(name=json['name']).count():
        raise ValueError(_('Theme "%s" already exists.')%json['name'])

    # Creates the new theme
    if not theme:
        theme = Theme.query().create(name=json['name'], verbose_name=json['verbose_name'])

    # Creates the new templates
    for json_tpl in json['templates']:
        tpl, new = theme['templates'].get_or_create(name=json_tpl['name'])
        tpl['content'] = json_tpl['content']
        tpl['notes'] = json_tpl['notes']
        tpl['engine'] = json_tpl['engine']
        tpl.save()

    # Creates the new static files
    db_field = ThemeStaticFile._meta.fields['file']
    for json_sf in json['static_files']:
        sf, new = theme['static_files'].get_or_create(
                name=json_sf['name'],
                defaults={
                    'url': json_sf['url'],
                    'mime_type': json_sf['mime_type'],
                    },
                )

        if json_sf['file']:
            fp = file(json_sf['file'])
            content = ContentFile(fp.read())
            fp.close()

            upload_name = db_field.generate_filename(sf, json_sf['file'])
            upload_name = db_field.storage.save(upload_name, content)
            sf['file'] = FieldFile(sf, db_field, upload_name)
            sf.save()

    return theme
예제 #3
0
파일: courses.py 프로젝트: Valikovanast/new
def create_theme(course_id):
    theme = Theme(name=request.form.get('name'))
    parent_id = request.form.get('parent_id')
    if parent_id:
        theme.parent_id = parent_id
    else:
        theme.course_id = course_id
    db.session.add(theme)
    db.session.commit()
    return redirect(url_for('courses.show', course_id=course_id))
예제 #4
0
def edit_theme(request, theme_id=None):
    """ allows requester to edit their theme

        args:
        theme_id: The theme to fill the form with 

    """
    if not theme_id:
        try:
            theme = request.user.theme
        except Theme.DoesNotExist:
            theme = Theme(user=request.user)
    else:
        theme = get_object_or_404(Theme, pk=theme_id)

    if request.method == 'POST':
        if request.POST['submit'] == 'Save':
            form = ThemeForm(request.POST, instance=theme)
            if form.is_valid():
                form.save()
        else:
            # preview feature
            form = ThemeForm(request.POST, instance=theme)
            theme = form.save(commit=False)
    else:
        form = ThemeForm(instance=theme)

    return render_to_response(
        "themes/edit_theme.html", {
            'form': form,
            'theme': theme,
            'extra_themes': Theme.objects.exclude(name="").all(),
        },
        context_instance=RequestContext(request))
예제 #5
0
 def render_page(self, errors=None, success=None):
     ''' Small wrap for self.render to cut down on lenghty params '''
     current_theme = Theme.by_cssfile(self.session["theme"])
     self.render("user/settings.html",
                 errors=errors,
                 success=success,
                 current_theme=current_theme)
예제 #6
0
    def process_request(self, request):
        if app_settings.CHOOSING_FUNCTION:
            try:
                path, func_name = app_settings.CHOOSING_FUNCTION.rsplit('.', 1)
            except ValueError:
                raise ImproperlyConfigured("Setting THEMES_CHOOSING_FUNCTION has '%s' with a unknown function path."%app_settings.CHOOSING_FUNCTION)

            try:
                mod = import_anything(path)
            except ImportError:
                raise ImproperlyConfigured("Module '%s' wasn't found."%path)

            try:
                func = getattr(mod, func_name)
            except AttributeError:
                raise ImproperlyConfigured("Module '%s' hasn't a function called."%func_name)

            request.theme = func(request)

        if not getattr(request, 'theme', None):
            if getattr(request, 'site', None) and request.site['theme']:
                request.theme = request.site['theme']
            else:
                try:
                    request.theme = Theme.query().get(is_default=True)
                except Theme.DoesNotExist:
                    request.theme = None
예제 #7
0
 def render_page(self, errors=None, success=None):
     ''' Small wrap for self.render to cut down on lenghty params '''
     current_theme = Theme.by_cssfile(self.session["theme"])
     self.render("user/settings.html",
         errors=errors,
         success=success,
         current_theme=current_theme
     )
예제 #8
0
    def get(self):
        template_values = get_generic_template_values(self)
        themeQuery = Theme.query()
        themeResults = themeQuery.fetch()

        template_values['themeResults'] = themeResults
        template = JINJA_ENVIRONMENT.get_template('/views/createMeetup.html')
        self.response.write(template.render(template_values))
예제 #9
0
 def get(self):
     themes = Theme.query(
                 Theme.used == False).order(-Theme.vote_value,
                                            Theme.created).fetch()
     context = {'themes': themes,
                'session_id': str(self.session.get('id', '0')),
                'item_count': len(themes)}
     self.response.out.write(template.render(self.path('add_themes.html'),
                                             self.add_context(context)))
예제 #10
0
파일: views.py 프로젝트: zenny/genesis-repo
def upload_theme(request):
	if request.method == 'POST':
		form = ThemeForm(request.POST)

		if not form.is_valid():
			return render(request, 'upload.html', {'form': form, 'function': 'theme', 'message': 'Form not valid', 'type': 'alert-danger'})

		get_reqno()
		newfile = Theme(name=request.POST['name'], THEME_ID=request.POST['THEME_ID'], 
			theme_css=request.POST['theme_css'], DESCRIPTION=request.POST['DESCRIPTION'], 
			AUTHOR=request.POST['AUTHOR'], VERSION=request.POST['VERSION'], 
			HOMEPAGE=request.POST['HOMEPAGE'])
		newfile.save()

		# Display success message
		return render(request, 'upload.html', {'form': form, 'function': 'theme', 'message': 'Upload successful!', 'type': 'alert-success'})
	else:
		form = ThemeForm()
	return render(request, 'upload.html', {'form': form, 'function': 'theme'})
예제 #11
0
def list_themes():
    if(request.args.get("submit",None)):
        arg={}
        arg["RECAPTCHA_PUBLIC_KEY"]=RECAPTCHA_PUBLIC_KEY
        arg["RECAPTCHA_KEY"]=RECAPTCHA_KEY
        return render_template('submittheme.html',**arg)
    elif(request.args.get("name",None)):
        themename=request.args.get("name")
        themedata=Theme.get_by_key_name(themename)
        if(themedata==None):
            return 'Theme not found',404
        thedict=dict()
        thedict["name"]=themedata.name
        thedict["submitter"]=themedata.submitter
        thedict["email"]=themedata.email
        thedict["data"]=JSON.loads(themedata.data)
        return JSON.dumps(thedict)
    else:
        themelist=Theme.all()
        return render_template( 'themegallery.html' , themes=themelist)
예제 #12
0
def list_themes():
    if (request.args.get("submit", None)):
        arg = {}
        arg["RECAPTCHA_PUBLIC_KEY"] = RECAPTCHA_PUBLIC_KEY
        arg["RECAPTCHA_KEY"] = RECAPTCHA_KEY
        return render_template('submittheme.html', **arg)
    elif (request.args.get("name", None)):
        themename = request.args.get("name")
        themedata = Theme.get_by_key_name(themename)
        if (themedata == None):
            return 'Theme not found', 404
        thedict = dict()
        thedict["name"] = themedata.name
        thedict["submitter"] = themedata.submitter
        thedict["email"] = themedata.email
        thedict["data"] = JSON.loads(themedata.data)
        return JSON.dumps(thedict)
    else:
        themelist = Theme.all()
        return render_template('themegallery.html', themes=themelist)
예제 #13
0
def screenshot():
    themename = request.args.get("themename", None)
    if (not themename):
        return 'No theme selected', 404
    themedata = Theme.get_by_key_name(themename)
    if (not themedata):
        return "The theme '" + themename + "' does not exist.", 404
    if (themedata.rendered):
        return themedata.rendered
    else:
        return "<h1>Sorry Thumbnail is not avalable</h1>"
예제 #14
0
def screenshot():
    themename=request.args.get("themename",None)
    if(not themename):
        return 'No theme selected',404
    themedata=Theme.get_by_key_name(themename)
    if(not themedata):
        return "The theme '"+themename+"' does not exist.",404
    if(themedata.rendered):
        return themedata.rendered
    else:
        return "<h1>Sorry Thumbnail is not avalable</h1>"
def put_theme(plateid):  #向主题界面发布问答主题
    if request.method == 'GET':
        return render_template('question.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        plate_id = plateid
        # plate_id=request.form.get('plate_id')
        theme = Theme(title=title, content=content)
        theme.author = g.user
        plate = Plate.query.filter(Plate.id == plate_id).first()
        theme.plate = plate
        m = 0
        for x in Theme.query.all():  # 迭代器,
            if x.plate_id == theme.plate_id:
                m = m + 1
        plate.post_num = m
        db.session.add(theme)
        db.session.commit()
        return redirect(url_for('theme', plate_id=plate.id))
예제 #16
0
def process_theme(lst):
    if lst[0]:
        new_theme = Theme(name=lst[0],
                          player_id=PlayerDict.id_dict[lst[1]],
                          date=datetime.datetime.strptime(
                              lst[2], "%d. %m. %Y"))
        db.session.add(new_theme)
        db.session.flush()
        db.session.refresh(new_theme)
    else:
        new_theme = Theme.query.order_by(desc(Theme.id)).first()
    return new_theme.id
예제 #17
0
    def post(self):
        theme = Theme()
        name = self.request.get('name')
        description = self.request.get('description')
        theme.name = name
        theme.description = description
        email = self.request.get('email')
        url = self.request.get('url')
        token = self.request.get('token')
        imageUrl = url + '&token=' + token
        correctUrl = imageUrl.replace("images/", "images%2F")
        theme.image_url = correctUrl
        theme.created_user_email = email

        theme.put()
        self.response.write('Got post request: ' + name + '  ' + description)
예제 #18
0
    def post(self):
        user = users.get_current_user()
        if user:
            theme = Theme()
            name = self.request.get('themeName')
            description = self.request.get('themeDescription')
            theme.name = name
            theme.description = description

            uploaded_file = self.request.POST.get("themeImage")
            url = writeToGCBucket(uploaded_file)
            theme.image_url = url
            theme.created_user_email = user.email()

            theme.put()
            self.redirect('/viewThemes')
예제 #19
0
 def successful_login(self, user):
     ''' Called when a user successfully logs in '''
     logging.info("Successful login: %s/%s from %s" %
         (user.account, user.handle, self.request.remote_ip,))
     self.start_session()
     theme = Theme.by_id(user.theme_id)
     if user.team is not None:
         self.session['team_id'] = int(user.team.id)
     self.session['user_id'] = int(user.id)
     self.session['handle'] = ''.join(user.handle)  # Copy string
     self.session['theme'] = ''.join(theme.cssfile)
     if user.has_permission('admin'):
         self.session['menu'] = 'admin'
     else:
         self.session['menu'] = 'user'
     self.session.save()
예제 #20
0
 def post_theme(self, *args, **kwargs):
     ''' Change per-user theme '''
     form = Form(theme_uuid="Please select a theme",)
     if form.validate(self.request.arguments):
         theme = Theme.by_uuid(self.get_argument('theme_uuid'))
         if theme is not None:
             self.session['theme'] = ''.join(theme.cssfile)
             self.session.save()
             user = self.get_current_user()
             user.theme_id = theme.id
             dbsession.add(user)
             dbsession.flush()
             self.render_page()
         else:
             self.render_page(errors=["Theme does not exist."])
     else:
         self.render_page(errors=form.errors)
예제 #21
0
 def post_theme(self, *args, **kwargs):
     ''' Change per-user theme '''
     form = Form(theme_uuid="Please select a theme", )
     if form.validate(self.request.arguments):
         theme = Theme.by_uuid(self.get_argument('theme_uuid'))
         if theme is not None:
             self.session['theme'] = ''.join(theme.cssfile)
             self.session.save()
             user = self.get_current_user()
             user.theme_id = theme.id
             dbsession.add(user)
             dbsession.flush()
             self.render_page()
         else:
             self.render_page(errors=["Theme does not exist."])
     else:
         self.render_page(errors=form.errors)
예제 #22
0
 def successful_login(self, user):
     ''' Called when a user successfully logs in '''
     logging.info("Successful login: %s/%s from %s" % (
         user.account,
         user.handle,
         self.request.remote_ip,
     ))
     self.start_session()
     theme = Theme.by_id(user.theme_id)
     if user.team is not None:
         self.session['team_id'] = int(user.team.id)
     self.session['user_id'] = int(user.id)
     self.session['handle'] = ''.join(user.handle)  # Copy string
     self.session['theme'] = ''.join(theme.cssfile)
     if user.has_permission('admin'):
         self.session['menu'] = 'admin'
     else:
         self.session['menu'] = 'user'
     self.session.save()
예제 #23
0
def theme_save_as(request, name):
    theme = get_object_or_404(Theme, name=name)

    if request.method == 'POST':
        # Theme
        new_theme = Theme()
        new_theme.verbose_name = request.POST['name']
        new_name = slugify(new_theme.verbose_name)
        counter = 0
        while Theme.objects.filter(name=new_name).exclude(pk=theme.pk).count():
            counter += 1
            new_name = '%s-%s'%(slugify(theme.verbose_name), counter)
        new_theme.name = new_name
        new_theme.save()

        # Templates
        for tpl in theme.templates.all():
            new_tpl, new = new_theme.templates.get_or_create(name=tpl.name)
            new_tpl.notes = tpl.notes
            new_tpl.content = tpl.content
            new_tpl.engine = tpl.engine
            new_tpl.save()

        # Static files
        for sf in theme.static_files.all():
            try:
                new_sf, new = new_theme.static_files.get_or_create(name=sf.name)
                new_sf.url = sf.url
                new_sf.mime_type = sf.mime_type
                new_sf.save()

                if sf.file:
                    # Finds a name for the new file
                    root = sf.file.path.replace(sf.file.name, '')
                    name, ext = os.path.splitext(sf.file.name)
                    while os.path.exists(root + name + ext):
                        name += '_'

                    # Reads the old file to make a ContentFile instance
                    fp = file(sf.file.path)
                    content = ContentFile(fp.read())
                    fp.close()
                    
                    # Saves the new file for the new static file object
                    new_sf.file.save(name+ext, content)
            except Exception, e:
                print (sf, e.__class__, e)
                raise

        ret = {'new_url': reverse('themes_theme', args=(new_theme.name,))}
예제 #24
0
	def post(self):
		scheduled_string = self.request.get('scheduled')
		theme_id = self.request.get('theme_id')
		player_list = self.request.get_all('player_list')
		action_intervals = self.request.get('action_intervals')
		context = {'players': Player.query().fetch(),
		           'themes': Theme.query(Theme.used == False).fetch()}
		if player_list and action_intervals:
			# Get the list of interval times
			try:
				interval_list = [int(x.strip()) for x in action_intervals.split(',')]
			except ValueError:
				raise ValueError("Invalid interval list '%s'. Must be comma separated.")
			if scheduled_string:
				scheduled = datetime.datetime.strptime(scheduled_string,
													   "%d.%m.%Y %H:%M")
			else:
				scheduled = get_mountain_time()
			theme = ndb.Key(Theme, int(theme_id))
			show = Show(scheduled=scheduled, theme=theme).put()
			players = []
			# Add the players to the show
			for player in player_list:
				player_key = ndb.Key(Player, int(player)).get().key
				players.append(player_key)
				ShowPlayer(show=show, player=player_key).put()
			# Make a copy of the list of players and randomize it
			rand_players = list(players)
			random.shuffle(rand_players, random.random)
			# Add the action intervals to the show
			for interval in interval_list:
				# If random players list gets empty, refill it with more players
				if len(rand_players) == 0:
					rand_players = list(players)
					random.shuffle(rand_players, random.random)
				# Pop a random player off the list and create a PlayerAction
				player_action = PlayerAction(interval=interval,
											 player=rand_players.pop()).put()
				ShowAction(show=show, player_action=player_action).put()
			context['created'] = True
		self.response.out.write(template.render(self.path('create_show.html'),
												self.add_context(context)))
예제 #25
0
    def post(self):
        created_user_id = ""
        user = users.get_current_user()
        if user:
            listOfUrls = []

            i = 0
            while True:
                f = self.request.POST.get("file[{}]".format(i))
                if type(f) == type(None):
                    break
                else:
                    url = writeToGCBucket(f)
                    listOfUrls.append(url)
                    i += 1

        created_user_id = user.user_id()
        themeName = self.request.get('meetupTheme')
        meetupName = self.request.get('meetupName')
        tags = self.request.get('meetupTags[]', allow_multiple=True)
        desc = self.request.get('meetupDescription')
        location = self.request.get('location')
        coordinates = getCoordinates(location)

        themeQuery = Theme.query(Theme.name == themeName)
        theme_id = themeQuery.fetch(keys_only=True)

        event = Events()
        event.name = meetupName
        event.description = desc
        event.created_user_id = created_user_id
        event.theme_id = theme_id
        event.image_urls = listOfUrls
        event.tag = tags
        event.cover_image = random.choice(listOfUrls)
        event.place = coordinates[0]
        event.lat = coordinates[1]
        event.long = coordinates[2]
        event.created_user_email = user.email()

        key = event.put()
        self.redirect('/manageMeetups')
예제 #26
0
    def get(self):
        user = users.get_current_user()
        email = self.request.get('email')
        template_values = get_generic_template_values(self)
        themeQuery = Theme.query()
        results = themeQuery.fetch()
        if user:

            #self.response.write(json.dumps(results))
            # for mobile
            #         serialized_results = filter_results(results)
            #         self.response.headers['Content-Type'] = 'application/json'
            #         self.response.write(json.dumps(serialized_results))

            template_values['results'] = results
            template = JINJA_ENVIRONMENT.get_template('/views/viewThemes.html')
            self.response.write(template.render(template_values))
        elif email:
            serialized_results = filter_results(results)
            self.response.headers['Content-Type'] = 'application/json'
            self.response.write(json.dumps(serialized_results))
예제 #27
0
 def successful_login(self, user):
     ''' Called when a user successfully logs in '''
     logging.info("Successful login: %s from %s" % (
         user.handle, self.request.remote_ip,
     ))
     user.last_login = datetime.now()
     user.logins += 1
     dbsession.add(user)
     dbsession.flush()
     self.start_session()
     theme = Theme.by_id(user.theme_id)
     if user.team is not None:
         self.session['team_id'] = int(user.team.id)
     self.session['user_id'] = int(user.id)
     self.session['user_uuid'] = user.uuid
     self.session['handle'] = user.handle
     self.session['theme'] = theme.cssfile
     if user.has_permission(ADMIN_PERMISSION):
         self.session['menu'] = 'admin'
     else:
         self.session['menu'] = 'user'
     self.session.save()
예제 #28
0
def insert_theme():
    last_theme = Theme.query.order_by(desc(Theme.date)).limit(1).all()[0]
    next_monday = time_calc.get_next_monday(last_theme.date)
    players = Player.query.all()
    head = ["id", "name"]
    players = [row2dict(p, head) for p in players]
    new_theme = None
    if request.method == 'POST':
        name = request.form.get('name')
        player_id = int(request.form.get('player'))
        print(player_id)
        date = request.form.get('date')
        try:
            new_theme = Theme(name=name, player_id=player_id, date=date)
            db.session.add(new_theme)
            db.session.commit()
        except Exception as e:
            return str(e)
    print(db.engine.pool.status())
    return render_template("insert_theme.html",
                           insert_theme_page=True,
                           players=players,
                           inserted=new_theme,
                           default_date=next_monday)
예제 #29
0
def home():
    display_message = None
    if request.method == 'POST':
        theme_name = request.form['theme_name']
        video_title = request.form['video_title']

        if theme_name and video_title:
            if Theme.objects(name=theme_name).count() > 0:
                theme = Theme.objects(name=theme_name).first()
            else:
                theme = Theme(name=theme_name)
                theme.save()
            
            Video(title=video_title, theme=theme).save()

            display_message = 'Video added successfully!'
        else:
            display_message = 'An error occurred while adding a video!'
        
    
    return render_template('homepage.html', videos=Video.objects(), message=display_message)
예제 #30
0
 def form_valid(self, form):
     name = form.cleaned_data['name']
     theme_color = form.cleaned_data['theme_color']
     background_image = form.cleaned_data['background_image']
     theme = Theme(name=name, theme_color=theme_color, background_image=background_image)
     theme.save()
예제 #31
0
	def post(self):
		deleted = None
		unused_deleted = False
		show_list = self.request.get_all('show_list')
		action_list = self.request.get_all('action_list')
		item_list = self.request.get_all('item_list')
		character_list = self.request.get_all('character_list')
		theme_list = self.request.get_all('theme_list')
		delete_unused = self.request.get_all('delete_unused')
		# If action(s) were deleted
		if action_list:
			for action in action_list:
				action_entity = ndb.Key(Action, int(action)).get()
				# Get all the related action votes and delete them
				action_votes = ActionVote.query(ActionVote.action == action_entity.key).fetch()
				for av in action_votes:
					av.key.delete()
				action_entity.key.delete()
			deleted = 'Action(s)'
		# If theme(s) were deleted
		if theme_list:
			for theme in theme_list:
				theme_entity = ndb.Key(Theme, int(theme)).get()
				# Get all the related theme votes and delete them
				theme_votes = ThemeVote.query(ThemeVote.theme == theme_entity.key).fetch()
				for tv in theme_votes:
					tv.key.delete()
				theme_entity.key.delete()
			deleted = 'Theme(s)'
		# If show(s) were deleted
		if show_list:
			for show in show_list:
				show_entity = ndb.Key(Show, int(show)).get()
				show_actions = ShowAction.query(ShowAction.show == show_entity.key).fetch()
				# Delete the actions that occurred within the show
				for show_action in show_actions:
					action = show_action.player_action.get().action
					if action:
						action.delete()
					show_action.player_action.delete()
					show_action.key.delete()
				# Delete player associations to the show
				show_players = ShowPlayer.query(ShowPlayer.show == show_entity.key).fetch()
				for show_player in show_players:
					show_player.key.delete()
				# Delete all Role votes
				role_votes = RoleVote.query(RoleVote.show == show_entity.key).fetch()
				for role_vote in role_votes:
					role_vote.key.delete()
				# Delete the theme used in the show, if it existed
				if show_entity.theme:
					show_entity.theme.delete()
				show_entity.key.delete()
				deleted = 'Show(s)'
		# Delete ALL un-used things
		if delete_unused:
			# Delete Un-used Actions
			unused_actions = Action.query(Action.used == False).fetch()
			for unused_action in unused_actions:
				# Get all the related action votes and delete them
				action_votes = ActionVote.query(ActionVote.action == unused_action.key).fetch()
				for av in action_votes:
					av.key.delete()
				# Delete the un-used actions
				unused_action.key.delete()
			deleted = 'All Un-used Actions'
		context = {'deleted': deleted,
				   'unused_deleted': unused_deleted,
				   'shows': Show.query().fetch(),
				   'actions': Action.query(Action.used == False).fetch(),
				   'themes': Theme.query(Theme.used == False).fetch()}
		self.response.out.write(template.render(self.path('delete_tools.html'),
												self.add_context(context)))
예제 #32
0
def themes():
    themelist = Theme.all()
    return JSON.dumps([x.simple_to_hash() for x in themelist.all()])
예제 #33
0
def save_theme():
    error = False
    errormessage = None
    themename = request.form.get("name")
    submitter = request.form.get("submitter", None)
    template = request.form.get("template", None)
    data = request.form.get("data", None)
    email = request.form.get("email", None)
    rendered = request.form.get("rendered", None)

    if (not error):
        if (themename == None):
            error = True
            errormessage = "You must enter a theme name"

    if (not error):
        recaptchallange = request.form.get("recaptcha_challenge_field")

    if (not error):
        recaptresponse = request.form.get("recaptcha_response_field")

    if (not error):
        if (submitter == None or submitter == ""):
            error = True
            errormessage = "Please enter your name"

    if (not error):
        if (email == None or email == ""):
            error = True
            errormessage = "Please enter your email"

    if (not error and not re.match(r"[^@]+@[^@]+\.[^@]+", email)):
        error = True
        errormessage = "Please enter a valid email address"

    if (not error):
        if (data == None or data == ""):
            error = True
            errormessage = "The no data found"

    if (not error):
        themedata = Theme.get_by_key_name(themename)
        if (themedata):
            error = True
            errormessage = "A theme with the same name already exist"

    if (not DEBUG):
        validation = recaptcha.submit(recaptchallange, recaptresponse,
                                      RECAPTCHA_KEY, request.remote_addr)
        if (not validation.is_valid):
            error = True
            errormessage = "Please reenter the recaptcha."

    if ((DEBUG or validation.is_valid) and not error):
        newtheme = Theme()
        newtheme.name = themename
        newtheme.submitter = submitter
        newtheme.email = email
        newtheme.data = data
        newtheme.counter = 0
        newtheme.rendered = rendered
        newtheme.generate_photo()
        newtheme.put()
        return 'success', 200
    elif (not error):
        return 'Something went wrong', 400
    else:
        return JSON.dumps({"error": errormessage}), 400
예제 #34
0
def themes():
    return render_template('themes.html', themes=Theme.objects().order_by('-score'))
예제 #35
0
	def get(self):
		context = {'shows': Show.query().fetch(),
				   'actions': Action.query(Action.used == False).fetch(),
				   'themes': Theme.query(Theme.used == False).fetch()}
		self.response.out.write(template.render(self.path('delete_tools.html'),
												self.add_context(context)))
예제 #36
0
파일: urls.py 프로젝트: mgoh/arkestrator

post_save.connect(invalidate_theme, sender=Theme)

default_cache_control = cache_control(
    max_age=604800,
    must_revalidate=False,
)

urlpatterns = patterns(
    '',
    url(r"^(?P<object_id>\d+)/$",
        default_cache_control(theme_css), {
            'queryset': Theme.objects,
            'template_name': 'themes/theme.css',
            'mimetype': 'text/css',
        },
        name='theme-css'),
    url(r"^default/$",
        default_cache_control(cache_page(direct_to_template, 600)), {
            'template': 'themes/theme.css',
            'mimetype': 'text/css',
            'extra_context': {
                'object': Theme(),
            },
        },
        name='default-theme-css'),
    url(r"^edit/$", edit_theme, name="edit-theme"),
    url(r"^edit/(?P<theme_id>\d+)/$", edit_theme, name="edit-existing-theme"),
)
예제 #37
0
def themes():
    themelist=Theme.all()
    return JSON.dumps([x.simple_to_hash() for x in themelist.all()])
예제 #38
0
    (u"Bootstrap", u'bootstrap.min.css'),
    (u"Amelia", u'amelia.min.css'),
    (u"Cyborg", u'cyborg.min.css'),
    (u"Readable", u'readable.min.css'),
    (u"Slate", u'slate.min.css'),
    (u"Spruce", u'spruce.min.css'),
    (u"United", u'united.min.css'),
    (u"Cerulean", u'cerulean.min.css'),
    (u"Journal", u'journal.min.css'),
    (u"Simplex", u'simplex.min.css'),
    (u"Spacelab", u'spacelab.min.css'),
    (u"Superhero", u'superhero.min.css'),
]
for css in css_files:
    theme = Theme(
        name=css[0],
        cssfile=css[1],
    )
    dbsession.add(theme)
    dbsession.flush()

# Market Items
item = MarketItem(
    name=u"Source Code Market",
    price=5000,
    description=u"Buy leaked source code.",
)
dbsession.add(item)
dbsession.flush()

item = MarketItem(
    name=u"Password Security",
예제 #39
0
    def get_source(self, environment, template):
        if ":" in template:
            active_theme, template_name = template.split(":", 1)
            active_theme = Theme.query().get(name=active_theme)
        elif getattr(environment, "theme", None):
            template_name = template
            active_theme = environment.theme
        else:
            template_name = template
            active_theme = None
            if app_settings.CACHE_EXPIRATION:
                try:
                    active_theme = Theme.query().get(pk=cache.get("themes:active", None))
                except Theme.DoesNotExist:
                    pass

            if not active_theme:
                try:
                    theme = Theme.query().get(is_default=True)
                    if app_settings.CACHE_EXPIRATION:
                        cache.set("themes:active", theme["pk"], app_settings.CACHE_EXPIRATION)
                    active_theme = theme
                except Theme.DoesNotExist:
                    # raise JinjaTemplateNotFound('There\'s no active theme.')
                    pass

        try:
            reg_template = get_registered_template(template)
        except KeyError:
            if app_settings.ALLOW_NOT_REGISTERED:
                reg_template = {}
            else:
                raise JinjaTemplateNotFound('Template "%s" is not registered.' % template)

        content = None
        uptodate = lambda: True
        full_name = None
        engine = None
        if active_theme:
            try:
                # Using cache to restore/store template content
                cache_key = "themes:%s|%s" % (active_theme["name"], template_name)
                content = cache.get(cache_key, None) if app_settings.CACHE_EXPIRATION else None

                if not content or not content.split(";", 1)[-1] or content.split(";", 1)[-1] == "None":
                    tpl = ThemeTemplate.query().get(theme=active_theme, name=template_name)
                    engine = tpl["engine"]
                    content = tpl["content"]
                    if app_settings.CACHE_EXPIRATION:
                        cache.set(cache_key, "engine:%s;%s" % (engine, content or ""), app_settings.CACHE_EXPIRATION)

                full_name = "%s:%s" % (active_theme["name"], template_name)
            except ThemeTemplate.DoesNotExist:
                content = None

        if reg_template and not content:
            content = reg_template.get("content", None)

        if not content:
            if (
                reg_template
                and reg_template.get("mirroring", None)
                and reg_template.get("mirroring", None) != template_name
            ):
                # Trying this firstly...
                try:
                    return self.get_source(environment, reg_template["mirroring"])
                except JinjaTemplateNotFound as e:
                    pass

                # If get no success, tries by the hardest way, from file system...
                ret = environment.get_template(reg_template["mirroring"])
                if ret:
                    f = open(ret.filename)
                    try:
                        contents = f.read()
                    finally:
                        f.close()
                    return contents.decode("utf-8"), ret.filename, ret.is_up_to_date
            raise JinjaTemplateNotFound('Template "%s" doesn\'t exist in active theme.' % template_name)

        if content.startswith("engine:"):
            engine, content = content.split(";", 1)
            engine = engine.split(":")[1]

        return content, full_name, uptodate
예제 #40
0
	def get(self):
		context = {'players': Player.query().fetch(),
				   'themes': Theme.query(Theme.used == False,
				   				).order(-Theme.vote_value).fetch()}
		self.response.out.write(template.render(self.path('create_show.html'),
												self.add_context(context)))
예제 #41
0
def load():
    Role.load_roles()
    Theme.load_themes()
예제 #42
0
def save_theme():
    error=False
    errormessage=None
    themename=request.form.get("name")
    submitter=request.form.get("submitter",None)
    template=request.form.get("template",None)
    data=request.form.get("data",None)
    email=request.form.get("email",None)
    rendered=request.form.get("rendered",None)

    if(not error):
        if(themename==None):
            error=True
            errormessage="You must enter a theme name"

    if(not error):
        recaptchallange=request.form.get("recaptcha_challenge_field")

    if(not error):
        recaptresponse=request.form.get("recaptcha_response_field")

    if(not error):
        if(submitter==None or submitter==""):
            error=True
            errormessage="Please enter your name"

    if(not error):
        if(email==None or email==""):
            error=True
            errormessage="Please enter your email"

    if(not error and not re.match(r"[^@]+@[^@]+\.[^@]+",email)):
        error=True
        errormessage="Please enter a valid email address"

    if(not error):
        if(data==None or data==""):
            error=True
            errormessage="The no data found"

    if(not error):
        themedata=Theme.get_by_key_name(themename)
        if(themedata):
            error=True
            errormessage="A theme with the same name already exist"

    if(not DEBUG):
        validation=recaptcha.submit(recaptchallange,recaptresponse,RECAPTCHA_KEY,request.remote_addr)
        if(not validation.is_valid):
            error=True
            errormessage="Please reenter the recaptcha."

    if((DEBUG or validation.is_valid) and not error):
        newtheme=Theme()
        newtheme.name=themename
        newtheme.submitter=submitter
        newtheme.email=email
        newtheme.data=data
        newtheme.counter=0
        newtheme.rendered=rendered
        newtheme.generate_photo()
        newtheme.put()
        return 'success',200
    elif(not error):
        return 'Something went wrong',400
    else:
        return JSON.dumps({ "error": errormessage }),400