コード例 #1
0
def school_student(shortname_username):
    if current_user.is_authenticated():
        search_form = SearchForm()
        if search_form.validate_on_submit():
            return redirect(url_for('search', query=search_form.query.data))
        student = finder(shortname_username, 'student', current_user.school)
        incomplete_projects = Project.query.filter_by(student=student,
                                                      complete=False)
        complete_projects = Project.query.filter_by(student=student,
                                                    complete=True)
        rendered_html = render_template(
            'student.html',
            student=student,
            search_form=search_form,
            incomplete_projects=incomplete_projects,
            complete_projects=complete_projects)
        return html_minify(rendered_html)
    school = finder(shortname_username, 'school')
    if len(school.projects.all()) < 3:
        projects = school.projects.all()
    else:
        projects = sample(school.projects.filter_by(complete=False).all(), 3)
    rendered_html = render_template('school.html',
                                    school=school,
                                    projects=projects)
    return html_minify(rendered_html)
コード例 #2
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def index():
    if current_user.is_authenticated():
        search_form = SearchForm()
        if search_form.validate_on_submit():
            return redirect(url_for('search', query=search_form.query.data))
        incoming_requests = []
        for project in Project.query.filter_by(student=current_user, 
                                               complete=False).all():
            for student in project.r_students:
                incoming_requests.append((project, student))
        outgoing_requests = current_user.r_projects.all()
        active_projects = Project.query.filter_by(student=current_user, 
                          complete=False).all() + current_user.j_projects.all()
        explore_projects = Project.query.filter(Project.student!=current_user).\
            filter_by(school=current_user.school, complete=False).\
            order_by(Project.time_posted.desc()).\
            paginate(1, POSTS_PER_PAGE, False)
        if not current_user.description:
            message = Markup("""You haven't added a description yet! 
                             <a href="/settings">Complete your profile.</a>""")
            flash(message)
        rendered_html = render_template('dashboard.html', 
                                        search_form=search_form, 
                                        incoming_requests=incoming_requests,
                                        outgoing_requests=outgoing_requests,
                                        active_projects=active_projects,
                                        explore_projects=explore_projects)
        return html_minify(rendered_html)
    schools = School.query.all()
    rendered_html = render_template('index.html', schools=schools)
    return html_minify(rendered_html)
コード例 #3
0
ファイル: bake.py プロジェクト: symroe/useful_inkleby
    def render_to_file(self,args=None,only_absent=False):
        """
        renders this set of arguments to a files
        """
        if args == None:
            args = []

        file_path = self._get_bake_path(*args)
        
        if only_absent and os.path.isfile(file_path):
            return None
        
        print u"saving {0}".format(file_path)
        directory = os.path.dirname(file_path)
        if os.path.isdir(directory) == False:
            os.makedirs(directory)
        
        request = RequestMock().request()
        
        request.path = "/" + file_path.replace(settings.BAKE_LOCATION,"")
        request.path = request.path.replace("\\","/").replace("index.html","").replace(".html","")

        context = self._get_view_context(request,*args)
        if isinstance(context,HttpResponse):
            html = html_minify(context.content).replace("<html><head></head><body>","").replace("</body></html>","")
        else:
            html = html_minify(self.context_to_html(request,context).content)
        
        with io.open(file_path, "w", encoding="utf-8") as f:
            f.write(html)
コード例 #4
0
def index():
    if current_user.is_authenticated():
        search_form = SearchForm()
        if search_form.validate_on_submit():
            return redirect(url_for('search', query=search_form.query.data))
        incoming_requests = []
        for project in Project.query.filter_by(student=current_user,
                                               complete=False).all():
            for student in project.r_students:
                incoming_requests.append((project, student))
        outgoing_requests = current_user.r_projects.all()
        active_projects = Project.query.filter_by(
            student=current_user,
            complete=False).all() + current_user.j_projects.all()
        explore_projects = Project.query.filter(Project.student!=current_user).\
            filter_by(school=current_user.school, complete=False).\
            order_by(Project.time_posted.desc()).\
            paginate(1, POSTS_PER_PAGE, False)
        if not current_user.description:
            message = Markup("""You haven't added a description yet! 
                             <a href="/settings">Complete your profile.</a>""")
            flash(message)
        rendered_html = render_template('dashboard.html',
                                        search_form=search_form,
                                        incoming_requests=incoming_requests,
                                        outgoing_requests=outgoing_requests,
                                        active_projects=active_projects,
                                        explore_projects=explore_projects)
        return html_minify(rendered_html)
    schools = School.query.all()
    rendered_html = render_template('index.html', schools=schools)
    return html_minify(rendered_html)
