Ejemplo n.º 1
0
def create(request):
    try:
        if not request.POST.get('pid', ''):
            return HttpResponse('You did not specify a parent ID.')
        else:
            parent = Section.objects.get(pk = request.POST['pid'])
    except:
        return HttpResponse('The specified ID # ' + request.POST['pid'] + ' does not exist.', status=400)
    
    if not request.POST.get('caption', ''):
        return HttpResponse('Name is not specified for the new section.')
    else:
        caption = unicode(request.POST['caption'])
    
    if request.POST.get('slug', ''):
        slug = request.POST['slug']
    else:
        slug = ''
        
    try:
        if request.POST.get('type', ''):
            section_type = SectionType.objects.get(pk = request.POST['type'])
        else:
            section_type = None
    except:
        return HttpResponse('Current type <b>' + request.POST['type'] + '</b> does not exist.', status=400)
    
    Section.create_section(parent, caption, slug, section_type)
    return HttpResponse('OK')
Ejemplo n.º 2
0
def get_sections():
    total_c = 0
    total_s = 0
    courses = Course.objects.all()
    for course in courses:
        total_s += 1
        try:
            link = "https://apis-dev.berkeley.edu/cxf/asws/classoffering/" + course.code + "?_type=json&app_id=a641ceca&app_key=eea0330432f77b498709afe6fe7fb6f8"
            data = json.loads(urlopen(link).read())
            sections = data["ClassOffering"]["sections"]
            if type(sections) == list:
                for section in sections:
                    total_c += 1
                    number = section['sectionNumber']
                    s = Section()
                    s.init(number, course)
                    s.save()
            elif type(sections) == dict:
                total_c += 1
                number = sections['sectionNumber']
                s = Section()
                s.init(number, course)
                s.save()
        except Exception:
            continue
        print "Courses:   " + str(total_s) + " / " + str(len(courses)) + "     Sections:   " + str(total_c)    
Ejemplo n.º 3
0
def destroy(id=1):
    try:
        sections = Section()
        section = sections.query.get_or_404(id)

        if section.children:
            # html or Json response
            if request_wants_json():
                return jsonify(data={
                    message:
                    "Unauthorized : Must delete child's section' first"
                }), 422, {
                    'Content-Type': 'application/json'
                }
            else:
                flash("Unauthorized : Must delete child's section first.",
                      category="danger")
                return redirect(url_for('sections_page.index'))

        else:
            sections.destroy_data(section.id)
            # html or Json response
            if request_wants_json():
                return jsonify(data={
                    message: "Record deleted successfully.",
                    section: m_section
                })
            else:
                flash("Record deleted successfully.", category="success")
                return redirect(url_for('sections_page.index'))

    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
        flash(str(ex.message), category="warning")
        abort(404)
Ejemplo n.º 4
0
 def process_request(self, request):
     try:
         request.current_section = Section.get_node_by_path(request.path)
         request.structure = Section.get_structure()
     except:
         request.current_section = None
         request.structure = {}
Ejemplo n.º 5
0
    def post(self):
        item = None
        vals = {}
        try:
            # get all the incoming values
            section = Section.get( self.request.get('section') )
            name = self.request.get('name').strip()
            title = self.request.get('title').strip()
            content = self.request.get('content')
            type = self.request.get('type')
            label_raw = self.request.get('label_raw').strip()
            attribute_raw = util.make_attr_raw_string(
                {
                    'index-entry'   : self.request.get('index_entry'),
                    'has-comments'  : self.request.get('has_comments'),
                    'comments-open' : self.request.get('comments_open'),
                    }
                ).strip()

            # some pre-processing of the input params
            if name == '':
                name = util.urlify(self.request.get('title'))

            if self.request.get('key'):
                item = Page.get( self.request.get('key') )
                item.section = section
                item.name = name
                item.title = title
                item.content = content
                item.type = type
                item.label_raw = label_raw
                item.attribute_raw = attribute_raw
            else:
                item = Page(
                    section = section,
                    name = name,
                    title = title,
                    content = content,
                    type = type,
                    label_raw = label_raw,
                    attribute_raw = attribute_raw,
                    )

            # update and save this page
            item.set_derivatives()
            item.put()
            # once saved, regenerate certain section properties
            section.regenerate()
            # also, check that this section doesn't have duplicate content
            Task( params={ 'section_key': str(section.key()), 'name': item.name }, countdown=30, ).add( queue_name='section-check-duplicate-nodes' )
            self.redirect('.')
        except Exception, err:
            vals['item'] = self.request.POST
            vals['err'] = err
            vals['sections'] = Section.all()
            vals['types'] = models.type_choices
            self.template( 'page-form.html', vals, 'admin' );
Ejemplo n.º 6
0
def new():
    try:
        users = User.query.filter(User.is_active == True).all()
        form = Form_Record_Add(request.form)
        sections = Section.query.filter(Section.is_active == True).all()
        items = Item.query.filter(Item.is_active == True).all()

        if request.method == 'POST':
            if form.validate():
                sections = Section()

                sanitize_form = {
                    'slug': form.slug.data,
                    'parent': form.parent.data,
                    'title_en_US': form.title_en_US.data,
                    'title_fr_FR': form.title_fr_FR.data,
                    'description_en_US': form.description_en_US.data,
                    'description_fr_FR': form.description_fr_FR.data,
                    'users': form.users.data,
                    'items': form.items.data,
                    'is_active': form.is_active.data
                }

                Section().create_data(sanitize_form)
                logger.info("Adding a new record.")

                if request_wants_json():
                    return jsonify(data={
                        message: "Record added successfully.",
                        form: form
                    }), 200, {
                        'Content-Type': 'application/json'
                    }
                else:
                    flash("Record added successfully.", category="success")
                    return redirect("/sections")

        form.action = url_for('sections_page.new')

        # html or Json response
        if request_wants_json():
            return jsonify(data=form), 200, {
                'Content-Type': 'application/json'
            }
        else:
            return render_template("sections/edit.html",
                                   form=form,
                                   sections=sections,
                                   items=items,
                                   users=users,
                                   title_en_US='New',
                                   app=app)
    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
        flash(str(ex.message), category="warning")
        abort(404)
Ejemplo n.º 7
0
def update(request):
    id = eval("request." + request.method + "['id']")
    if Post.objects(id=id):
        post = Post.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            post.title = request.POST['title']
            str_date_published = request.POST['date_published']
            post.date_published = datetime.fromtimestamp(
                mktime(time.strptime(str_date_published, "%b %d %Y")))
            post.publisher = request.POST['publisher']
            post.papertype = request.POST['papertype']
            post.authors = request.POST['authors']
            post.additional_info = request.POST['additional_info']
            post.page_num = request.POST['page_num']
            if request.POST.get('selectedpublication', True):
                post.selectedpublication = True
            post.save()
            params = {'Posts': Post.objects}

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'post': post}

    elif Section.objects(id=id):
        section = Section.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            section.heading = request.POST['heading']
            section.content = request.POST['content']
            section.save()
            params = {'Sections': Section.objects}

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'section': section}

    elif Profile.objects(id=id):
        profile = Profile.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            profile.details = request.POST['profile']
            profile.save()
            params = {'Profile': Profile.objects.limit(1)}

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'Profile': Profile.objects.limit(1)}

    return render_to_response(template,
                              params,
                              context_instance=RequestContext(request))