コード例 #5
0
ファイル: bake.py プロジェクト: ajparsons/useful_inkleby
    def render_to_file(self, args=None, only_absent=False):
        """
        renders this set of arguments to a files
        """
        if args == None:
            args = []

        file_path = self._get_bake_path(*args)

        if only_absent and os.path.isfile(file_path):
            return None

        print u"saving {0}".format(file_path)
        directory = os.path.dirname(file_path)
        if os.path.isdir(directory) == False:
            os.makedirs(directory)

        request = RequestMock().request()

        request.path = "/" + file_path.replace(settings.BAKE_LOCATION, "")
        request.path = request.path.replace(
            "\\", "/").replace("index.html", "").replace(".html", "")

        context = self._get_view_context(request, *args)
        if isinstance(context, HttpResponse):
            html = html_minify(context.content).replace(
                "<html><head></head><body>", "").replace("</body></html>", "")
        else:
            html = html_minify(self.context_to_html(request, context).content)

        with io.open(file_path, "w", encoding="utf-8") as f:
            f.write(html)
コード例 #6
0
ファイル: commands.py プロジェクト: MechanisM/django-htmlmin
def main():
    parser = argparse.ArgumentParser(description=u'Minify content of HTML files')
    parser.add_argument('filename', metavar='filename', type=str, nargs=1)
    parser.add_argument('--keep-comments', action='store_true')
    args = parser.parse_args()

    content = ""
    with open(os.path.join(my_dir, args.filename[0])) as html_file:
        content = html_file.read()

    print html_minify(content, ignore_comments=not args.keep_comments)
コード例 #7
0
def main():
    parser = argparse.ArgumentParser(
        description=u'Minify content of HTML files', )
    parser.add_argument('filename', metavar='filename', type=str, nargs=1)
    parser.add_argument('--keep-comments', action='store_true')
    args = parser.parse_args()

    content = ""
    with open(os.path.join(my_dir, args.filename[0])) as html_file:
        content = html_file.read()

    print html_minify(content, ignore_comments=not args.keep_comments)
コード例 #8
0
ファイル: views.py プロジェクト: rtgdk/PittQuantumRepository
def contact():
    page = {'id': "page-contact"}

    if request.method == 'GET':
        rendered_html = render_template("contact.html", page=page)
        min_html = html_minify(rendered_html.encode('utf8'))
        return min_html
    else:
        if (validate_contact_us(request.form)):
            send_email(request.form)
            rendered_html = render_template("contact.html", page=page)
            min_html = html_minify(rendered_html.encode('utf8'))
            return min_html
コード例 #9
0
ファイル: app.py プロジェクト: JoaoTimm/MOZEN
def index():
    posts = Post.query.order_by(Post.date_posted.desc()).limit(15).all()
    if current_user.is_authenticated:
        rendered_html = render_template('index.html',
                                        **holders,
                                        posts=posts,
                                        image_file=current_user_image_file(),
                                        input_search_form=search_form())
        return html_minify(rendered_html)
    rendered_html = render_template('index.html',
                                    **holders,
                                    posts=posts,
                                    input_search_form=search_form())
    return html_minify(rendered_html)
コード例 #10
0
ファイル: app.py プロジェクト: Hydrophobefireman/dl-js
def video():
    u = request.args.get("url")
    if u is None:
        return redirect("/", code=302)
    url_obj = URL(u)
    url = str(url_obj)
    data = streamsites.check_for_stream_sites(
        url, request.headers.get("User-Agent"))
    if data:
        return html_minify(
            render_template("multioptions.html",
                            urls=data,
                            url=url,
                            number_=len(data)))
    return html_minify(render_template("video.html", url=url))
コード例 #11
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def signup():
    if current_user.is_authenticated():
        flash('You have already signed up and logged in!')
        return redirect(url_for('index'))
    form = SignupForm()
    if form.validate_on_submit():
        school = \
        School.query.filter_by(email_domain= \
                               form.email.data.split('@')[1]).first()
        username = form.email.data.split('@')[0]
        if username in BLACKLIST:
            flash('GET OUT OF HERE!')
            return redirect(url_for('index'))
        student = Student(name=form.name.data,
                          username=username,
                          email=form.email.data,
                          time_joined=datetime.now(),
                          password=form.password.data,
                          school=school)
        db.session.add(student)
        db.session.commit()
        login_user(student)
        token = student.generate_confirmation_token()
        message = email_creator(student)
        message.set_subject('DevAffair: confirm your account')
        message.set_text("Dear " + student.name + ", \n\n" + "Welcome to " +
            "DevAffair! To confirm your account please click on the following" +
            " link: \n\n" + url_for('confirm', token=token, _external=True) +
            "\n\nSincerely, \n\nThe DevAffair Team")
        status, msg = sg.send(message)
        flash('A confirmation email has been sent to you by email.')
        return redirect(url_for('index'))
    rendered_html = render_template('signup.html', form=form)
    return html_minify(rendered_html)
コード例 #12
0
ファイル: django_tools.py プロジェクト: inkleby/postal_vote
    def render_to_file(self,args=None,only_absent=False):
        """
        renders this set of arguments to a file
        """
        if args == None:
            file_path = os.path.join(settings.BAKE_LOCATION,
                                     self.__class__.bake_path)
            args = []
        else:
            file_path = os.path.join(settings.BAKE_LOCATION,
                                     self.__class__.bake_path.format(*args))
        
        if only_absent and os.path.isfile(file_path):
            return None
        
        print "saving {0}".format(file_path)
        directory = os.path.dirname(file_path)
        if os.path.isdir(directory) == False:
            os.makedirs(directory)
        
        request = RequestMock().request()
        
        request.path = "/" + file_path.replace(settings.BAKE_LOCATION,"").replace("\\","/").replace("index.html","").replace(".html","")

        context = self.view(request,*args)
        html = html_minify(self.context_to_html(request,context).content)
        
        with io.open(file_path, "w", encoding="utf-8") as f:
            f.write(html)
コード例 #13
0
ファイル: run.py プロジェクト: wattools/WatTools
def index():
    dicts = []
    files = sorted(glob.glob("data/*.json"))
    for fname in files:
        with open(fname) as f:
            dicts.append(json.loads(f.read()))
    return html_minify(render_template("index.html", dicts=dicts))
コード例 #14
0
ファイル: fe.py プロジェクト: goors/flask-microblog
def home():

    tag = TagModel()
    post = PostModel()

    t = render_template("home/index.html", tags=tag.tags(), posts=post.posts(True, None))
    return html_minify(unicode(t).encode('utf-8'))
コード例 #15
0
ファイル: test_minify.py プロジェクト: Laksh02/supportkidica
 def test_minify_function_should_return_a_unicode_object(self):
     html = "<html>   <body>some text here</body>    </html>"
     minified = html_minify(html)
     if six.PY2:
         self.assertEqual(unicode, type(minified))
     else:
         self.assertEqual(str, type(minified))
コード例 #16
0
ファイル: views.py プロジェクト: rtgdk/PittQuantumRepository
def fiveohtwo():
    page = {'id': "page-error"}
    rendered_html = render_template("502.html",
                                    page=page,
                                    amount_mol=amount_mol)
    min_html = html_minify(rendered_html.encode('utf8'))
    return min_html
コード例 #17
0
 def rendertemplate(self, template, context):
     rendercontext = {'settings': self.settings, 'content': context}
     if 'include' in context:
         for include in context['include']:
             rendercontext[include['content']] = self.content[
                 include['content']][0:include['count']:include['order']]
     return html_minify(template.render(rendercontext))
コード例 #18
0
    def create(self):
        """
        This method creates a SVG chart.
        :return: (string) contents of the SVG file
        """

        # variables for drawing
        grid = self.__grid_coordinates()
        objs = {
            "grid": grid,
            "labels": self.__txt_coordinates(grid),
            "reference": self.area_coordinates(self.reference, grid),
            "whisky": self.area_coordinates(self.comparison, grid),
            "center_x": self.center_x,
            "center_y": self.center_y,
        }

        # generate the svg
        basedir = app.config["BASEDIR"]
        template = basedir.child("whiskyton", "templates", "chart.svg")
        with open(template, "r") as file_handler:

            # create SVG
            svg_template = Template(file_handler.read())
            return html_minify(svg_template.render(**objs), parser="xml")
コード例 #19
0
    def pages(self, page, **_):
        start = datetime.now()

        request = '/pages/{0}'.format(page)
        self.__logger.debug('pages - request: {0}'.format(request))

        if Options().caching and PageCacher().cached_already(request):
            minified = PageCacher().get_cached(request)

        else:
            remapped = Remapper().remap_url(request)
            self.__logger.debug('pages - remapped: {0}'.format(remapped))

            if request != remapped:
                page = remapped.split('/')[2]
                self.__logger.debug('pages - page: {0}'.format(page))

            # page on the URL: http://www.yoursite.ext/pages/page
            data = DataLoader().pages_data(page)
            data['url'] = remapped

            template = TemplateLoader().get_template('screen_page.html')
            rendered = template.render(data=data)
            minified = html_minify(rendered)

            if Options().caching:
                PageCacher().cache(request, minified)

        finished = datetime.now()
        self.__logger.info('{0} {1}'.format(request, finished - start))

        return minified
コード例 #20
0
 def minify(*args, **kwargs):
     response = f(*args, **kwargs)
     minifiable_status = response.status_code == 200
     minifiable_content = 'text/html' in response['Content-Type']
     if minifiable_status and minifiable_content:
         response.content = html_minify(response.content)
     return response
コード例 #21
0
    def tags(self, tag, page_index=1, **_):
        start = datetime.now()

        request = '/tags/{0}/{1}'.format(tag, page_index)
        self.__logger.debug('tags - tag: {0}'.format(tag))

        if Options().caching and PageCacher().cached_already(request):
            minified = PageCacher().get_cached(request)

        else:
            short_request = 'tags/{0}'.format(tag)
            self.__logger.debug('tags - short_request: {0}'.format(short_request))

            remapped = Remapper().remap_url(short_request)
            self.__logger.debug('tags - remapped: {0}'.format(remapped))

            if short_request != remapped:
                tag = remapped.split('/')[2]
                self.__logger.debug('tags - tag: {0}'.format(tag))

            data = DataLoader().tags_data(tag, page_index)
            data['url'] = remapped

            template = TemplateLoader().get_template('screen_tag.html')
            rendered = template.render(data=data)
            minified = html_minify(rendered)

            if Options().caching:
                PageCacher().cache(request, minified)

        finished = datetime.now()
        self.__logger.info('{0} {1}'.format(request, finished - start))

        return minified