Ejemplo n.º 8
0
def update(request):
    id = eval("request." + request.method + "['id']")
    if Post.objects(id=id):
        post = Post.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            post.title = request.POST['title']
            #str_date_published = request.POST['date_published']
            #post.date_published = datetime.fromtimestamp(mktime(time.strptime(str_date_published, "%b %d %Y")))
            post.publisher = request.POST['publisher']
            post.papertype = request.POST['papertype']
            post.authors = request.POST['authors']
            #post.additional_info = request.POST['additional_info']
            #post.page_num = request.POST['page_num']
            #if request.POST.get('selectedpublication', True):
            #    post.selectedpublication = True;
            post.save()
            params = {'Posts': Post.objects} 

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'post':post}
    
    elif Section.objects(id=id):
        section = Section.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            section.heading = request.POST['heading']
            section.content = request.POST['content']
            section.save()
            params = {'Sections': Section.objects} 

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'section':section}
            
    elif Profile.objects(id=id):
        profile = Profile.objects(id=id)[0]
        if request.method == 'POST':
            template = 'admin/index.html'
            # update field values and save to mongo
            profile.details = request.POST['profile']
            profile.save()
            params = {'Profile': Profile.objects.limit(1)} 

        elif request.method == 'GET':
            template = 'admin/update.html'
            params = {'Profile': Profile.objects.limit(1)}

    return render_to_response(template, params, context_instance=RequestContext(request))
Ejemplo n.º 9
0
 def _get_or_create_section(self, course, instructors):
     section_record = Section.query.filter_by(crn=course.crn).first()
     if not section_record:
         section_record = Section("Spring 2015", course.crn, course.start_time,
                                  course.end_time, course.days, course.enrollment)
         #print "Adding Section: \"%s\"" % course.crn
         self.num_new_sections += 1
     section_record.instructors = instructors
     db.session.add(section_record)
     #db.session.commit()
     if course.crn not in self.crns:
         self.num_sections += 1
         self.crns[course.crn] = True
     return section_record