コード例 #22
0
ファイル: test_minify.py プロジェクト: abal09/django-htmlmin
 def test_should_keep_new_line_as_space_when_minifying(self):
     html = '<html><body>Click <a href="#">here</a>\nto see ' +\
            'more</body></html>'
     minified = '<html><head></head><body>Click <a href="#">here</a> to ' +\
                'see more</body></html>'
     got_html = html_minify(html)
     self.assertEqual(minified, got_html)
コード例 #23
0
ファイル: routes.py プロジェクト: rdelarosa3/cambomakeup
def edit(username):
	user = User.query.filter_by(username=username).first_or_404()
	if user != current_user:
		abort(403)
	form = UpdateAccountForm()
	if form.validate_on_submit():
		# if form.picture.data:
		# 	file = form.picture.data
		# if file and allowed_profile_images(file.filename):
		# 	old_filename = user.image_file
		# 	delete_file_from_s3(old_filename)
		# 	file.filename = secure_filename(user.username + "-" + file.filename)
		# 	output = upload_file_to_s3(file)
		# 	current_user.picture_file = file.filename

		current_user.username = form.username.data
		current_user.email = form.email.data
		db.session.commit()
		flash('Account Updated', 'success')
		return redirect(url_for('main.home'))
	elif request.method == 'GET':
		form.username.data = current_user.username
		form.email.data = current_user.email
	# image_file = url_for('static', filename='profile_pics/' + current_user.image_file)
	render_html = render_template('users/edit.html', title='Account', user=current_user,form=form)
	return html_minify(rendered_html)
コード例 #24
0
 def test_should_not_produce_two_spaces_in_new_line(self):
     html = '<html><body>Click <a href="#">here</a> \nto see more' +\
            '</body></html>'
     minified = '<html><head></head><body>Click <a href="#">here' + \
                '</a> to see more</body></html>'
     got_html = html_minify(html)
     self.assertEqual(minified, got_html)
コード例 #25
0
def reset_password():
    if request.method == 'POST':
        user = User.query.filter_by(email=request.form['email']).first()
        if user:
            subject = "Techvaganza 2k16 : Password Reset"

            token = ts.dumps(request.form['email'], salt='reset-key')

            reset_url = url_for('.reset_with_token',
                                token=token,
                                _external=True)

            html = render_template('_snippets/_reset.html',
                                   reset_url=reset_url)

            msg = Message(subject=subject,
                          sender='*****@*****.**',
                          recipients=[request.form['email']],
                          html=html)

            Mail(app).send(msg)
            flash("Password reset email sent, check your mail!")
        else:
            flash("User doesn't exist!")
    return html_minify(render_template('forgot-password.html'))
コード例 #26
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
 def minify(*args, **kwargs):
     response = f(*args, **kwargs)
     minifiable_status = response.status_code == 200
     minifiable_content = 'text/html' in response['Content-Type']
     if minifiable_status and minifiable_content:
         response.content = html_minify(response.content)
     return response
コード例 #27
0
ファイル: views.py プロジェクト: cruzeMc/dreamvents
def getStats():
    idnum = request.args.get('c', type=int)
    event = Event.query.filter_by(id=idnum).first()
    ratings = []
    for i in range(5, 0, -1):
        ratings.append(Rating.query.filter_by(event_id=idnum, rate=i).count())
    comments = []
    sql = text(
        """SELECT count(Comment.id) AS counts,sum(CAST(Comment.percentage AS DECIMAL(9,2))) AS csum FROM Comment WHERE Comment.event_id =:idnums GROUP BY Comment.status"""
    )
    comment_sum = db.engine.execute(sql, idnums=idnum)
    for comment in comment_sum:
        comments.append(
            str(
                json.dumps(
                    round(float(comment['csum']) / comment['counts'] * 100,
                          1))))
    i = 1
    days = []
    visits = []
    hits = Hit.query.with_entities(func.sum(Hit.number).label('sum')).group_by(
        Hit.timestamp).filter(
            Hit.event_id == idnum).order_by("timestamp asc").all()
    for hit in hits:
        visits.append(hit.sum)
        days.append("day" + str(i))
        i += 1
    rendered_html = render_template('event_stats.html',
                                    event=event,
                                    ratings=json.dumps(ratings),
                                    visits=json.dumps(visits),
                                    comments=json.dumps(comments),
                                    days=days)
    return html_minify(rendered_html)
コード例 #28
0
def dialog():
    team = cache.get("team")
    return html_minify(
        render_template("dialog.html",
                        subdomain=team["domain"],
                        users_active=len(cache.get("users_active")),
                        users_total=len(cache.get("users_total"))))
コード例 #29
0
def iframe():
    return html_minify(
        render_template(
            "iframe.html",
            large="slack-btn-large" if "large" in request.args.keys() else "",
            users_active=len(cache.get("users_active")),
            users_total=len(cache.get("users_total"))))
コード例 #30
0
ファイル: views.py プロジェクト: CARocha/acticaire
def sanitize_html(html_table):
    html_table = urllib.unquote(html_table)
    VALID_TAGS = ['table', 'thead', 'tbody', 'th', 'tr', 'td', 'span']
    VALID_ATTRS = ['class', 'rowspan', 'colspan', 'id', 'width']
    
    while True:
        soup = BeautifulSoup(html_table)
        removed = False
            
        for tag in soup.findAll(True): # find all tags
            if tag.name not in VALID_TAGS:
                tag.extract() # remove the bad ones
                removed = True
            else: # it might have bad attributes
                # a better way to get all attributes?
                for attr in tag._getAttrMap().keys():
                    if attr not in VALID_ATTRS:
                        del tag[attr]

        # turn it back to html
        html_table = str(soup)

        if removed:
            # we removed tags and tricky can could exploit that!
            # we need to reparse the html until it stops changing
            continue # next round

        return html_minify(html_table).replace('<!DOCTYPE html>', '') 
コード例 #31
0
def new():
    form = PostForm()
    session['url'] = url_for('blog.new')
    if current_user.is_authenticated:
        if request.method == 'POST':
            content = request.form['body'].replace(
                "<script>", "<strong class="
                'warning'
                ">"
                "<'Scripts tags on source Code are not allowed, "
                "please use the Insert Code Snipped instead'></strong>")
            add_new_post = Post(
                post_image_file=save_picture(form.post_image_file.data),
                title=request.form['title'],
                slug=slugify(request.form['title']),
                body=content,
                # body=string.replace("geeks", "Geeks"),
                tags=request.form['tags'],
                author=current_user)
            db.session.add(add_new_post)
            db.session.commit()
            # flash('Post was successfully added')
            return redirect(url_for('blog.all_posts'))
    else:
        return current_app.login_manager.unauthorized()
    rendered_html = render_template('blog/new.html',
                                    form=form,
                                    image_file=current_user_image_file(),
                                    input_search_form=search_form())
    return html_minify(rendered_html)
コード例 #32
0
def badge_svg():
    users = len(cache.get("users_total"))
    active = len(cache.get("users_active"))

    label = request.args.get("label", "slack")

    if active > 0:
        value = "{}/{}".format(active, users)
    else:
        value = str(users) if users > 0 else "-"

    left_width = 8 + 7 * len(label)
    right_width = 8 + 7 * len(value)

    try:
        templates = {
            "plastic": "badge.svg",
            "flat": "badge_flat.svg",
            "flat-square": "badge_flat-square.svg"
        }
        template = templates[request.args.get("style", "plastic")]
    except KeyError:
        template = "badge.svg"

    svg = html_minify(
        render_template(template,
                        label=label,
                        value=value,
                        left_width=left_width,
                        right_width=right_width))
    svg = svg.replace("<html><head></head><body>", "")
    svg = svg.replace("</body></html>", "")
    response = make_response(svg)
    response.content_type = 'image/svg+xml'
    return response
コード例 #33
0
    def posts(self, post, **_):
        start = datetime.now()

        request = '/posts/{0}'.format(post)
        self.__logger.debug('posts - request: {0}'.format(request))

        if Options().caching and PageCacher().cached_already(request):
            minified = PageCacher().get_cached(request)

        else:
            remapped = Remapper().remap_url(request)
            self.__logger.debug('posts - remapped: {0}'.format(remapped))

            if request != remapped:
                post = remapped.split('/')[2]
                self.__logger.debug('posts - post: {0}'.format(post))

            data = DataLoader().posts_data(post)
            data['url'] = remapped

            template = TemplateLoader().get_template('screen_post.html')
            rendered = template.render(data=data)
            minified = html_minify(rendered)

            if Options().caching:
                PageCacher().cache(request, minified)

        finished = datetime.now()
        self.__logger.info('{0} {1}'.format(request, finished - start))

        return minified
コード例 #34
0
 def process_response(self, request, response):
     minify = getattr(settings, "HTML_MINIFY", not settings.DEBUG)
     keep_comments = getattr(settings, 'KEEP_COMMENTS_ON_MINIFYING', False)
     if minify and self.can_minify_response(request, response):
         response.content = html_minify(response.content,
                                        ignore_comments=not keep_comments)
     return response
コード例 #35
0
def all_posts():
    session['url'] = url_for('blog.all_posts')
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.date_posted.desc()).paginate(
        page=page, per_page=posts_per_page)

    if current_user.is_authenticated:
        rendered_html = render_template('blog/all.html',
                                        posts=posts,
                                        image_file=current_user_image_file(),
                                        input_search_form=search_form())
        return html_minify(rendered_html)
    rendered_html = render_template('blog/all.html',
                                    posts=posts,
                                    input_search_form=search_form())
    return html_minify(rendered_html)