Ejemplo n.º 10
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        user = self.context['request'].user

        if instance is None:
            instance = Section(classgroup=classgroup, name=alphanumeric_name(name), display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError("You do not have permission to modify this section.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name
        return instance
Ejemplo n.º 11
0
def show(id=1):
    try:
        m_sections = Section()
        m_section = m_sections.read_data(id)
        # html or Json response
        if request_wants_json():
            return jsonify(data=m_section)
        else:
            return render_template("sections/show.html",
                                   section=m_section,
                                   app=app)

    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
        flash(str(ex.message), category="warning")
        abort(404)
    def get_instructor_terms(self):
        instructor_id = self.get_payload()['id']
        query = (Section.select(Term.title, Term.id).distinct().join(
            Term, on=(Section.term_id == Term.id)).where(
                Section.instructor_id == instructor_id).dicts())

        return query
Ejemplo n.º 13
0
def eval(ast, document, last_create=None):
    head, *tail = ast

    if head[0] == 'section':
        section = Section(head[1].rstrip())
        document.sections.append(section)
        if tail:
            eval(tail, document, 'section')
    elif head[0] == 'subsection':
        subsection = Subsection(head[1].rstrip())
        document.sections[-1].subsections.append(subsection)
        if tail:
            eval(tail, document, 'subsection')
    elif head[0] == 'attr':
        value = tail[0][1].replace('{', "")
        value = value.replace('}', "")
        value = value.replace('\t', "")
        attr = ({head[1]: (value).rstrip()})
        if last_create == 'section':
            document.sections[-1].attrs.append(attr)
        else:
            document.sections[-1].subsections[-1].attrs.append(attr)
    else:
        eval(head, document, last_create)
        if tail:
            eval(tail, document, last_create)
Ejemplo n.º 14
0
def admin_sections():
    if not User.is_logged_in():
        return redirect('/admin/login?e=You%20need%20to%20log%20in%20first')
    args = {
        'sections': Section.get_all()
    }
    return render('/admin/sections.html', 'Sections', args)
Ejemplo n.º 15
0
def admin_sections_name(name):
    if not User.is_logged_in():
        return redirect('/admin/login?e=You%20need%20to%20log%20in%20first')
    args = {
        'section': Section.get(name)
    }
    return render('/admin/section_single.html', '{} section'.format(args['section'].title), args)
Ejemplo n.º 16
0
    def post(self):
        item = None
        vals = {}
        try:
            # get all the incoming values
            name = self.request.get('name')
            email = self.request.get('email')
            website = self.request.get('website')
            comment = self.request.get('comment')

            if self.request.get('key'):
                item = Comment.get( self.request.get('key') )
                item.name = name
                item.email = email
                item.website = website
                item.comment = comment
            else:
                # we have no ability to add comments, so fail here
                raise error.RequiresEntityError("Needs a comment key (ie. can't add new comments in the admin interface)")

            # update and save this comment
            item.set_derivatives()
            item.put()

            # don't need to item.node.regenerate() since the status is _not_ changing

            self.redirect('.')
        except Exception, err:
            vals['item'] = self.request.POST
            vals['err'] = err
            vals['sections'] = Section.all()
            vals['types'] = models.type_choices
            self.template( 'comment-form.html', vals, 'admin' );
Ejemplo n.º 17
0
 def post(self, request):
     response_data = {'retCode': error_constants.ERR_STATUS_SUCCESS[0],
                      'retMsg': error_constants.ERR_STATUS_SUCCESS[1]}
     try:
         section_id = int(request.POST.get('sectionId'))
         name = request.POST.get('name')
         start_place = request.POST.get('startPlace')
         end_place = request.POST.get('endPlace')
         xy_coordinate = request.POST.get('XYCOORDINATE', '')
         channel = request.POST.get('channel', '')
         call_sign = request.POST.get('callSign', '')
         remark_1 = request.POST.get('remark1', '')
         remark_2 = request.POST.get('remark2', '')
         remark_3 = request.POST.get('remark3', '')
     except Exception as ex:
         print 'function name: ', __name__
         print Exception, ":", ex
         return generate_error_response(error_constants.ERR_INVALID_PARAMETER, status.HTTP_400_BAD_REQUEST)
     cur_section = Section.objects.get(id=section_id)
     district_id = cur_section.district_id
     new_section = Section(name=name, start_place=start_place, channel=channel, call_sign=call_sign,
                                          end_place=end_place, xy_coordinate=xy_coordinate,
                                          remark1=remark_1, remark2=remark_2, remark3=remark_3,
                                          district_id=district_id)
     try:
         with transaction.atomic():
             new_section.save()
     except Exception as ex:
         print 'function name: ', __name__
         print Exception, ":", ex
         return generate_error_response(error_constants.ERR_SAVE_INFO_FAIL,
                                        status.HTTP_500_INTERNAL_SERVER_ERROR)
     chief = cur_section.chief.all()
     bureau = cur_section.exec_chief_sub_bureau.all()
     trans = cur_section.exec_chief_trans.all()
     arm_poli = cur_section.exec_chief_armed_poli.all()
     for item in chief:
         new_section.chief.add(item)
     for item in bureau:
         new_section.exec_chief_sub_bureau.add(item)
     for item in trans:
         new_section.exec_chief_trans.add(item)
     for item in arm_poli:
         new_section.exec_chief_armed_poli.add(item)
     # 复制段时将岗及人员全部复制关联
     copy_station_to_new_section(new_section, cur_section)
     return Response(response_data, status.HTTP_200_OK)
Ejemplo n.º 18
0
def sections(request):
    if request.method == 'POST':
       # save new post
       heading = request.POST['heading']
       content = request.POST['content']
       
       section = Section(heading=heading)
       section.heading = heading
#       section.content = cgi.escape(content).encode("ascii", "xmlcharrefreplace")
       section.content = content
       section.save()

    # Get all sections from DB
    sections = Section.objects

    return render_to_response('admin/index.html', {'Sections': sections},
                              context_instance=RequestContext(request))
Ejemplo n.º 19
0
def get_all_sections():
    """Get all sections"""
    return {
        "sections": [
            Section(id=ind, name=section, slug=slug)
            for ind, (slug, section) in enumerate(slug_to_section.items())
        ]
    }
Ejemplo n.º 20
0
    def import_sections(sheet_url):
        index = read_spreadsheet(course="cs61a", url=sheet_url, sheet_name="Index")
        header = index[0][:4]
        if header != ["Day", "Start Time", "End Time", "Sheet"]:
            raise Failure("Invalid header for index sheet")
        for day, start_time, end_time, sheet, *args in index[1:]:
            sheet: List[List[Union[str, int]]] = read_spreadsheet(
                course="cs61a", url=sheet_url, sheet_name=repr(sheet)
            )
            header = sheet[0]
            name_col = header.index("Name")
            email_col = header.index("Email")

            day = list(calendar.day_name).index(day)

            start_time = datetime.strptime(start_time, "%I:%M %p")
            start_time = start_time.replace(
                year=datetime.now().year,
                month=datetime.now().month,
                day=datetime.now().day,
            )
            while start_time.weekday() != day:
                start_time += timedelta(days=1)

            end_time = datetime.strptime(end_time, "%I:%M %p")
            end_time = end_time.replace(
                year=start_time.year, month=start_time.month, day=start_time.day
            )

            pst = pytz.timezone("US/Pacific")
            start_time = pst.localize(start_time).timestamp()
            end_time = pst.localize(end_time).timestamp()

            for section in sheet[1:]:
                tutor_name = section[name_col]
                tutor_email = section[email_col]
                if not tutor_name or not tutor_email:
                    continue
                tutor_user = User.query.filter_by(email=tutor_email).one_or_none()
                if tutor_user is None:
                    tutor_user = User(email=tutor_email, name=tutor_name, is_staff=True)
                    db.session.add(tutor_user)
                tutor_user.is_staff = True

                capacity = sum(1 for col in header if "Student" in col)

                db.session.add(
                    Section(
                        start_time=start_time,
                        end_time=end_time,
                        capacity=capacity,
                        staff=tutor_user,
                    )
                )

            db.session.commit()

        return refresh_state()
Ejemplo n.º 21
0
def section_save(section_key_us=None):
    form = SectionFormAdmin()

    # form validation
    if not form.validate_on_submit():
        return "VALIDATION_ERROR", 400

    # get and validate parent section
    if form.parent_section.data == '/':
        parent_section_key = None
    else:
        parent_section = ndb.Key(
            urlsafe=form.parent_section.data).get() or abort(404)
        parent_section_key = parent_section.key

    # section instance
    if section_key_us:
        # edit
        # print 'admin section save EDIT'
        section = ndb.Key(urlsafe=section_key_us).get() or abort(404)
    else:
        # new
        # print 'admin section save NEW'
        section = Section()

    # update data
    g.cache.clear()
    section.parent_section = parent_section_key
    section.set_name(form.name.data, g.language)
    section.put()
    return 'ok'
Ejemplo n.º 22
0
    def get_list(self, *args, **kwargs):
        count, threads = super().get_list(*args, **kwargs)

        for thread in threads:
            thread.forum = Forum.get(thread.forum).title
            thread.section = Section.get(thread.section).title
            thread.author = User.get(thread.author).username

        return count, threads
Ejemplo n.º 23
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.write('Started section regeneration task:')

        key = self.request.get('key')
        self.write('- key = ' + key)

        # ok, so get the section first
        section = Section.get( self.request.get('key') )
        if section is None:
            self.write('No section found')
            logging.warn( 'No section found for key: ' +  key )
            return

        # keep a count of all these things
        labels = {}
        archives = {}

        # get all the nodes
        # FixMe: why doesn't "nodes = section.nodes()" work ???
        nodes = Node.all().filter('section =', section.key())
        self.write('Nodes:')
        for node in nodes:
            self.write('- node=' + node.kind()) # FixMe: why doesn't "node.name()" work :(
            # count all of the labels
            for label in node.label:
                self.write('  - ' + label)
                if label in labels:
                    labels[label] += 1
                else:
                    labels[label] = 1

            # the archive counts
            for archive in node.archive:
                self.write('  - ' + archive)
                if archive in archives:
                    archives[archive] += 1
                else:
                    archives[archive] = 1

        # after all that, make them into a list (for ease of use in Django Templates)
        archives = [
            { 'archive' : x, 'count' : archives[x] }
            for x in sorted(archives)
            if re.search(r'^\d\d\d\d(-\d\d)?$', x, re.DOTALL | re.VERBOSE) # just get years and months
            ]
        labels = [
            { 'label' : x, 'count' : labels[x] }
            for x in sorted(labels)
            ]

        # now that we have our counts, save it as JSON
        section.archive_json = archives
        section.label_json = labels
        section.put()

        self.write('Finished')
Ejemplo n.º 24
0
def wtp_catalog(request, pid):
    context = get_default_context(request)
    product = Product.objects.get(pk=pid)
    wtp_pid = []
    for wtp in product.wtp.all():
        wtp_pid.append(wtp.id)
    context['wtp_pid'] = wtp_pid
    context['catalog'] = Product.objects.filter(section=Section.get_node_by_path(request.POST['current_section'])).order_by('-order')
    return render_to_response('wtp/catalog.html', context)
Ejemplo n.º 25
0
def action_catalog(request, id):
    context = get_default_context(request)
    product_in_actions = Action.objects.get(pk=id)
    action_id = []
    for product in product_in_actions.products.all():
        action_id.append(product.id)
    context['action_id'] = action_id
    context['catalog'] = Product.objects.filter(section=Section.get_node_by_path(request.POST['current_section'])).order_by('-order')
    return render_to_response('change_action/catalog.html', context)
Ejemplo n.º 26
0
    def post(self):
        item = None
        vals = {}
        try:
            # get all the incoming values
            path = self.request.get('path').strip()
            title = self.request.get('title').strip()
            description = self.request.get('description')
            type = self.request.get('type')
            layout = self.request.get('layout')
            attribute_raw = util.make_attr_raw_string(
                {
                    'sitemap-entry' : self.request.get('sitemap_entry'),
                    'contact-form'  : self.request.get('contact_form'),
                    'sitefeed'      : self.request.get('sitefeed'),
                    }
                ).strip()

            # some pre-processing of the input params
            description_html = util.render(description, type)

            if self.request.get('key'):
                item = Section.get( self.request.get('key') )
                item.path = path
                item.title = title
                item.description = description
                item.description_html = description_html
                item.type = type
                item.layout = layout
                item.attribute_raw = attribute_raw
            else:
                item = Section(
                    path = path,
                    title = title,
                    description = description,
                    description_html = description_html,
                    type = type,
                    layout = layout,
                    attribute_raw = attribute_raw,
                    )

            # update and save this section
            item.set_derivatives()
            item.put()
            # once saved, add the section to the two task queues
            item.regenerate()
            self.redirect('.')
        except Exception, err:
            vals['item'] = self.request.POST
            vals['err'] = err
            vals['types'] = models.type_choices
            vals['layouts'] = models.layout_choices
            self.template( 'section-form.html', vals, 'admin' );
Ejemplo n.º 27
0
class SectionForm(wt.Form):

    title = wt.StringField(validators=(wt.validators.required(), ))
    forum = wt.SelectField(choices=[(forum.id, forum.title)
                                    for forum in Forum.all()],
                           coerce=int)
    # TODO(a.telishev): Section relates from forum
    parent = wt.SelectField(choices=[(section.id, section.title)
                                     for section in Section.all()],
                            coerce=int)
Ejemplo n.º 28
0
def public_homepage():
    return render_public_template(
        'public/default.html',
        'HomePage',
        {
            'sections': Section.get_all()
        }
    )

####: Stop Editing
Ejemplo n.º 29
0
    def get(self):
        item = None
        if self.request.get('key'):
            item = Section.get( self.request.get('key') )

        vals = {
            'item' : item,
            'types' : models.type_choices,
            'layouts' : models.layout_choices,
            }
        self.template( 'section-form.html', vals, 'admin' );
Ejemplo n.º 30
0
    def get_list(self, *args, **kwargs):
        count, sections = super().get_list(*args, **kwargs)

        for section in sections:
            section.forum = Forum.get(section.forum).title
            parent = Section.get(section.parent)
            if parent:
                section.parent = parent.title
            section.created_by = User.get(section.created_by).username

        return count, sections
Ejemplo n.º 31
0
    def get(self):
        item = None
        if self.request.get('key'):
            item = Page.get( self.request.get('key') )

        vals = {
            'item' : item,
            'sections' : Section.all(),
            'types' : models.type_choices
            }
        self.template( 'page-form.html', vals, 'admin' );
Ejemplo n.º 32
0
def add_section():

    if request.method == "POST":
        title = request.form['title']
        description = request.form['description']
        new_section = Section(title=title, description=description)
        db.session.add(new_section)
        db.session.commit()
        return redirect(url_for('admin_bag'))

    return render_template('add_section.html')
Ejemplo n.º 33
0
    def get(self):
        sections = Section.all().fetch(section_count+1)

        more = True if len(sections) > section_count else False

        vals = {
            'title'         : 'Section List',
            'sections'      : sections,
            'section_count' : section_count if more else len(sections),
            'more'          : more,
        }
        self.template( 'section-list.html', vals, 'admin' );
    def get_instructor_term_sections(self):
        instructor_id = self.get_payload()['id']
        term_id = self.get_payload()['term_id']

        query = (Section.select(Course.name, Course.title, Section.number,
                                Section.id).join(
                                    Course,
                                    on=(Section.course_id == Course.id)).where(
                                        Section.instructor_id == instructor_id,
                                        Section.term_id == term_id).dicts())

        return query
Ejemplo n.º 35
0
def addsection():
    if not g.user:  # not logged in
        return redirect(url_for('home'))
    desc = request.form['description']
    if desc == '':
        flash('error: must enter a title')
    else:
        db.session.add(Section(desc, session['user_id'],
                               request.form['color']))
        db.session.commit()
        flash('added section')
    return redirect(url_for('sections'))
Ejemplo n.º 36
0
def index(page=1):
    try:
        m_sections = Section()
        list_sections = m_sections.all_data(page,
                                            app.config['LISTINGS_PER_PAGE'])
        # html or Json response
        if request_wants_json():
            return jsonify([{
                'id': d.id,
                'title_en_US': d.title_en_US,
                'description_en_US': d.description_en_US,
                'title_fr_FR': d.title_fr_FR,
                'description_fr_FR': d.description_fr_FR
            } for d in list_sections.items])
        else:
            return render_template("sections/index.html",
                                   list_sections=list_sections,
                                   app=app)

    except Exception, ex:
        print("------------ ERROR  ------------\n" + str(ex.message))
Ejemplo n.º 37
0
    def get(self):
        item = None
        if self.request.get('key'):
            item = Comment.get( self.request.get('key') )
        else:
            raise error.RequiresEntityError("Needs a comment key (ie. can't add new comments in the admin interface)")

        vals = {
            'item' : item,
            'sections' : Section.all(),
            'types' : models.type_choices
            }
        self.template( 'comment-form.html', vals, 'admin' );
Ejemplo n.º 38
0
def delete(request):
    id = eval("request." + request.method + "['id']")

    if request.method == 'POST':
        template = 'admin/index.html'
        if Post.objects(id=id):
            post = Post.objects(id=id)[0]
            post.delete()
            params = {'Posts': Post.objects, 'Sections': Section.objects, 'Profile': Profile.objects.limit(1)} 
        elif Section.objects(id=id):
            section = Section.objects(id=id)[0]
            section.delete()            
            params = {'Sections': Section.objects, 'Posts': Post.objects, 'Profile': Profile.objects.limit(1)} 
        elif Profile.objects(id=id):
            profile = Profile.objects(id=id)[0]
            profile.delete()            
            params = {'Profile': Profile.objects.limit(1), 'Sections': Section.objects, 'Posts': Post.objects} 
    elif request.method == 'GET':
        template = 'admin/delete.html'
        params = { 'id': id } 

    return render_to_response(template, params, context_instance=RequestContext(request))
Ejemplo n.º 39
0
    def post(self, request):
        response_data = {'retCode': error_constants.ERR_STATUS_SUCCESS[0],
                         'retMsg': error_constants.ERR_STATUS_SUCCESS[1]}
        try:
            road_id = int(request.POST.get('roadId', 0))
            district_id = int(request.POST.get('districtId'))
            name = request.POST.get('name')
            start_place = request.POST.get('startPlace')
            end_place = request.POST.get('endPlace')
            xy_coordinate = request.POST.get('XYCOORDINATE', '')
            channel = request.POST.get('channel', '')
            call_sign = request.POST.get('callSign', '')
            remark_1 = request.POST.get('remark1', '')
            remark_2 = request.POST.get('remark2', '')
            remark_3 = request.POST.get('remark3', '')
        except Exception as ex:
            print 'function name: ', __name__
            print Exception, ":", ex
            return generate_error_response(error_constants.ERR_INVALID_PARAMETER, status.HTTP_400_BAD_REQUEST)

        if road_id:
            cur_section = Section(name=name, start_place=start_place, end_place=end_place,
                                                 xy_coordinate=xy_coordinate, road_id=road_id, channel=channel,
                                                 call_sign=call_sign, remark1=remark_1, remark2=remark_2,
                                                 remark3=remark_3, district_id=Road.objects.get(id=road_id).district_id)

            try:
                with transaction.atomic():
                    cur_section.save()
            except Exception as ex:
                print 'function name: ', __name__
                print Exception, ":", ex
                return generate_error_response(error_constants.ERR_SAVE_INFO_FAIL,
                                               status.HTTP_500_INTERNAL_SERVER_ERROR)
            update_road_section_ids(road_id, cur_section.id, True)
        else:
            cur_section = Section(name=name, start_place=start_place,
                                                 end_place=end_place, xy_coordinate=xy_coordinate,
                                                 remark1=remark_1, channel=channel, call_sign=call_sign,
                                                 remark2=remark_2, remark3=remark_3, district_id=district_id)
            try:
                with transaction.atomic():
                    cur_section.save()
            except Exception as ex:
                print 'function name: ', __name__
                print Exception, ":", ex
                return generate_error_response(error_constants.ERR_SAVE_INFO_FAIL,
                                               status.HTTP_500_INTERNAL_SERVER_ERROR)
        return Response(response_data, status=status.HTTP_200_OK)
Ejemplo n.º 40
0
    def get(self):
        try:
            if self.request.get('key'):
                item = Section.get( self.request.get('key') )

                vals = {
                    'item' : item,
                    }
                self.template( 'section-del.html', vals, 'admin' );
            else:
                self.redirect('.')
        except:
            self.redirect('.')
Ejemplo n.º 41
0
def manage_sections(request):
    """
    Render the page where instructors can go to make a new section or
    edit existing ones.
    """

    if request.method == "POST":
        # Class is being submitted
        form = NewSectionForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data["name"]
            new_section = Section(name=name)
            new_section.save()
            return HttpResponseRedirect("/managesection/")

    form = NewSectionForm()
    sections = Section.objects.all()
    context = {
        "form": form,
        "sections": sections,
        "listSize": sections.count()
    }
    return render(request, "managesection.html", context)
Ejemplo n.º 42
0
 def get(self):
     vals = {
         'sections'   : Section.all(),
         'node_types' : models.node_choices,
         'title'      : 'Import a node',
         'data_types' : [
             { 'value' : 'json', 'text' : 'JSON' },
             { 'value' : 'yaml', 'text' : 'YAML' },
             ],
         'node_type'   : self.request.get('node_type'),
         'section_key' : self.request.get('section_key'),
         'data_type'   : self.request.get('data_type'),
         }
     self.template( 'load-form.html', vals, 'admin' );
Ejemplo n.º 43
0
    def get(self):
        section = None
        if self.request.get('section'):
            try:
                section = Section.get( self.request.get('section') )
            except BadKeyError:
                # invalid key
                self.redirect('.')
            pages = Page.all().filter('section =', section).order('-inserted').fetch(page_count+1)
        else:
            pages = Page.all().order('-inserted').fetch(page_count+1)

        more = True if len(pages) > page_count else False

        vals = {
            'title'      : 'Page List',
            'sections'   : Section.all(),
            'section'    : section,
            'pages'      : pages,
            'page_count' : page_count if more else len(pages),
            'more'       : more,
        }
        self.template( 'page-list.html', vals, 'admin' );
Ejemplo n.º 44
0
def delete(request):
    id = eval("request." + request.method + "['id']")

    if request.method == 'POST':
        template = 'admin/index.html'
        if Post.objects(id=id):
            post = Post.objects(id=id)[0]
            post.delete()
            params = {
                'Posts': Post.objects,
                'Sections': Section.objects,
                'Profile': Profile.objects.limit(1)
            }
        elif Section.objects(id=id):
            section = Section.objects(id=id)[0]
            section.delete()
            params = {
                'Sections': Section.objects,
                'Posts': Post.objects,
                'Profile': Profile.objects.limit(1)
            }
        elif Profile.objects(id=id):
            profile = Profile.objects(id=id)[0]
            profile.delete()
            params = {
                'Profile': Profile.objects.limit(1),
                'Sections': Section.objects,
                'Posts': Post.objects
            }
    elif request.method == 'GET':
        template = 'admin/delete.html'
        params = {'id': id}

    return render_to_response(template,
                              params,
                              context_instance=RequestContext(request))
Ejemplo n.º 45
0
 def post(self):
     try:
         item = Section.get( self.request.get('key') ) if self.request.get('key') else None
         if item is not None:
             try:
                 item.delete()
                 self.redirect('.')
             except:
                 vals = {
                     'item' : item,
                     'err' : 'There was an error when deleting this section, please try again'
                     }
                 self.template( 'section-del.html', vals, 'admin' );
     except:
         self.redirect('.')
Ejemplo n.º 46
0
    def index(self):
        counts = {
            'forums': Forum.count(),
            'sections': Section.count(),
            'threads': Thread.count(),
            'labels': ThreadLabel.count(),
            'answers': Answer.count(),
            'users': User.count(),
        }
        for item, count in counts.items():
            counts[item] = '{:,}'.format(counts[item])

        date = datetime.now().strftime('%d.%m.%Y %H:%M')

        return self.render(
            'admin/statistics.html',
            date=date,
            counts=counts,
        )
Ejemplo n.º 47
0
def index():
    # is a search?
    if 'q' in request.args:
        res = []
        q = request.args.get('q', '')
        q = q.lower()
        sections = Section.query(Section.lname_searchable == q).fetch(10)
        for section in sections:
            r = {}
            r['value'] = section.key.urlsafe()
            r['section_name'] = section.name
            r['section_path'] = section.path
            res.append(r)
        return jsonify({'results': res})

    # sections_tree_ent = ndb.Key('SectionTree', g.language).get()
    # if sections_tree_ent:
    # 	sections_tree = sections_tree_ent.tree
    # else:
    # 	sections_tree = {}
    #
    # root_routes = get_root_routes()
    # return render_template(
    # 	'atuincms/pages/admin/index.html',
    # 	menuid='pages',
    # 	sections_tree=sections_tree,
    # 	root_routes=root_routes
    # )

    sections = get_sections_by_parent(None)
    root_routes = atuincms.router.get_root_routes()
    # menu_lang_form = MenuLangFormAdmin()
    section_form = SectionFormAdmin()

    return render_template('atuincms/sections/admin/index.html',
                           menuid='sections',
                           sections=sections,
                           root_routes=root_routes,
                           section_form=section_form)
Ejemplo n.º 48
0
def sections(request):
    if request.method == 'POST':
        # save new post
        heading = request.POST['heading']
        content = request.POST['content']

        section = Section(heading=heading)
        section.heading = heading
        #       section.content = cgi.escape(content).encode("ascii", "xmlcharrefreplace")
        section.content = content
        section.save()

    # Get all sections from DB
    sections = Section.objects

    return render_to_response('admin/index.html', {'Sections': sections},
                              context_instance=RequestContext(request))
Ejemplo n.º 49
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/plain'
        self.write('Started section duplicate node check:')

        section_key = self.request.get('section_key')
        name = self.request.get('name')
        self.write('- key  = ' + section_key)
        self.write('- name = ' + name)

        # get the section first (and if the section_key is crap just finish)
        section = None
        try:
            section = Section.get( self.request.get('section_key') )
        except:
            # by just returning here, it ends up a 200, so all is good
            return

        if section is None:
            self.write('No section found')
            logging.warn( 'No section found for key: ' +  section_key )
            return

        nodes = Node.all().filter('section =', section).filter('name =', name)
        if nodes.count() <= 1:
            msg = 'Only [%d] nodes of this name in this section' % nodes.count()
            self.write(msg)
            return

        msg = 'More than one node named [%s] in section [%s]' % (name, section.path)
        self.write(msg)
        logging.warn(msg)
        admin_email = util.config_value('Admin Email')
        if not mail.is_email_valid(admin_email):
            return

        url_edit = util.construct_url() + '/admin/node/'
        body = 'Section %s has two nodes named %s ' % (section.path, name)
        mail.send_mail(admin_email, admin_email, 'Duplicate node name in section ' + section.path, body)
def create_sections_for_programs(programs, activities):
    for prog in programs:
        for i in range(programs[prog]['num_sections']):
            section_id = generate_random_uuid()
            section_name = prog + " section " + str(i)
            section = Section(section_id=section_id,
                              name=section_name,
                              description=section_name,
                              overview_image=section_name + ".png")
            add_and_commit(section)

            prog_section_mapping = ProgramSectionMapping(
                mapping_id=generate_random_uuid(),
                program_id=programs[prog]['program_id'],
                section_id=section_id,
                order_index=i + 1)
            add_and_commit(prog_section_mapping)

            for activity_id in activities:
                section_activity_mapping = SectionActivityMapping(
                    mapping_id=generate_random_uuid(),
                    section_id=section_id,
                    activity_id=activity_id)
Ejemplo n.º 51
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        user = self.context['request'].user

        if instance is None:
            instance = Section(classgroup=classgroup,
                               name=alphanumeric_name(name),
                               display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError(
                    "You do not have permission to modify this section.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name
        return instance
Ejemplo n.º 52
0
        hour = int(hour_str[:-2])
        if hour_str[-2:] == "PM" and hour != 12:
            hour += 12

        start_time = pst.localize(
            datetime(year=2021, month=1, day=day, hour=hour, minute=10))
        end_time = start_time + timedelta(minutes=50)

        if email not in users:
            users[email] = User(email=email, name=name, is_staff=True)

        section = Section(
            id=group,
            start_time=start_time.timestamp(),
            end_time=end_time.timestamp(),
            capacity=9,
            staff=users[email],
        )

        if is_npe:
            section.tags = ["NPE"]

        lookup[group] = section

        db.session.add(section)

    for row in student_reader[1:]:
        name, email, time, group, npe = row
        lookup[group].students.append(
            User(email=email, name=name, is_staff=False))
Ejemplo n.º 53
0
    def import_sections(sheet_url):
        index = read_spreadsheet(course="cs61a",
                                 url=sheet_url,
                                 sheet_name="Index")
        header = index[0][:7]
        if header != [
                "ID",
                "Day",
                "Start Time",
                "End Time",
                "Staff Name",
                "Staff Email",
                "Label",
        ]:
            raise Failure("Invalid header for index sheet")
        for (
                id,
                day,
                start_time,
                end_time,
                staff_name,
                staff_email,
                label,
                *args,
        ) in index[1:]:
            day = list(calendar.day_name).index(day)

            start_time = datetime.strptime(start_time, "%I:%M %p")
            start_time = start_time.replace(
                year=datetime.now().year,
                month=datetime.now().month,
                day=datetime.now().day,
            )
            while start_time.weekday() != day:
                start_time += timedelta(days=1)

            end_time = datetime.strptime(end_time, "%I:%M %p")
            end_time = end_time.replace(year=start_time.year,
                                        month=start_time.month,
                                        day=start_time.day)

            pst = pytz.timezone("US/Pacific")
            start_time = pst.localize(start_time).timestamp()
            end_time = pst.localize(end_time).timestamp()

            staff_user = User.query.filter_by(email=staff_email).one_or_none()
            if staff_user is None:
                staff_user = User(email=staff_email,
                                  name=staff_name,
                                  is_staff=True)
                db.session.add(staff_user)
            staff_user.is_staff = True

            sheet: List[List[Union[str, int]]] = read_spreadsheet(
                course="cs61a", url=sheet_url, sheet_name=str(id))
            header = sheet[0]
            email_col = header.index("Email")

            students = [student[email_col] for student in sheet[1:]]
            capacity = len(students) * 2

            section = Section.query.filter_by(id=id).one_or_none()
            if not section:
                section = Section(
                    start_time=start_time,
                    end_time=end_time,
                    capacity=capacity,
                    staff=staff_user,
                    tag_string=label,
                )
                db.session.add(section)

            for student in students:
                user = User.query.filter_by(email=student).one_or_none()
                if not user:
                    user = User(email=student, name=student, is_staff=False)
                    db.session.add(user)
                user.sections = [section]
                user.is_staff = False

            db.session.commit()
        return refresh_state()
Ejemplo n.º 54
0
def sitemap(request):
    context = RequestContext(request)
    context['structure'] = Section.get_structure()
    return render_to_response('sitemap.html', context)
Ejemplo n.º 55
0
    if is_forum_exist:
        print(f' - Skip initialization for forum `{fdata["title"]}`')
        continue

    forum = Forum.create(
        **{
            'title': fdata['title'],
            'created_at': datetime.datetime.now(),
            'created_by': admin.id,
        })

    for section_data in fdata['sections']:
        section = Section.create(
            **{
                'forum': forum.id,
                'title': section_data['title'],
                'created_at': datetime.datetime.now(),
                'created_by': admin.id,
            })

        for subsection_title in section_data['subsections']:
            Section.create(
                **{
                    'forum': forum.id,
                    'parent': section.id,
                    'title': subsection_title,
                    'created_at': datetime.datetime.now(),
                    'created_by': admin.id,
                })

# Create threads
Ejemplo n.º 56
0
Archivo: views.py Proyecto: kpx13/vv
def home(request, cat_name=None, sec_name=None):
    c = get_common_context(request)
    
    if not request.user.is_authenticated():
        if cat_name is None:
            category = Category.get_by_slug('first')
        else:        
            category = Category.get_by_slug(cat_name)
        
        if sec_name is None:
            section = Section.objects.filter(category=category)[0]
        else:
            section = Section.get_by_slug(category, sec_name)
        
        c['title'] = u''
        c['can_request'] = (category.id == 1)
        c['category'] = category
        c['section'] = section
        c['request_url'] = '/'.join(['edu', category.slug, section.slug])
        return render_to_response('section_deny.html', c, context_instance=RequestContext(request))
    
    user = request.user
    profile = user.get_profile()
    have_access = list(profile.have_access())
    
    if cat_name is None:
        if len(have_access) > 0:
            category = have_access[-1]
        else:
            category = Category.get_by_slug('first')
    else:        
        category = Category.get_by_slug(cat_name)
        
    can_access = category in have_access
    
    request_form = RequestForm()
    if request.method == "POST":
        if request.POST['action'] == 'request':
            request_form = RequestForm(request.POST)
            if request_form.is_valid():
                r = request_form.save(commit=False)
                r.profile = profile
                r.category = category
                r.save()
                r.send()
                return HttpResponseRedirect(request.path)
    c['request_form'] = request_form
    
    if sec_name is None:
        section = Section.objects.filter(category=category)[0]
        if 'section' in request.session:
            sections = Section.objects.filter(category=category, id=request.session['section'])
            if sections:
                section = sections[0]
    else:
        section = Section.get_by_slug(category, sec_name)
        request.session['section'] = section.id
        
    c['category'] = category
    c['section'] = section
    c['request_url'] = '/'.join(['edu', category.slug, section.slug])
    if can_access:
        c['title'] = section.name
        return render_to_response('section_allow.html', c, context_instance=RequestContext(request))
    else:
        c['title'] = u''
        c['can_request'] = (category.id == 1) or (category.id == (len(have_access) + 1))
        c['status'] = profile.status(category)
        return render_to_response('section_deny.html', c, context_instance=RequestContext(request))
Ejemplo n.º 57
0
def section_view(section_id):
    section = Section.get(section_id)
    forum = Forum.get(section.forum)
    parent_section = Section.get(section.parent)
    subsections = Section.filter(parent=section.id)

    # Threads
    try:
        page = int(request.args.get('page'))
    except (TypeError, ValueError):
        page = 1

    if not page or page < 1:
        page = 1

    threads_count = len(Thread.filter(section=section.id))
    # FIXME(a.telishev): Threads per page by search
    pages_count = threads_count // THREADS_PER_PAGE

    if page > pages_count:
        page = pages_count

    prev_page = page - 1
    next_page = page + 1
    if page == 1:
        prev_page = None
    if page == pages_count:
        next_page = None

    offset = (page - 1) * THREADS_PER_PAGE

    search = request.args.get('search', '')
    search_condition = f'AND thread.title LIKE "%{search}%"' if search else ''
    query = f"""
        SELECT
            thread.id thread_id,
            thread.title thread_title,
            thread.created_at thread_created_at,
            thread.last_answer_time thread_last_answer_time,
            user.id user_id,
            user.username username
        FROM thread
        INNER JOIN user ON thread.author = user.id
        WHERE section = %(section_id)s {search_condition}
        ORDER BY thread.last_answer_time DESC
        LIMIT %(limit)s
        OFFSET %(offset)s;
    """
    cursor = get_connector().cursor()
    cursor.execute(query, {
        'section_id': section.id,
        'limit': THREADS_PER_PAGE,
        'offset': offset,
    })
    threads = {
        thread_id: {
            'id':
            thread_id,
            'title':
            thread_title,
            'created_at':
            thread_created_at.strftime('%d %b %Y'),
            'created_at_h':
            thread_created_at.strftime('%d %b %Y\n%H:%M:%S'),
            'last_answer_time':
            (thread_last_answer_time.strftime('%d %b %Y\n%H:%M:%S')
             if thread_last_answer_time else None),
            'user_id':
            user_id,
            'username':
            username,
        }
        for (
            thread_id,
            thread_title,
            thread_created_at,
            thread_last_answer_time,
            user_id,
            username,
        ) in cursor
    }

    if threads:
        answers_count_query = f"""
            SELECT
                thread.id,
                COUNT(*)
            FROM thread INNER JOIN answer on thread.id = answer.thread
            WHERE thread.id IN ({
                ', '.join(str(thread_id) for thread_id in threads)
            })
            GROUP BY thread.id;
        """
        cursor.execute(answers_count_query)
        for thread_id, answers_count in cursor:
            threads[thread_id]['answers_count'] = answers_count

    cursor.close()

    return render_template(
        'section.html',
        section=section,
        forum=forum,
        parent_section=parent_section,
        subsections=subsections,
        threads=threads.values(),
        search=search,
        next_page=next_page,
        curr_page=page,
        prev_page=prev_page,
    )
Ejemplo n.º 58
0
    def post(self):
        path = urllib.unquote(self.request.path)
        m = parts.search(path)

        if m is None:
            self.error(404)
            return

        this_path = m.group(1)
        this_page = m.group(3) or 'index'
        this_ext = m.group(4) or 'html'

        # get section and node
        section = Section.all().filter('path =', this_path).get()
        node = Node.all().filter('section =', section).get()

        if section is None or node is None:
            self.error(404)
            return

        self.request.charset = 'utf8'

        # remove the horribleness from comment
        if this_page == 'comment' and this_ext == 'html':
            # firstly, check the 'faux' field and if something is in there, redirect
            faux = self.request.get('faux')
            if len(faux) > 0:
                logging.info('COMMENT: Spam comment detected (Faux field not empty)')
                self.redirect('/')
                return

            # comment submission for each section
            node = Node.get( self.request.get('node') )
            name = self.request.get('name')
            email = self.request.get('email')
            website = self.request.get('website')
            comment_text = re.sub('\r', '', self.request.get('comment'));

            # if there are more than 4 links (https?://) in the comment, we consider it spam
            if spammy_links(comment_text):
                logging.info('COMMENT: Spam comment detected (Too many links)')
                self.redirect('/')
                return

            # now create the comment
            comment = Comment(
                node = node,
                name = name,
                email = email,
                website = website,
                comment = comment_text,
                )
            comment.set_derivatives()
            comment.put()

            # send a mail to the admin
            admin_email = util.config_value('Admin Email')
            if mail.is_email_valid(admin_email):
                url_post = util.construct_url() + node.section.path + node.name + '.html'
                url_mod  = util.construct_url() + '/admin/comment/?key=' + str(comment.key()) + ';status='
                url_del  = util.construct_url() + '/admin/comment/del.html?key='+ str(comment.key())

                body = 'From: ' + name + ' <' + email + '>\n'
                body = body + 'Site: ' + website + '\n\n'
                body = body + comment_text + '\n\n'
                body = body + '*** Actions ***\n\n'
                body = body + 'ViewPost = ' + url_post + '\n\n'
                body = body + 'Approve  = ' + url_mod + 'approve\n'
                body = body + 'Reject   = ' + url_mod + 'reject\n'
                body = body + 'Delete   = ' + url_del + '\n'
                mail.send_mail(admin_email, admin_email, 'New comment on ' + section.path + node.name + '.html', body)
            else:
                # don't do anything
                logging.info('No valid email set, skipping sending admin an email for new comment')

            # redirect to the comment page
            self.redirect('comment.html?key=' + str(comment.key()))
            return

        elif this_page == 'message' and this_ext == 'html':
            # firstly, check the 'faux' field and if something is in there, redirect
            faux = self.request.get('faux')
            if len(faux) > 0:
                logging.info('MESSAGE: Spam detected, not saving')
                self.redirect('/')
                return

            # message submission for each section
            type = self.request.get('type')
            subject = self.request.get('subject')
            message = self.request.POST.items()
            redirect = self.request.get('redirect')

            # create the full URL we should be redirecting to
            full_redirect = util.construct_redirect( redirect )

            # now create the message
            msg = Message(
                type = type,
                subject = subject,
                message = message,
                )
            msg.put()

            # send a mail to the admin
            admin_email = util.config_value('Admin Email')
            if mail.is_email_valid(admin_email):
                body =        'type    : ' + type + '\n'
                body = body + 'subject : ' + subject + '\n'
                for k, v in self.request.POST.items():
                    body = body + k + ' : ' + v + '\n'
                mail.send_mail(admin_email, admin_email, '[' + type + '] ' + subject, body)
            else:
                # don't do anything
                logging.info('No valid email set, skipping sending admin an email for new message')

            self.redirect(full_redirect)
            return
        else:
            # not found
            self.error(404)
            return
Ejemplo n.º 59
0
    def get(self):
        path = urllib.unquote(self.request.path)
        m = parts.search(path)

        if m is None:
            self.error(404)
            return

        this_path = m.group(1)
        this_page = m.group(3) or 'index'
        this_ext = m.group(4) or 'html'

        if this_page is None:
            this_page = 'index'
            this_ext = 'html'

        section = Section.all().filter('path =', this_path).get()
        if section is None:
            self.error(404)
            return

        # if this is an index, call a different template
        if this_page == 'index' and this_ext == 'html':
            # index.html
            vals = {
                'page'    : 'index.html',
                'section' : section,
                }
            self.template(  section.layout + '-index.html', vals, util.config_value('Theme') );

        elif this_page == 'rss20' and this_ext == 'xml':
            # rss20.xml
            nodes = self.latest_nodes(section, 'index-entry', 10)
            vals = {
                'page'    : 'rss20.xml',
                'section' : section,
                'nodes'   : nodes,
                }
            self.response.headers['Content-Type'] = 'application/rss+xml'
            self.template( 'rss20.xml', vals, 'rss' );

        elif this_page == 'sitefeed' and this_ext == 'xml' and section.has('sitefeed'):
            # sitefeed.xml
            nodes = Node.all().filter('attribute =', 'index-entry').order('-inserted').fetch(10)
            vals = {
                'page'    : 'sitefeed.xml',
                'section' : section,
                'nodes'   : nodes,
                }
            self.response.headers['Content-Type'] = 'application/rss+xml'
            self.template( 'rss20.xml', vals, 'rss' );

        elif this_page == 'sitemapindex' and this_ext == 'xml':
            # sitemapindex.xml
            vals = {
                'page'    : 'sitemapindex.xml',
                'sections' : Section.all().filter('attribute =', 'sitemap-entry').order('inserted'),
                }
            self.response.headers['Content-Type'] = 'text/xml'
            self.template( 'sitemapindex.xml', vals, 'sitemaps' );

        elif this_page == 'urlset' and this_ext == 'xml':
            # urlset.xml
            vals = {
                'page'    : 'urlset.xml',
                'section' : section,
                'nodes'   : Node.all().filter('section =', section.key()).filter('attribute =', 'index-entry').order('inserted')
                }
            self.response.headers['Content-Type'] = 'text/xml'
            self.template( 'urlset.xml', vals, 'sitemaps' );

        elif label_page.search(this_page) and this_ext == 'html':
            # path =~ 'label:something.html'
            m = label_page.search(this_page)
            label = m.group(1)
            vals = {
                'page'    : 'label:' + label + '.html',
                'section' : section,
                'nodes'   : Node.all().filter('section =', section.key()).filter('label =', label).order('-inserted'),
                'label'   : label
                }
            self.template( 'label-index.html', vals, util.config_value('Theme') );

        elif archive_page.search(this_page) and this_ext == 'html':
            # path =~ 'archive:2009.html'
            m = archive_page.search(this_page)
            archive = m.group(1)
            vals = {
                'page'    : 'archive:' + archive + '.html',
                'section' : section,
                'nodes'   : Node.all().filter('section =', section.key()).filter('archive =', archive).order('-inserted'),
                'archive' : archive
                }
            self.template( 'archive-index.html', vals, util.config_value('Theme') );

        elif this_page == 'comment' and this_ext == 'html':
            # get the comment if it exists
            try:
                comment = Comment.get( self.request.get('key') )
            except db.BadKeyError:
                self.error(404)
                return

            if comment is None:
                self.error(404)
                return

            vals = {
                'page'    : 'comment.html',
                'section' : section,
                'node'    : comment.node,
                'comment' : comment,
                }
            self.template( 'comment.html', vals, util.config_value('Theme') );

        elif this_ext == 'html':
            # get the node itself
            node_query = Node.all().filter('section =', section.key()).filter('name =', this_page)
            if node_query.count() == 0:
                self.error(404)
                return
            node = node_query.fetch(1)[0]

            # get the approved comments (but only if we know some are there, save a trip to the datastore)
            comments = None
            if node.comment_count:
                comments = Comment.all().filter('node =', node.key()).filter('status =', 'approved').order('inserted')

            vals = {
                'page'     : this_page + '.html',
                'section'  : section,
                'node'     : node,
                'comments' : comments,
                }
            self.template( 'node.html', vals, util.config_value('Theme') );
        else:
            # 404
            self.error(404)
            return
Ejemplo n.º 60
0
def query(section_id):
    query = (Section.select(Section.number, Course.name, Course.title).join(
        Course, on=(Section.course_id == Course.id)).where(
            Section.id == section_id).dicts())

    return query