コード例 #36
0
def index():
    team = cache.get("team")
    return html_minify(render_template("index.html",
        subdomain=team["domain"],
        logo=team["icon"]["image_132"],
        users_active=len(cache.get("users_active")),
        users_total=len(cache.get("users_total"))))
コード例 #37
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def new():
    search_form = SearchForm()
    if search_form.validate_on_submit():
        return redirect(url_for('search', query=search_form.query.data))
    project_form = ProjectForm()
    if request.form:
        submit_val = request.form['submit']
        if submit_val == 'Go':
            if search_form.validate_on_submit():
                return redirect(url_for('search', query=search_form.query.data))
        elif submit_val == 'Create':
            if project_form.validate_on_submit():
                project = Project(name=project_form.name.data,
                          website=project_form.website.data,
                          description=project_form.description.data,
                          time_posted=datetime.now(),
                          student=current_user,
                          school=current_user.school)
                db.session.add(project)
                db.session.commit()
                Project.query.get(project.id).hashid = \
                hashids.encode(project.id)
                db.session.commit()
                flash('Project successfully created.')
                return redirect(url_for('project', 
                                student_username=current_user.username,
                                project_hashid=project.hashid))
    rendered_html = render_template('new.html', project_form=project_form, 
                                    search_form=search_form)
    return html_minify(rendered_html)
コード例 #38
0
ファイル: fe.py プロジェクト: goors/flask-microblog
def hometags(tagname=None):

    tag = TagModel()
    post = PostModel()
    tagId = tag.getTagByName(tagname)
    t = render_template("home/index.html", tags=tag.tags(), posts=post.posts(None, tagId))
    return html_minify(unicode(t).encode('utf-8'))
コード例 #39
0
def register():
    errors = None
    if request.method == 'POST':
        validate, errors = RegisterRequest().validate(request.form)
        if validate:
            user = User(password=request.form['password'],
                        name=request.form['name'],
                        email=request.form['email'],
                        cell=request.form['cell'],
                        gender=request.form['gender'],
                        college=request.form['college'],
                        batch=request.form['batch'],
                        branch=request.form['branch'])
            user.email_confirmed = False
            db.session.add(user)
            db.session.commit()

            token = ts.dumps(request.form['email'], salt='email-confirm-key')
            confirm_url = url_for('.confirm_email',
                                  token=token,
                                  _external=True)
            html = render_template('_snippets/_activate.html',
                                   confirm_url=confirm_url)
            msg = Message(subject="Confirm your email",
                          sender='*****@*****.**',
                          recipients=[request.form['email']],
                          html=html)
            Mail(app).send(msg)

            flash(
                'Registration Successful! Please confirm your email within 24 hours.'
            )
            return redirect(url_for('.login'))
    return html_minify(
        render_template('register.html', errors=errors, form=request.form))
コード例 #40
0
def deck(deck_id, search_table=None):

    form = InputForm()
    if form.validate_on_submit():
        search_table, log_0 = process(current_user, form.text.data)
    else:
        log_0 = []
        search_table = None

    bu = Builder(DatabaseConfig)

    deck_table, log_1 = print_user_deck(current_user, deck_id)
    library_table, log_2 = print_user_library(current_user)

    log = log_0 + log_1 + log_2

    return html_minify(
        render_template('deck.html',
                        title='Deck',
                        form="",
                        deck_table=deck_table,
                        library_table=library_table,
                        search_table=search_table,
                        fill="",
                        log=log,
                        db_info=bu.get_db_info()))
コード例 #41
0
ファイル: test_minify.py プロジェクト: abal09/django-htmlmin
 def test_should_not_produce_two_spaces_in_new_line(self):
     html = '<html><body>Click <a href="#">here</a> \nto see more' +\
            '</body></html>'
     minified = '<html><head></head><body>Click <a href="#">here' + \
                '</a> to see more</body></html>'
     got_html = html_minify(html)
     self.assertEqual(minified, got_html)
コード例 #42
0
def library():

    bu = Builder(DatabaseConfig)

    decks = current_user.get_deck_list()

    for deck in decks:
        if not deck['name']:
            deck['name'] = "Deck {}".format(deck['id'])
        if not deck['card_count']:
            deck['card_count'] = 0

    if decks:
        new_id = decks[-1]['id'] + 1
    else:
        new_id = 1
    newdeck = [{
        'id': new_id,
        'name': 'New Deck',
        'card_count': '',
        'info': ''
    }]

    library_table, log = print_user_library(current_user)

    return html_minify(
        render_template('library.html',
                        title='Library',
                        form="",
                        table_of_decks_data=decks + newdeck,
                        library_table=library_table,
                        fill="",
                        log=log,
                        db_info=bu.get_db_info()))
コード例 #43
0
 def test_should_keep_new_line_as_space_when_minifying(self):
     html = '<html><body>Click <a href="#">here</a>\nto see ' +\
            'more</body></html>'
     minified = '<html><head></head><body>Click <a href="#">here</a> to ' +\
                'see more</body></html>'
     got_html = html_minify(html)
     self.assertEqual(minified, got_html)
コード例 #44
0
ファイル: test_minify.py プロジェクト: dugo/django-htmlmin
 def test_minify_function_should_return_a_unicode_object(self):
     html = "<html>   <body>some text here</body>    </html>"
     minified = html_minify(html)
     if six.PY2:
         self.assertEqual(unicode, type(minified))
     else:
         self.assertEqual(str, type(minified))
コード例 #45
0
ファイル: app.py プロジェクト: niruhan/candis
def minify(response):
    if response.content_type == u'text/html; charset=utf-8':
        data     = response.get_data(as_text = True)
        minified = html_minify(data)

        response.set_data(minified)

    return response
コード例 #46
0
ファイル: main.py プロジェクト: PolyLearn/portal
def response_minify(response):
    """
    minify html response to decrease site traffic
    """
    if (response.content_type == u'text/html; charset=utf-8'):
        response.direct_passthrough = False
        response.data = html_minify(response.data)
    return response
コード例 #47
0
ファイル: __init__.py プロジェクト: datallysis/pgadmin4
    def response_minify(response):
        """Minify html response to decrease traffic"""
        if config.MINIFY_HTML and not config.DEBUG:
            if response.content_type == u'text/html; charset=utf-8':
                response.set_data(
                    html_minify(response.get_data(as_text=True))
                )

        return response
コード例 #48
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def empty_search():
    search_form = SearchForm()
    if search_form.validate_on_submit():
        return redirect(url_for('search', query=search_form.query.data))
    rendered_html = render_template('search.html', query=None, 
                                    student_results=None,
                                    project_results=None,
                                    search_form = SearchForm())
    return html_minify(rendered_html)
コード例 #49
0
ファイル: sitegen.py プロジェクト: jjsandee/jjstatic
 def rendertemplate(self, template, context):
     rendercontext = {
                 'settings': self.settings,
                 'content': context
             }
     if 'include' in context:
         for include in context['include']:
             rendercontext[include['content']] = self.content[include['content']][0:include['count']:include['order']]
     return html_minify(template.render(rendercontext))
コード例 #50
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def settings():
    search_form = SearchForm()
    profile_form = StudentForm(obj=current_user)
    password_form = PasswordForm()
    delete_form = DeleteForm()
    if request.form:
        submit_val = request.form['submit']
        if submit_val == 'Go':
            if search_form.validate_on_submit():
                return redirect(url_for('search', query=search_form.query.data))
            else:
                profile_form.name.data = current_user.name
                profile_form.website.data = current_user.website
                profile_form.description.data = current_user.description
        elif submit_val == 'Update profile':
            if profile_form.validate_on_submit():
                current_user.name = profile_form.name.data
                current_user.website = profile_form.website.data
                current_user.description = profile_form.description.data
                db.session.commit()
                flash('Profile successfully updated.')
        elif submit_val == 'Change password':
            if password_form.validate_on_submit():
                current_user.password = password_form.new_password.data
                db.session.commit()
                flash('Password successfully updated.')
            profile_form.name.data = current_user.name
            profile_form.website.data = current_user.website
            profile_form.description.data = current_user.description
        elif submit_val == 'Delete account':
            if delete_form.validate_on_submit():
                deadman = finder(current_user.username, 'student', 
                                 current_user.school)
                for project in deadman.projects:
                    db.session.delete(project)
                logout_user()
                db.session.delete(deadman)
                db.session.commit()
                message = email_creator(deadman)
                message.set_subject('DevAffair: account deleted')
                message.set_text("Dear " + deadman.name + ", \n\nYour account" + 
                    " at DevAffair has been deleted!\n\nSincerely, \n\nThe " +
                    "DevAffair Team")
                status, msg = sg.send(message)
                flash('Account successfully deleted.')
                return redirect(url_for('index'))
            else:
                profile_form.name.data = current_user.name
                profile_form.website.data = current_user.website
                profile_form.description.data = current_user.description   
    rendered_html = render_template('settings.html', 
                                    profile_form=profile_form, 
                                    password_form=password_form, 
                                    delete_form=delete_form,
                                    search_form=search_form)
    return html_minify(rendered_html)        
コード例 #51
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def reset(token):
    form = ResetForm()
    if form.validate_on_submit():
        student = Student.query.filter_by(email=form.email.data).first()
        if student.reset_password(token, form.new_password.data):
            flash('Password successfully updated.')
            return redirect(url_for('login'))
        flash('The password reset link is invalid or has expired.')
    rendered_html = render_template('reset.html', form=form)
    return html_minify(rendered_html)
コード例 #52
0
 def testPie(self):
     pieChart = Pie('Participant Origin', self.pieData)
     html = ChartMaker.makeWebPage(pieChart)
     #print(html)
     htmlNoCR = re.sub('\n','',html)
     htmlMinimized = html_minify(htmlNoCR)
     #print(htmlMinimized)
     with open('data/testPieGroundTruth.txt', 'r') as fd:
         groundTruth = fd.read()
     self.assertEqual(self.removeLocalPart(groundTruth.strip()), self.removeLocalPart(htmlMinimized.strip()))
コード例 #53
0
 def testLine(self):
     lineChart = Line('Percent Finishing to Certificate', self.xAxisLabels, 'Completion (%)', self.lineData)
     html = ChartMaker.makeWebPage(lineChart)
     #print(html)
     htmlNoCR = re.sub('\n','',html)
     htmlMinimized = html_minify(htmlNoCR)
     print(htmlMinimized)
     with open('data/testLineGroundTruth.txt', 'r') as fd:
         groundTruth = fd.read()
     self.assertEqual(self.removeLocalPart(groundTruth.strip()), self.removeLocalPart(htmlMinimized.strip()))
コード例 #54
0
 def process_response(self, request, response):
     minify = getattr(settings, "HTML_MINIFY", not settings.DEBUG)
     keep_comments = getattr(settings, 'KEEP_COMMENTS_ON_MINIFYING', False)
     parser = getattr(settings, 'HTML_MIN_PARSER', 'html5lib')
     if minify and self.can_minify_response(request, response):
         response.content = html_minify(response.content,
                                        ignore_comments=not keep_comments,
                                        parser=parser)
         response['Content-Length'] = len(response.content)
     return response
コード例 #55
0
ファイル: dontpanic.py プロジェクト: MrMattSim/DontPanic
def show_articles():
    cur = g.db.execute(
        'select title, slug, published from articles order by published')
    articles = [
        dict(title=row[0],
             slug=row[1],
             published=row[2].strftime('%d %B, %Y')) for row in cur.fetchall()]
    return html_minify(
        render_template(
            'blog.html', articles=articles, page_title='Blog | ', year=YEAR))
コード例 #56
0
ファイル: sitebuilder.py プロジェクト: gatesphere/blog-new
def tags():
  tags = {}
  for page in pages:
    ts = page.meta.get('tags',None)
    if ts is not None and len(ts) > 0:
      for tag in ts:
        val = tags.get(tag, 0)
        val += 1
        tags[tag] = val
  return html_minify(render_template('tags.html', tags=tags))
コード例 #57
0
ファイル: fe.py プロジェクト: goors/flask-microblog
def read(slug=None):

    from models import db
    tag = TagModel()
    post = PostModel()
    comment = CommentModel()
    id = post.post(slug)

    id.NoOfViews += 1
    db.session.commit()

    postFiles = post.getPostFiles(id.Id)

    if request.method == "POST":

        if 'comment' in request.form and 'cid' not in request.form:

            comment.addcomment(request.form['comment'], request.form['email'], request.form['nick'], id.Id)

        if 'comment' in request.form and 'cid' in request.form:

            comment.addcomment(request.form['comment'], request.form['email'], request.form['nick'], id.Id, request.form['cid'])

            ##send reply to if any email address defined
            c = comment.getCommentEmail(request.form['cid'])
            if c.Email:
                from UserModel import UserModel
                u = UserModel()
                u.send_email(request.form['nick'] + " just commented on post "+id.Title, c.Email, request.form['comment']+ "<p>"+URL_FE+"read/"+id.Slug+"</p>", c.Nick)

        if 'password' in request.form:

            from werkzeug import check_password_hash

            if check_password_hash(id.Password, request.form['password']):
                t = render_template("home/read.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles)
                return html_minify(unicode(t).encode('utf-8'))

    if id.Password != 'NULL':
        t = render_template("home/read-with-password.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles)
    else:
        t = render_template("home/read.html", tags=tag.tags(), post=post.post(slug), comments = comment.comments(id), postFiles=postFiles)
    return html_minify(unicode(t).encode('utf-8'))
コード例 #58
0
ファイル: app.py プロジェクト: nikrdc/DevAffair
def project(student_username, project_hashid):
    student =  finder(student_username, 'student', current_user.school)
    project = finder(hashids.decode(project_hashid), 'project')
    if project.student is student:
        search_form = SearchForm()
        if search_form.validate_on_submit():
            return redirect(url_for('search', query=search_form.query.data))
        rendered_html = render_template('project.html', project=project,
                                        search_form=search_form)
        return html_minify(rendered_html)
    abort(404)
コード例 #59
0
ファイル: simplifier.py プロジェクト: vfazel/greylock2
def simplify(html):
    soup = BeautifulSoup(html, 'html.parser')
    [s.extract() for s in soup('script')]
    [s.extract() for s in soup('link')]
    [s.extract() for s in soup('img')]

    soup.head.append(soup.new_tag("link", rel="stylesheet", type="text/css", href="/static/style.css"))
    soup.head.append(soup.new_tag("script", src="/static/custom.js"))

    minhtml = html_minify(str(soup))
    return minhtml