flask.render_template

Here are the examples of the python api flask.render_template taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

183 Examples 7

Example 1

Project: bepasty-server Source File: app.py
Function: create_app
def create_app():
    app = Flask(__name__)

    app.config.from_object('bepasty.config.Config')
    if os.environ.get('BEPASTY_CONFIG'):
        app.config.from_envvar('BEPASTY_CONFIG')

    app.storage = create_storage(app)
    setup_werkzeug_routing(app)

    app.register_blueprint(blueprint)
    app.register_blueprint(blueprint_apis)

    @app.errorhandler(403)
    def url_forbidden(e):
        heading = 'Forbidden'
        body = Markup("""\
            <p>
                You are not allowed to access the requested URL.
            </p>
            <p>
                If you entered the URL manually please check your spelling and try again.
            </p>
            <p>
                Also check if you maybe forgot to log in or if your permissions are insufficient for this.
            </p>
""")
        return render_template('error.html', heading=heading, body=body), 403

    @app.errorhandler(404)
    def url_not_found(e):
        heading = 'Not found'
        body = Markup("""\
            <p>
                The requested URL was not found on the server.
            </p>
            <p>
                If you entered the URL manually please check your spelling and try again.
            </p>
""")
        return render_template('error.html', heading=heading, body=body), 404

    @app.before_request
    def before_request():
        """
        before the request is handled (by its view function), we compute some
        stuff here and make it easily available.
        """
        flaskg.logged_in = logged_in()
        flaskg.permissions = get_permissions()
        flaskg.icon_permissions = get_permission_icons()
        if flaskg.logged_in:
            session.permanent = current_app.config['PERMANENT_SESSION']

    def datetime_format(ts):
        """
        takes a unix timestamp and outputs a iso8601-like formatted string.
        times are always UTC, but we don't include the TZ here for brevity.
        it should be made clear (e.g. in the template) that the date/time is UTC.
        """
        if not ts:  # we use 0 to indicate undefined time
            return 'undefined'
        return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(ts))

    app.jinja_env.filters['datetime'] = datetime_format

    app.jinja_env.globals['flaskg'] = flaskg
    app.jinja_env.globals['may'] = may
    app.jinja_env.globals['ADMIN'] = ADMIN
    app.jinja_env.globals['LIST'] = LIST
    app.jinja_env.globals['CREATE'] = CREATE
    app.jinja_env.globals['READ'] = READ
    app.jinja_env.globals['DELETE'] = DELETE

    return app

Example 2

Project: zipnish Source File: views.py
Function: traces
@traces.route('/<hex_trace_id>', methods=['GET'])
def traces(hex_trace_id):
    # hex trace_id converted to long
    traceId = str(ParseTraceURLId(hex_trace_id))

    # get database engine connection
    connection = db.engine.connect()

    # find trace information
    query = "SELECT *  \
            FROM zipnish_annotations \
            WHERE \
            trace_id = %s \
            ORDER BY a_timestamp ASC, service_name ASC" \
            % str(traceId)
    resultAnnotations = connection.execute(query)

    minTimestamp = sys.maxint
    maxTimestamp = 0

    span_ids = []
    service_names = []

    spans = {}

    for row in resultAnnotations:
        span_id = row['span_id']
        trace_id = row['trace_id']
        span_name = row['span_name']
        service_name = row['service_name']
        value = row['value']
        ipv4 = row['ipv4']
        port = row['port']
        a_timestamp = row['a_timestamp']

        minTimestamp = min(a_timestamp, minTimestamp)
        maxTimestamp = max(a_timestamp, maxTimestamp)

        if span_id not in span_ids:
            span_ids.append(span_id)
            spans[span_id] = {}

        if service_name not in service_names:
            service_names.append(service_name)

        spans[span_id]['spanId'] = span_id
        spans[span_id]['serviceName'] = service_name
        spans[span_id]['spanName'] = span_name

    totalDuration = (maxTimestamp - minTimestamp) / 1000
    totalSpans = len(span_ids)
    totalServices = len(service_names)

    #return str(spans)

    # find depth information
    query = "SELECT DISTINCT span_id, parent_id \
            FROM zipnish_spans \
            WHERE trace_id = %s" % traceId
    depthResults = connection.execute(query)

    depthRows = {}
    for row in depthResults:
        depthRows[row['span_id']] = row['parent_id']

    totalDepth = findTraceDepth(depthRows)

    # fetch all annotations related to this trace
    query = "SELECT span_id, span_name, service_name, \
            value, ipv4, port, a_timestamp \
            FROM `zipnish_annotations` \
            WHERE trace_id = %s" % traceId
    allAnnotations = connection.execute(query)

    annotations = []
    for row in allAnnotations:
        annotations.append( row )

    # generate time markers
    timeMarkers = generateTraceTimeMarkers(totalDuration)

    return render_template('trace.html', \
            spanParentDict=depthRows,
            annotations=annotations,
            totalDuration=totalDuration, \
            totalSpans=totalSpans, \
            totalServices=totalServices, \
            totalDepth=totalDepth, \
            timeMarkers=timeMarkers, \
            spans=spans)

Example 3

Project: ldapass Source File: ldapass.py
@app.route('/reset/<link_id>', methods=['GET', 'POST'])
def reset(link_id):
    error = None
    form = PasswordForm(request.form)

    db_conn = sqlite3.connect(conf.get('app', 'database'))
    db_curs = db_conn.cursor()
    db_curs.execute("SELECT * FROM mails WHERE link_id='{link_id}'".format(
        link_id=link_id))
    db_data = db_curs.fetchall()

    if len(db_data) == 1:
        if request.method == 'GET':
            flash(
                'You are changing password for the account of {mail}'.format(
                    mail=db_data[0][1]))
            return render_template(
                'reset.html',
                error=error,
                form=form,
                link_id=link_id)

        if request.method == 'POST':
            if form.validate():
                ldap_uri = 'ldap://{addr}:{port}'.format(
                    addr=conf.get('ldap', 'addr'),
                    port=conf.get('ldap', 'port')
                )
                try:
                    ldap.set_option(
                        ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                    l = ldap.initialize(
                        ldap_uri, trace_level=conf.get('app', 'ldap_debug'))
                    l.start_tls_s()
                except ldap.LDAPError as error:
                    return render_template('error.html', error=error)
                try:
                    search_filter = 'mail={mail}'.format(mail=db_data[0][1])
                    ldap_result_id = l.search(
                        conf.get('ldap', 'basedn'),
                        ldap.SCOPE_SUBTREE,
                        search_filter,
                        None)
                    result_type, result_data = l.result(ldap_result_id, 0)
                    l.simple_bind_s(
                        conf.get('ldap', 'user'), conf.get('ldap', 'pass'))
                    l.passwd_s(
                        'uid={uid},{basedn}'.format(
                            uid=result_data[0][1]['uid'][0],
                            basedn=conf.get('ldap', 'basedn')),
                        None,
                        '{passwd}'.format(passwd=form.passwd.data))
                except ldap.LDAPError as error:
                    error = 'LDAP error: {error}, please get in touch with \
                        LDAP administration.'.format(error=error)
                    return render_template(
                        'reset.html',
                        error=error,
                        form=form
                    )
                flash('Password for account {mail} has been changed.'.format(
                    mail=db_data[0][1]))
                db_curs.execute(
                    "DELETE FROM mails WHERE link_id='{link_id}'".format(
                        link_id=link_id))
                db_conn.commit()
                db_conn.close()
                return redirect(url_for('index'))
            else:
                error = 'The form is invalid, please try again.'
                return render_template('reset.html', error=error, form=form)
    else:
        db_conn.close()
        error = 'There is no such password reset id {link_id}'.format(
            link_id=link_id)
        return render_template('error.html', error=error)

Example 4

Project: nbdiff Source File: MergeURLCommand.py
    def process(self, request, filename, db_session):
        errMsg = ""
        parser = NotebookParser()
        # Max Size of a notebook accepted is 20M.
        max_size = 20*1024*1024

        try:
            localURL = request.form['localURL']
            baseURL = request.form['baseURL']
            remoteURL = request.form['remoteURL']
        except BadRequestKeyError:
            errMsg = """Invalid notebook Merge Request.
                <br/>Please return to the home page and
                submit the request again."""
            return render_template('Error.html', err=errMsg)

        try:
            localFile = urllib2.urlopen(localURL)
            if int(localFile.info()['Content-Length']) > max_size:
                errMsg = errMsg + """The Local notebook
                    exceeds 20MB. Only notebooks below
                    20MB are accepted.<br/>"""
        except:
            errMsg = errMsg + """We are unable to access
                the Local notebook file from the
                given URL.<br/>"""

        try:
            baseFile = urllib2.urlopen(baseURL)
            if int(baseFile.info()['Content-Length']) > max_size:
                errMsg = errMsg + """The Base notebook
                    exceeds 20MB. Only notebooks below
                    20MB are accepted.<br/>"""
        except:
            errMsg = errMsg + """We are unable to access
                the Base notebook file from the given
                URL.<br/>"""

        try:
            remoteFile = urllib2.urlopen(remoteURL)
            if int(remoteFile.info()['Content-Length']) > max_size:
                errMsg = errMsg + """The Remote notebook
                    exceeds 20MB. Only notebooks below
                    20MB are accepted.<br/>"""
        except:
            errMsg = errMsg + """We are unable to access
                the Remote notebook file from
                the given URL.<br/>"""

        if len(errMsg) == 0:
            try:
                nb_local = parser.parse(localFile)
            except nbformat.NotJSONError:
                errMsg = errMsg + """The Local notebook
                    contains invalid JSON data. <br/>"""
            try:
                nb_base = parser.parse(baseFile)
            except nbformat.NotJSONError:
                errMsg = errMsg + """The Base notebook
                    contains invalid JSON data. <br/>"""
            try:
                nb_remote = parser.parse(remoteFile)
            except nbformat.NotJSONError:
                errMsg = errMsg + """The Remote notebook
                    contains invalid JSON data. <br/>"""

            localFile.close()
            baseFile.close()
            remoteFile.close()

        if len(errMsg) == 0:
            mergedNotebook = notebook_merge(nb_local, nb_base, nb_remote)

            # bitarray used to convert notebook to binary for BLOB
            ba = bitarray.bitarray()
            ba.fromstring(json.dumps(mergedNotebook, indent=2))

            # object to be saved to database
            obj = nbdiffModel(ba.to01())

            # add to database and commit it.
            try:
                db_session.add(obj)
                db_session.commit()
            except OperationalError:
                db_session.rollback()
                print """The database is not initialized.
                    Please restart server with argument init_db"""
                errMsg = """There was an error with the database. <br/>
                   Please contact administrator to resolve this issue."""
                return render_template('Error.html', err=errMsg)
            except:
                db_session.rollback()
                errMsg = """There was an unexpected error with the database.
                    <br/>Please try again later. <br/>
                    If this problem persists please contact administrator."""
                return render_template('Error.html', err=errMsg)

            # return the id of the object.
            nb_id = obj.id

            # redirect is used because we want users
            # to have a easier url to return to.
            return redirect("/Comparison/"+str(nb_id), code=302)
        else:
            return render_template('Error.html', err=errMsg)

Example 5

Project: utter-va Source File: configurehandlers.py
@mod.route('/configure', methods=['GET', 'POST'])
@login_required
def configure():
	# get the form for the page
	form = ApplianceForm(request.form)

	# get existing database entries
	appliance = db.session.query(Appliance).first()

	# page is POST'ing data
	if request.method == 'POST':
		# clear settings cache
		Status().flush()
	
		# load the form into the appliance object (excluding API token)
		apitoken = appliance.apitoken
		form.populate_obj(appliance)
		appliance.apitoken = apitoken
		
		if form.validate_on_submit():
			# our form validates, so update the database
			appliance.update(appliance)

			# check the settings
			settings = Status().check_settings()

			if settings['coinbase']:				
				# sync up addresses with coinbase
				addresses = Addresses()
				addresses.sync(appliance)

				# grab the first address we got from coinbase
				address = db.session.query(Addresses).first()
				
				if address and address.subdomain:
					# overload the appliance's existing subdomain with one from coinbase address
					appliance.subdomain = address.subdomain
					appliance.update()
				else:
					# there exists no address with a subdomain, so we generate a new one
					appliance.subdomain = generate_token(size=16, caselimit=True)
					appliance.update()

				# build the tunnel config file - ngrok will start after it's built
				appliance.build_tunnel_conf()

				# not ideal, but whatever
				os.system('monit restart ngrok')

			# form was valid, so say thanks	
			flash("Setting have been saved.", "success")

		else:
			# form was not valid, so show errors	
			flash("There were form errors. Please check your entries and try again.", "error")
		
	# populate map
	try:
		lat = float(appliance.latitude)
		lon = float(appliance.longitude)
	except ValueError, TypeError:
		geodata = get_geodata()
		appliance.latitude = geodata['latitude']
		appliance.longitude = geodata['longitude']
		appliance.update()

	# check configuration
	settings = Status().check_settings()

	if settings['token'] == False:
		flash("Please register the API token.", "error")
	
	if settings['coinbase'] == False:
		flash("Please enter valid Coinbase credentials.", "error")

	if settings['ngrok'] == 0:
		flash("Please enter a valid Ngrok token.", "error")
	elif settings['ngrok'] == -1:
		flash("The Ngrok tunnel is not running.", "error")
		
	# return the template
	return render_template(
		'configure/appliance.html', 
		settings=settings, 
		form=form, 
		appliance=appliance
	)

Example 6

Project: sagenb Source File: base.py
def create_app(path_to_notebook, *args, **kwds):
    """
    This is the main method to create a running notebook. This is
    called from the process spawned in run_notebook.py
    """
    global notebook
    startup_token = kwds.pop('startup_token', None)

    #############
    # OLD STUFF #
    #############
    import sagenb.notebook.notebook as notebook
    notebook.MATHJAX = True
    notebook = notebook.load_notebook(path_to_notebook, *args, **kwds)
    init_updates()

    ##############
    # Create app #
    ##############
    app = SageNBFlask('flask_version', startup_token=startup_token,
                      template_folder=TEMPLATE_PATH)
    app.secret_key = os.urandom(24)
    oid.init_app(app)
    app.debug = True

    @app.before_request
    def set_notebook_object():
        g.notebook = notebook

    ####################################
    # create Babel translation manager #
    ####################################
    babel = Babel(app, default_locale='en_US')

    #Check if saved default language exists. If not fallback to default
    @app.before_first_request
    def check_default_lang():
        def_lang = notebook.conf()['default_language']
        trans_ids = [str(trans) for trans in babel.list_translations()]
        if def_lang not in trans_ids:
            notebook.conf()['default_language'] = None

    #register callback function for locale selection
    #this function must be modified to add per user language support
    @babel.localeselector
    def get_locale():
        return g.notebook.conf()['default_language']

    ########################
    # Register the modules #
    ########################
    app.register_blueprint(base)

    from .worksheet_listing import worksheet_listing
    app.register_blueprint(worksheet_listing)

    from .admin import admin
    app.register_blueprint(admin)

    from .authentication import authentication
    app.register_blueprint(authentication)

    from .doc import doc
    app.register_blueprint(doc)

    from .worksheet import ws as worksheet
    app.register_blueprint(worksheet)

    from .settings import settings
    app.register_blueprint(settings)

    # Handles all uncaught exceptions by sending an e-mail to the
    # administrator(s) and displaying an error page.
    @app.errorhandler(Exception)
    def log_exception(error):
        from sagenb.notebook.notification import logger
        logger.exception(error)
        return app.message(
            gettext('''500: Internal server error.'''),
            username=getattr(g, 'username', 'guest')), 500

    #autoindex v0.3 doesnt seem to work with modules
    #routing with app directly does the trick
    #TODO: Check to see if autoindex 0.4 works with modules
    idx = AutoIndex(app, browse_root=SRC, add_url_rules=False)
    @app.route('/src/')
    @app.route('/src/<path:path>')
    @guest_or_login_required
    def autoindex(path='.'):
        filename = os.path.join(SRC, path)
        if os.path.isfile(filename):
            from cgi import escape
            src = escape(open(filename).read().decode('utf-8','ignore'))
            if (os.path.splitext(filename)[1] in
                ['.py','.c','.cc','.h','.hh','.pyx','.pxd']):
                return render_template(os.path.join('html', 'source_code.html'),
                                       src_filename=path,
                                       src=src, username = g.username)
            return src
        return idx.render_autoindex(path)

    return app

Example 7

Project: galah Source File: _view_snapshot.py
@app.route("/assignments/<assignment_id>/snapshot/<student_email>")
@account_type_required(("teacher", "teaching_assistant"))
def view_snapshot(assignment_id, student_email):
    simple_archive_form = SimpleArchiveForm()

    # Convert the assignment in the URL into an ObjectId
    try:
        id = ObjectId(assignment_id)
    except InvalidId:
        logger.info("Invalid Assignment ID requested.")

        abort(404)

    # Retrieve the assignment
    try:
        assignment = Assignment.objects.get(id = id)
        deadline = current_user.personal_deadline
        if str(assignment_id) in deadline:
            assignment.due_cutoff = deadline[str(assignment_id)]
    except Assignment.DoesNotExist:
        logger.info("Non-extant ID requested.")

        abort(404)

    # Retrieve the student
    try:
        student = User.objects.get(email = student_email)
    except User.DoesNotExist:
        logger.info("Non-extant Student ID requested.")

    # Get all of the submissions for this assignment
    submissions = list(
        Submission.objects(
            user = student.id,
            assignment = id
        ).order_by(
            "-most_recent",
            "-timestamp"
        )
    )

    test_results = list(
        TestResult.objects(
            id__in = [i.test_results for i in submissions if i.test_results]
        )
    )

    # Match test results to submissions
    for i in submissions:
        for j in test_results:
            if i.test_results == j.id:
                i.test_results_obj = j

    # Current time to be compared to submission test_request_timestamp
    now = datetime.datetime.now()

    # Flag to set refresh trigger if user is waiting on test results
    wait_and_refresh = False

    # Add the pretty version of each submissions timestamp
    for i in submissions:
        i.timestamp_pretty = pretty_time(i.timestamp)
        i.status = "Submitted"

        # If the user submitted a test request and there aren't any results
        if (i.test_request_timestamp and not i.test_results):
            timedelta = now - i.test_request_timestamp
            i.show_resubmit = (timedelta > config["STUDENT_RETRY_INTERVAL"])
            if not i.show_resubmit:
                i.status = "Waiting for test results..." 
            else:
                i.status = "Test request timed out"
        elif (i.test_results and i.test_results_obj.failed):
            i.status = "Tests Failed"
            i.show_resubmit = True
        elif (i.test_results and not i.test_results_obj.failed):
            i.status = "Tests Completed"

    wait_and_refresh = \
        any(i.status == "Waiting for test results..." for i in submissions)

    return render_template(
        "assignment.html",
        now = datetime.datetime.today(),
        create_time_element = create_time_element,
        assignment = assignment,
        submissions = submissions,
        simple_archive_form = simple_archive_form,
        wait_and_refresh = wait_and_refresh,
        new_submissions = [v for k, v in get_flashed_messages(with_categories = True) if k == "new_submission"],
        view_snapshot = True,
        student = student,
        enumerate = enumerate
    )

Example 8

Project: rootio_web Source File: views.py
@user.route('/profile', methods=['GET', 'POST'], defaults={'user_id': None})
@user.route('/profile/<int:user_id>/edit', methods=['GET', 'POST'])
@login_required
def profile(user_id):
    if user_id:
        edit = True
        user = User.query.get(user_id)
    else:
        edit = False
        user = User.query.filter_by(name=current_user.name).first_or_404()
    if not user.user_detail:
        user.user_detail = UserDetail()
    form = ProfileForm(obj=user.user_detail,
                       email=user.email,
                       name=user.name,
                       networks=user.networks,
                       role_code=user.role_code,
                       status_code=user.status_code,
                       next=request.args.get('next'))
    form.set_edit(edit)
    if form.validate_on_submit():

        if form.avatar_file.data:
            upload_file = request.files[form.avatar_file.name]
            if upload_file and allowed_file(upload_file.filename):
                # Don't trust any input, we use a random string as filename.
                # or use secure_filename:
                # http://flask.pocoo.org/docs/patterns/fileuploads/

                user_upload_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], "user_%s" % user.id)
                current_app.logger.debug(user_upload_dir)

                make_dir(user_upload_dir)
                root, ext = os.path.splitext(upload_file.filename)
                today = datetime.now().strftime('_%Y-%m-%d')
                # Hash file content as filename.
                hash_filename = hashlib.sha1(upload_file.read()).hexdigest() + "_" + today + ext
                user.avatar = hash_filename

                avatar_ab_path = os.path.join(user_upload_dir, user.avatar)
                # Reset file curso since we used read()
                upload_file.seek(0)
                upload_file.save(avatar_ab_path)

        form.populate_obj(user)
        form.populate_obj(user.user_detail)
        form.populate_obj(user.networks)
        

        db.session.add(user)
        db.session.commit()

        flash(form.data, 'success')

    return render_template('user/profile.html', user=user,
                           active="profile", form=form, edit=edit)

Example 9

Project: viaduct Source File: domjudge.py
@blueprint.route('/contest/<int:contest_id>/problem/<int:problem_id>/submit/',
                 methods=['GET', 'POST'])
@login_required
def contest_problem_submit(contest_id, problem_id):
    r = DOMjudgeAPI.request_get('api/languages')
    if not r:
        return render_template('domjudge/problem/submit.htm',
                               contest_id=contest_id)

    languages = r.json()

    r = DOMjudgeAPI.request_get('api/contests')
    if not r:
        return render_template('domjudge/problem/submit.htm',
                               contest_id=contest_id)

    if str(contest_id) not in r.json():
        flash(_("Contest does not exist."), 'danger')
        return redirect(url_for('domjudge.contest_list'))

    contest = r.json()[str(contest_id)]
    contest['start'] = dt.datetime.fromtimestamp(contest['start']) \
        .strftime(DT_FORMAT)
    contest['end'] = dt.datetime.fromtimestamp(contest['end']) \
        .strftime(DT_FORMAT)

    r = DOMjudgeAPI.request_get('api/problems?cid={}'.format(contest_id))
    if not r:
        return render_template('domjudge/problem/submit.htm',
                               contest_id=contest_id)

    problem = None
    for p in r.json():
        if p['id'] == problem_id:
            problem = p
            break

    if not problem:
        flash(_('Problem does not exist.'), 'danger')
        return redirect(url_for('domjudge.contest_problems_list',
                                contest_id=contest_id))

    if request.method == 'POST':
        file = request.files.get('file', None)
        language = request.form.get('language', None)

        error = False
        if not file or file.filename == '':
            flash(_('No file uploaded.'), 'danger')
            error = True

        if not language:
            flash(_('Invalid language.'), 'danger')
            error = True
        else:
            valid = False
            for lang in languages:
                if lang['id'] == language:
                    valid = True
                    break

            if not valid:
                flash(_('Invalid language.'), 'danger')
                error = True

        if error:
            return render_template('domjudge/problem/submit.htm',
                                   problem=problem,
                                   contest=contest,
                                   contest_id=contest_id,
                                   languages=languages)

        dom_username = "via_user_{}".format(current_user.id)
        dom_teamname = 'via_user_team_{}'.format(current_user.id)
        dom_password = current_user.password
        session = DOMjudgeAPI.login(dom_username, dom_password,
                                    flash_on_error=False)

        # Check if user exists
        if not session:
            # User does not exist
            session = DOMjudgeAPI.login(DOMJUDGE_ADMIN_USERNAME,
                                        DOMJUDGE_ADMIN_PASSWORD)

            # Admin login failed, just give a 'request failed' error flash
            if not session:
                return render_template('domjudge/problem/submit.htm',
                                       contest_id=contest_id)

            # Get the id of the 'viaduct_user' team category
            viaduct_user_cat_id = DOMjudgeAPI.get_viaduct_category_id(session)
            if not viaduct_user_cat_id:
                flash('Team category viaduct_user not found on DOMjudge.',
                      'danger')
                return render_template('domjudge/problem/submit.htm',
                                       contest_id=contest_id)

            # Check if the team already exists. This should normally
            # not be the case, but things can go wrong if we
            # create a new team anyway, since team names are not unique.
            user_team_id = DOMjudgeAPI.get_teamid_for_user(dom_teamname,
                                                           viaduct_user_cat_id,
                                                           session)
            if not user_team_id:
                r = DOMjudgeAPI.add_team(dom_teamname, dom_username,
                                         viaduct_user_cat_id, session)
                if not r:
                    return render_template('domjudge/problem/submit.htm',
                                           contest_id=contest_id)

                # Get the id of the newly created team
                user_team_id = DOMjudgeAPI.get_teamid_for_user(
                    dom_teamname, viaduct_user_cat_id, session)

            # Create the user
            r = DOMjudgeAPI.add_user(
                dom_username, dom_password,
                current_user.first_name + " " + current_user.last_name,
                current_user.email, user_team_id, session)

            if not r:
                return render_template('domjudge/problem/submit.htm',
                                       contest_id=contest_id)

            DOMjudgeAPI.logout(session)

            # Login as the new user
            session = DOMjudgeAPI.login(dom_username, dom_password)

            if not session:
                return render_template('domjudge/problem/submit.htm',
                                       contest_id=contest_id)

        r = DOMjudgeAPI.submit(contest['shortname'], language,
                               problem['shortname'], file, session)
        if not r:
            return render_template('domjudge/problem/submit.htm',
                                   contest_id=contest_id)
        flash(_("Submission successful."))
        return redirect(url_for('domjudge.contest_view',
                                contest_id=contest_id))
    else:
        return render_template('domjudge/problem/submit.htm',
                               **locals())

Example 10

Project: runbook Source File: views.py
@monitor_blueprint.route(
    '/dashboard/edit-monitors/<cname>/<cid>', methods=['GET', 'POST'])
def editcheck_page(cname, cid):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-monitors/' + cname + "/" + cid
        tmpl = 'monitors/create.html'
        data['edit'] = True
        data['js_bottom'] = ['monitors/base.js',]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            oldmonitor = Monitor()
            oldmonitor.config = app.config
            oldmonitor.get(cid, g.rdb_conn)
            if oldmonitor.uid == user.uid:
                data['monitor'] = {
                    'cid': oldmonitor.cid,
                    'name': oldmonitor.name,
                    'uid': oldmonitor.uid,
                    'ctype': oldmonitor.ctype,
                    'url': oldmonitor.url,
                    'data': oldmonitor.data
                }
            # Check if the form contains the timer SelectField
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            reactdefaults = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
                if data['reactions'][key]['id'] in \
                        data['monitor']['data']['reactions']:
                    reactdefaults.append(data['reactions'][key]['id'])
            form.reactions.choices = reactchoices
            for item in form.__iter__():
                if item.type == "SelectField" or\
                        item.type == "SelectMultipleField":
                    item.default = data['monitor']['data'][item.name]

            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.config = app.config
                    monitor.cid = cid
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = oldmonitor.url
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    monitor.data = tmpdata
                    data['monitor'] = {
                        'cid': monitor.cid,
                        'name': monitor.name,
                        'uid': monitor.uid,
                        'ctype': monitor.ctype,
                        'url': monitor.url,
                        'data': monitor.data
                    }
                    reactdefaults = data['monitor']['data']['reactions']
                    # Check if the user already exceeds their limit
                    if oldmonitor.uid == user.uid:
                        # Create the monitor if all checks out
                        results = monitor.editMonitor(g.rdb_conn)
                    else:
                        results = "NotYours"
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: not users".format(cname))
                        flash("This Monitor doesn't appear to be yours.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: exists".format(cname))
                        flash('This monitor seems to already exist. \
                               Try using a different name.', 'danger')
                    elif results is False:
                        print("/dashboard/edit-monitors/{0} - Monitor \
                              edit failed: unknown reason".format(cname))
                        flash('Could not edit monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit failed: too many".format(cname))
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added',
                            1
                        )
                        print("/dashboard/edit-monitors/{0} - \
                              Monitor edit successful").format(cname)
                        flash('Monitor "{0}" successfully edited'.format(
                            monitor.name), 'success')
                else:
                    print("/dashboard/edit-monitors/{0} - \
                          Monitor edit failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
            # Process form to display defaults
            if form.__contains__("timer"):
                form.timer.default = data['monitor']['data']['timer']
            form.reactions.default = reactdefaults
            form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 11

Project: tarbell Source File: app.py
Function: preview
    def preview(self, path=None, extra_context=None, publish=False):
        """
        Serve up a project path
        """
        try:
            self.call_hook("preview", self)

            if path is None:
                path = 'index.html'

            # Detect files
            filepath, mimetype = self._resolve_path(path)

            # Serve dynamic
            if filepath and mimetype and mimetype in self.project.TEMPLATE_TYPES:
                context = self.get_context(publish)
                context.update({
                    "PATH": path,
                    "PREVIEW_SERVER": not publish,
                    "TIMESTAMP": int(time.time()),
                })
                if extra_context:
                    context.update(extra_context)

                rendered = render_template(path, **context)
                return Response(rendered, mimetype=mimetype)

            # Serve static
            if filepath:
                dir, filename = os.path.split(filepath)
                return send_from_directory(dir, filename)

        except Exception as e:
            ex_type, ex, tb = sys.exc_info()
            try:
                # Find template with name of error
                cls = e.__class__
                ex_type, ex, tb = sys.exc_info()

                context = self.project.DEFAULT_CONTEXT
                context.update({
                    'PATH': path,
                    'traceback': traceback.format_exception(ex_type, ex, tb),
                    'e': e,
                })
                if extra_context:
                    context.update(extra_context)

                try:
                    error_path = '_{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)
                except TemplateNotFound:
                    # Find template without underscore prefix, @TODO remove in v1.1
                    error_path = '{0}.{1}.html'.format(cls.__module__, cls.__name__)
                    rendered = render_template(error_path, **context)

                return Response(rendered, mimetype="text/html")
            except TemplateNotFound:
                # Otherwise raise old error
                raise ex_type, ex, tb

        # Last ditch effort -- see if path has "index.html" underneath it
        if not path.endswith("index.html"):
            if not path.endswith("/"):
                path = "{0}/".format(path)
            path = "{0}{1}".format(path, "index.html")
            return self.preview(path)

        # It's a 404
        if path.endswith('/index.html'):
            path = path[:-11]
        rendered = render_template("404.html", PATH=path)
        return Response(rendered, status=404)

Example 12

Project: utter-va Source File: configurehandlers.py
@mod.route('/configure/twitter', methods=['GET', 'POST'])
@login_required
def configure_twitter():
	# check configuration
	settings = Status().check_settings()

	# get the forms for the page
	form = TwitterForm(request.form)
	mrof = BotForm(request.form)

	# blow the flavors into a list
	flavor_list = []
	flavors = Flavors.get_all()
	for flavor in flavors:
		flavor_list.append((flavor.id, flavor.description))
	
	mrof.flavor.choices = flavor_list

	# twitter bot credentials
	bot = TwitterBot.get()

	# initialize the bot if it's not
	if not bot:
		bot = oauth_initialize()
	else:
		if bot.complete == 0:
			bot = oauth_initialize()

		if bot.complete == 1 and request.method == 'GET':
			# ensure we don't use stale creds
			bot = oauth_initialize()

		elif bot.complete == 1 and request.method == 'POST':
			if form.validate_on_submit():
				pin = request.form['pin']
				bot = oauth_complete(pin)
				if bot:
					flash("Authentication with Twitter complete.", "success")
				else:
					flash("Authentication with Twitter failed.", "error")
					bot = TwitterBot.get()
					bot.delete(bot)
					return redirect(url_for(".configure_twitter"))	
			else:
				# form was not valid, so show errors	
				flash("There were form errors. Please check your entries and try again.", "error")
				
		elif request.method == 'POST':
			if mrof.validate_on_submit():
				bot.flavor_id = mrof.flavor.data
				bot.announce = mrof.announce.data
				bot.max_instances = mrof.max_instances.data
				bot.updated = int(time.time())
				bot.update()

				if bot.announce > 0:
					# announce (requires 'settings' in comment to reload stream bot)
					tweet_status("Appliance settings updated. Now serving up to (%s) %s instances via '@%s !status'" % (
							bot.max_instances,
							bot.flavor.name,
							bot.screen_name
						)
					)
				flash("Bot settings updated.", "success")
			else:
				# form was not valid, so show errors	
				flash("There were form errors. Please check your entries and try again.", "error")	

	# no bot not hot
	if not bot:
		flash("Twitterbot failed to contact Twitter or get credentials.", "error")
		bot = None

	else:
		# set default form values
		mrof.flavor.data = bot.flavor_id
		mrof.announce.data = bot.announce

	return render_template(
		'configure/twitter.html',
		bot=bot,
		settings=settings,
		form=form,
		mrof=mrof
	)

Example 13

Project: sagenb Source File: authentication.py
@authentication.route('/register', methods = ['GET','POST'])
@with_lock
def register():
    if not g.notebook.user_manager().get_accounts():
        return redirect(url_for('base.index'))
    from sagenb.notebook.misc import is_valid_username, is_valid_password, \
    is_valid_email, do_passwords_match
    from sagenb.notebook.challenge import challenge

    # VALIDATORS: is_valid_username, is_valid_password,
    # do_passwords_match, is_valid_email,
    # challenge.is_valid_response
    # INPUT NAMES: username, password, retype_password, email +
    # challenge fields

    # TEMPLATE VARIABLES: error, username, username_missing,
    # username_taken, username_invalid, password_missing,
    # password_invalid, passwords_dont_match,
    # retype_password_missing, email, email_missing,
    # email_invalid, email_address, challenge, challenge_html,
    # challenge_missing, challenge_invalid

    # PRE-VALIDATION setup and hooks.
    required = set(['username', 'password'])
    empty = set()
    validated = set()

    # Template variables.  We use empty_form_dict for empty forms.
    empty_form_dict = {}
    template_dict = {}

    if g.notebook.conf()['email']:
        required.add('email')
        empty_form_dict['email'] = True

    if g.notebook.conf()['challenge']:
        required.add('challenge')
        empty_form_dict['challenge'] = True
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])
        empty_form_dict['challenge_html'] = chal.html()

    template_dict.update(empty_form_dict)

    # VALIDATE FIELDS.

    # Username.  Later, we check if a user with this username
    # already exists.
    username = request.values.get('username', None)
    if username:
        if not is_valid_username(username):
            template_dict['username_invalid'] = True
        elif g.notebook.user_manager().user_exists(username):
            template_dict['username_taken'] = True
        else:
            template_dict['username'] = username
            validated.add('username')
    else:
        template_dict['username_missing'] = True
        empty.add('username')

    # Password.
    password = request.values.get('password', None)
    retype_password = request.values.get('retype_password', None)
    if password:
        if not is_valid_password(password, username):
            template_dict['password_invalid'] = True
        elif not do_passwords_match(password, retype_password):
            template_dict['passwords_dont_match'] = True
        else:
            validated.add('password')
    else:
        template_dict['password_missing'] = True
        empty.add('password')

    # Email address.
    email_address = ''
    if g.notebook.conf()['email']:
        email_address = request.values.get('email', None)
        if email_address:
            if not is_valid_email(email_address):
                template_dict['email_invalid'] = True
            else:
                template_dict['email_address'] = email_address
                validated.add('email')
        else:
            template_dict['email_missing'] = True
            empty.add('email')

    # Challenge (e.g., reCAPTCHA).
    if g.notebook.conf()['challenge']:
        status = chal.is_valid_response(req_args = request.values)
        if status.is_valid is True:
            validated.add('challenge')
        elif status.is_valid is False:
            err_code = status.error_code
            if err_code:
                template_dict['challenge_html'] = chal.html(error_code = err_code)
            else:
                template_dict['challenge_invalid'] = True
        else:
            template_dict['challenge_missing'] = True
            empty.add('challenge')

    # VALIDATE OVERALL.
    if empty == required:
        # All required fields are empty.  Not really an error.
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                               **empty_form_dict)
    elif validated != required:
        # Error(s)!
        errors = len(required) - len(validated)
        template_dict['error'] = 'E ' if errors == 1 else 'Es '
        return render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)

    # Create an account, if username is unique.
    try:
        g.notebook.user_manager().add_user(username, password, email_address)
    except ValueError:
        template_dict['username_taken'] = True
        template_dict['error'] = 'E '

        form = render_template(os.path.join('html', 'accounts', 'registration.html'),
                        **template_dict)
        return HTMLResponse(stream = form)

    #XXX: Add logging support
    #log.msg("Created new user '%s'"%username)

    # POST-VALIDATION hooks.  All required fields should be valid.
    if g.notebook.conf()['email']:
        from sagenb.notebook.smtpsend import send_mail
        from sagenb.notebook.register import make_key, build_msg

        # TODO: make this come from the server settings
        key = make_key()
        listenaddr = g.notebook.interface
        port = g.notebook.port
        fromaddr = 'no-reply@%s' % listenaddr
        body = build_msg(key, username, listenaddr, port, g.notebook.secure)

        # Send a confirmation message to the user.
        try:
            send_mail(fromaddr, email_address,
                      _("Sage Notebook Registration"), body)
            waiting[key] = username
        except ValueError:
            pass

    # Go to the login page.
    from sagenb.misc.misc import SAGE_VERSION
    template_dict = {'accounts': g.notebook.user_manager().get_accounts(),
                     'welcome_user': username,
                     'recovery': g.notebook.conf()['email'],
                     'sage_version': SAGE_VERSION}

    return render_template(os.path.join('html', 'login.html'), **template_dict)

Example 14

Project: testssl.sh-webfrontend Source File: SSLTestPortal.py
@application.route("/", methods=['GET', 'POST'])
def main():
    if request.method == 'GET':                         # Main Page
        return render_template("main.html")
    elif request.method == 'POST':                      # Perform Test
        # Sanity checks of request values
        ok = True
        host = request.form['host']
        if not reHost.match(host):
            flash("Wrong host name!")
            ok = False
        if host == "localhost" or host.find("127.") == 0:
            flash("I was already pentested ;)")
            ok = False

        try:
            port = int(request.form['port'])
            if not (port >= 0 and port <= 65535):
                flash("Wrong port number!")
                ok = False
        except:
            flash("Port number must be numeric")
            ok = False

        if 'starttls' in request.form and request.form['starttls'] == "yes":
            starttls = True
        else:
            starttls = False

        protocol = request.form['protocol']
        if starttls and protocol not in protocols:
            flash("Wrong protocol!")
            ok = False

        if not ('confirm' in request.form and request.form['confirm'] == "yes"):
            flash("You must confirm that you are authorized to scan the given system!")
            ok = False

        # Perform preflight request to prevent that testssl.sh runs into long timeout
        if ok and preflightRequest:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                s.settimeout(preflightTimeout)
                s.connect((host, port))
                s.close()
            except:
                flash("Connection failed!")
                ok = False

        if not ok:
            return redirect(url_for('main'))

        # Build command line
        args = [checkCmd]
        args += checkArgs
        if starttls:
            args.append("-t")
            args.append(protocol)
        args.append(host + ":" + str(port))

        # Perform test
        output = b""
        try:
            check = Popen(args, stdout=PIPE, stderr=PIPE)
            output, err = check.communicate(timeout=checkTimeout)
            if check.returncode != 0:
                output = err
                flash("SSL Scan failed with error code " + str(check.returncode) + " - see below for details")
        except TimeoutExpired as e:
            flash("SSL Scan timed out")
            check.terminate()

        html = "<pre>" + str(output, 'utf-8') + "</pre>"
        try:
            renderer = Popen([rendererCmd], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            html, err = renderer.communicate(input=output, timeout=rendererTimeout)
            if renderer.returncode != 0:
                html = "<pre>" + str(err, 'utf-8') + "</pre>"
                flash("HTML formatting failed with error code " + str(renderer.returncode) + " - see raw output below")
        except TimeoutExpired as e:
            flash("HTML formatting failed - see raw output below")
            renderer.terminate()

        ts = datetime.now()
        try:
            resultfile = open(resultDirHTML + "/" + ts.strftime("%Y%m%d-%H%M%S.%f") + "-" + host + "_" + str(port) + ".html", mode='w')
            resultfile.write(str(html, 'utf-8'))
            resultfile.close()
        except:
            pass
        return render_template("result.html", result=str(html, 'utf-8'))

Example 15

Project: dynamodb-tictactoe-example-app Source File: application.py
@application.route('/game=<gameId>')
def game(gameId):
    """
    Method associated the with the '/game=<gameId>' route where the
    gameId is in the URL.

    Validates that the gameId actually exists.

    Checks to see if the game has been finished.

    Gets the state of the board and updates the visual representation
    accordingly.

    Displays a bit of extra information like turn, status, and gameId.
    """
    if session.get("username", None) == None:
        flash("Need to login")
        return redirect("/index")

    item = controller.getGame(gameId)
    if item == None:
        flash("That game does not exist.")
        return redirect("/index")


    boardState = controller.getBoardState(item)
    result = controller.checkForGameResult(boardState, item, session["username"])

    if result != None:
        if controller.changeGameToFinishedState(item, result, session["username"]) == False:
            flash("Some error occured while trying to finish game.")

    game = Game(item)
    status   = game.status
    turn     = game.turn

    if game.getResult(session["username"]) == None:
        if (turn == game.o):
            turn += " (O)"
        else:
            turn += " (X)"

    gameData = {'gameId': gameId, 'status': game.status, 'turn': game.turn, 'board': boardState};
    gameJson = json.dumps(gameData)
    return render_template("play.html",
                            gameId=gameId,
                            gameJson=gameJson,
                            user=session["username"],
                            status=status,
                            turn=turn,
                            opponent=game.getOpposingPlayer(session["username"]),
                            result=result,
                            TopLeft=boardState[0],
                            TopMiddle=boardState[1],
                            TopRight=boardState[2],
                            MiddleLeft=boardState[3],
                            MiddleMiddle=boardState[4],
                            MiddleRight=boardState[5],
                            BottomLeft=boardState[6],
                            BottomMiddle=boardState[7],
                            BottomRight=boardState[8])

Example 16

Project: galah Source File: _browse_assignments.py
@app.route("/assignments")
@account_type_required(("student", "teacher", "teaching_assistant"))
def browse_assignments():
    # Grab all the current user's classes
    classes = Class.objects(id__in = current_user.classes).only("name")

    # Get the current time so we don't have to do it over and over again.
    now = datetime.datetime.today()

    if "show_all" in request.args:
        assignments = list(Assignment.objects(
            Q(for_class__in = current_user.classes) &
            (Q(hide_until = None) | Q(hide_until__lt = now))
        ).only("name", "due", "due_cutoff", "for_class"))
    else:
        personal_deadlines = (current_user.personal_deadline.items() +
            current_user.personal_due_date.items())

        # Figure out which assignments the users have personal deadline
        # extensions first.
        due_date_exceptions = set()
        for k, v in personal_deadlines:
            if v > now - datetime.timedelta(weeks = 1):
                due_date_exceptions.add(ObjectId(k))
        due_date_exceptions = list(due_date_exceptions)

        assignments = list(Assignment.objects(
            Q(for_class__in = current_user.classes) &
            (Q(due__gt = now - datetime.timedelta(weeks = 1)) |
             Q(due_cutoff__gt = now - datetime.timedelta(weeks = 1)) |
             Q(id__in = due_date_exceptions)) &
            (Q(hide_until = None) | Q(hide_until__lt = now))
        ).only("name", "due", "due_cutoff", "for_class"))

    assignments = [i for i in assignments if
            not i.hide_until or i.hide_until < now]

    # Get the number of assignments that we could have gotten if we didn't
    # limit based on due date.
    all_assignments_count = Assignment.objects(
        Q(for_class__in = current_user.classes) &
        (Q(hide_until = None) | Q(hide_until__lt = now))
    ).count()

    submissions = list(Submission.objects(
            user = current_user.email,
            assignment__in = [i.id for i in assignments],
            most_recent = True
    ))

    # Add a property to all the assignments so the template can display their
    # respective class easier. Additionally, add a plain text version of the
    # due date
    for i in assignments:
        try:
            i.class_name = next((j.name for j in classes if j.id == i.for_class))
        except StopIteration:
            logger.error(
                "Assignment with id %s references non-existant class with id "
                "%s." % (str(i.id, i.for_class))
            )

            i.class_name = "DNE"

        i.apply_personal_deadlines(current_user)

        # Figure out the status messages that we want to display to the user.
        submitted = next((j for j in submissions if j.assignment == i.id), None)
        i.submitted = submitted
        i.status = i.status_color = None
        if submitted:
            i.status = (
                "You made a submission " +
                create_time_element(submitted.timestamp, now)
            )

            i.status_color = "#84B354"
        elif now < i.due:
            i.status = "You have not submitted yet"

            i.status_color = "#877150"
        elif now > i.due and i.due_cutoff and now > i.due_cutoff:
            i.status = "You have not submitted yet, and it is too late to do so"

            i.status_color = "#E9A400"
        elif now > i.due:
            i.status = "You have not submitted yet!"

            i.status_color = "#FB4313"

    # Sort the assignments by due_cutoff or due date if due_cutoff is not
    # assigned.
    assignments.sort(
        key = lambda i: i.due_cutoff if i.due_cutoff else i.due,
        reverse = True
    )

    return render_template(
        "assignments.html",
        assignments = assignments,
        hidden_assignments = -1 if "show_all" in request.args
                else all_assignments_count - len(assignments),
        create_time_element = create_time_element
    )

Example 17

Project: pybossa Source File: stats.py
@blueprint.route('/')
def index():
    """Return Global Statistics for the site."""
    title = "Global Statistics"

    n_auth = site_stats.n_auth_users()

    n_anon = site_stats.n_anon_users()

    n_total_users = n_anon + n_auth

    n_published_projects = cached_projects.n_published()
    n_draft_projects = cached_projects.n_count('draft')
    n_total_projects = n_published_projects + n_draft_projects

    n_tasks = site_stats.n_tasks_site()

    n_task_runs = site_stats.n_task_runs_site()

    top5_projects_24_hours = site_stats.get_top5_projects_24_hours()

    top5_users_24_hours = site_stats.get_top5_users_24_hours()

    locs = site_stats.get_locs()

    show_locs = False
    if len(locs) > 0:
        show_locs = True

    stats = dict(n_total_users=n_total_users, n_auth=n_auth, n_anon=n_anon,
                 n_published_projects=n_published_projects,
                 n_draft_projects=n_draft_projects,
                 n_total_projects=n_total_projects,
                 n_tasks=n_tasks,
                 n_task_runs=n_task_runs)

    users = dict(label="User Statistics",
                 values=[
                     dict(label='Anonymous', value=[0, n_anon]),
                     dict(label='Authenticated', value=[0, n_auth])])

    projects = dict(label="Projects Statistics",
                    values=[
                        dict(label='Published',
                             value=[0, n_published_projects]),
                        dict(label='Draft', value=[0, n_draft_projects])])

    tasks = dict(label="Task and Task Run Statistics",
                 values=[
                     dict(label='Tasks', value=[0, n_tasks]),
                     dict(label='Answers', value=[1, n_task_runs])])

    return render_template('/stats/global.html', title=title,
                           users=json.dumps(users),
                           projects=json.dumps(projects),
                           tasks=json.dumps(tasks),
                           locs=json.dumps(locs),
                           show_locs=show_locs,
                           top5_users_24_hours=top5_users_24_hours,
                           top5_projects_24_hours=top5_projects_24_hours,
                           stats=stats)

Example 18

Project: plenario Source File: __init__.py
def create_app():
    # API depends on the tables in the database to exist.
    # Don't import until we really need it to create the app
    # Since otherwise it may be called before init_db.py runs.
    from plenario.api import api, cache

    # These other imports might eventually use API as well.
    # plenario.views does now. So we'll put them here like
    # API and not import them until they're really needed.
    from plenario.apiary import apiary, apiary_bp
    from plenario.database import session as db_session
    from plenario.models import bcrypt
    from plenario.auth import auth, login_manager
    from plenario.views import views
    from plenario.utils.helpers import slugify as slug

    app = Flask(__name__)
    app.config.from_object('plenario.settings')
    app.url_map.strict_slashes = False
    login_manager.init_app(app)
    login_manager.login_view = "auth.login"
    bcrypt.init_app(app)

    if sentry:
        sentry.init_app(app)
    app.register_blueprint(api)
    app.register_blueprint(views)
    app.register_blueprint(auth)
    cache.init_app(app)

    apiary.init_app(app)
    app.register_blueprint(apiary_bp)

    @app.before_request
    def check_maintenance_mode():
        """
        If maintenance mode is turned on in settings.py,
        Disable the API and the interactive pages in the explorer.
        """
        maint = app.config.get('MAINTENANCE')
        maint_pages = ['/v1/api', '/explore', '/admin']

        maint_on = False
        for m in maint_pages:
            if m in request.path:
                maint_on = True

        if maint and maint_on and request.path != url_for('views.maintenance'):
            return redirect(url_for('views.maintenance'))

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    @app.errorhandler(500)
    def page_not_found(e):
        return render_template('error.html'), 500

    @app.template_filter('slugify')
    def slugify(s):
        return slug(s)

    @app.template_filter('format_number')
    def reverse_filter(s):
        return '{:,}'.format(s)

    @app.template_filter('format_date_sort')
    def reverse_filter(s):
        if s:
            return s.strftime('%Y%m%d%H%M')
        else:
            return '0'

    @app.template_filter('has_description')
    def has_description(list_of_cols):
        try:
            # Any description attribute filled?
            return any([col['description'] for col in list_of_cols])
        except KeyError:
            # Is there even a description attribute?
            return False

    return app

Example 19

Project: guides-cms Source File: views.py
@app.route('/publish', methods=['POST'])
@login_required
def change_publish_status():
    """Publish or unpublish article via POST"""

    user = models.find_user()
    if user is None:
        flash('Cannot change publish status unless logged in', category='error')
        return render_published_articles(status_code=401)

    path = request.form['path']
    branch = request.form['branch']

    publish_status = request.form['publish_status']
    if publish_status not in STATUSES:
        flash('Invalid publish status, must be one of "%s"' % (STATUSES),
              category='error')
        return render_template('index.html')

    if branch != u'master':
        flash('Cannot change publish status on guides from branches other than master', category='error')
        return redirect(url_for('index'))

    article = models.read_article(path, rendered_text=False, branch=branch)
    if article is None:
        flash('Cannot find guide to change publish status', category='error')
        return redirect(url_for('index'))

    if article.publish_status == publish_status:
        flash('Guide already in %s publish status' % (publish_status),
              category='warning')
        return redirect(filters.url_for_article(article))

    if not user.is_collaborator:
        if article.author_name != user.login:
            flash('Only collaborators can change publish status on guides they do not start',
                  category='error')
            return redirect(url_for('index'))

        if publish_status == PUBLISHED:
            flash('Only collaborators can publish guides')
            return redirect(url_for('index'))

    curr_path = article.path

    app.logger.info(u'Requesting publish change for "%s" from "%s" to "%s"',
                    article.title, article.publish_status, publish_status)

    article.publish_status = publish_status

    author_url = filters.url_for_user(article.author_name,
                                      base_url=app.config['DOMAIN'])

    # Create this link AFTER changing the status b/c the URL will have the
    # status in it if the article is not published yet.
    article_url = filters.url_for_article(article,
                                          base_url=app.config['DOMAIN'])

    tasks.update_listing.delay(article_url,
                               article.title,
                               author_url,
                               article.author_real_name,
                               user.login,
                               user.email,
                               author_img_url=article.image_url,
                               thumbnail_url=article.thumbnail_url,
                               stacks=article.stacks,
                               branch=article.branch,
                               status=article.publish_status)

    tasks.move_article.delay(curr_path, article.path, article.title,
                             user.login, user.email,
                             new_publish_status=article.publish_status)

    return redirect(filters.url_for_article(article, saved=1))

Example 20

Project: viaduct Source File: committee.py
@blueprint.route('/edit/commissie/<string:committee>', methods=['GET', 'POST'])
def edit_committee(committee=''):
    if not ModuleAPI.can_write('committee'):
        return abort(403)

    path = 'commissie/' + committee

    page = Page.get_by_path(path)

    form = request.form
    if page:
        revision = page.get_latest_revision()
        form = CommitteeForm(form, revision)
    else:
        revision = None
        form = CommitteeForm()

    try:
        url_group_id = int(request.args.get('group_id', None))
    except:
        url_group_id = None

    form.group_id.choices = [(group.id, group.name) for group in
                             Group.query.order_by(Group.name).all()]

    if len(request.form) == 0:
        if revision:
            selected_group_id = revision.group_id
        elif url_group_id is not None:
            selected_group_id = url_group_id
        else:
            selected_group_id = form.group_id.choices[0][0]
    else:
        selected_group_id = int(form.group_id.data)

    form.group_id.data = selected_group_id

    selected_group = Group.query.get(selected_group_id)
    form.coordinator_id.choices = [
        (user.id, user.name) for user in
        selected_group.users.order_by(User.first_name, User.last_name).all()]

    form.nl_title.data = selected_group.name

    if form.validate_on_submit():
        committee_nl_title = form.nl_title.data.strip()
        committee_en_title = form.en_title.data.strip()

        if not page:
            root_entry_url = url_for('committee.list').rstrip('/')
            root_entry = NavigationEntry.query\
                .filter(NavigationEntry.url == root_entry_url)\
                .first()

            # Check whether the root navigation entry exists.
            if not root_entry:
                last_root_entry = NavigationEntry.query\
                    .filter(NavigationEntry.parent_id == None)\
                    .order_by(NavigationEntry.position.desc()).first()  # noqa

                root_entry_position = 1
                if last_root_entry:
                    root_entry_position = last_root_entry.position + 1

                root_entry = NavigationEntry(
                    None, 'Commissies', 'Committees', root_entry_url, False,
                    False, root_entry_position)

                db.session.add(root_entry)
                db.session.commit()

            page = Page(path, 'committee')

            # Never needs payed.
            page.needs_payed = False

            # Create a navigation entry for the new committee.
            last_navigation_entry = NavigationEntry.query\
                .filter(NavigationEntry.parent_id == root_entry.id)\
                .first()

            entry_position = 1
            if last_navigation_entry:
                entry_position = last_navigation_entry.position + 1

            navigation_entry = NavigationEntry(
                root_entry, committee_nl_title, committee_en_title, '/' + path,
                False, False, entry_position)

            db.session.add(navigation_entry)
            db.session.commit()

            # Sort these navigation entries.
            NavigationAPI.alphabeticalize(root_entry)

            # Assign the navigation entry to the new page (committee).
            page.navigation_entry_id = navigation_entry.id

            db.session.add(page)
            db.session.commit()

            # Assign read rights to all, and edit rights to BC.
            all_group = Group.query.filter(Group.name == 'all').first()
            bc_group = Group.query.filter(Group.name == 'BC').first()

            all_entry = PagePermission(all_group.id, page.id, 1)
            bc_entry = PagePermission(bc_group.id, page.id, 2)

            db.session.add(all_entry)
            db.session.add(bc_entry)
            db.session.commit()
        else:
            # If the committee's title has changed, the navigation needs to be
            # updated. Look for the entry, compare the titles, and change where
            # necessary.
            entry = NavigationEntry.query\
                .filter(NavigationEntry.url == '/' + path).first()
            if entry.title != committee_nl_title:
                entry.title = committee_nl_title
                db.session.add(entry)
                db.session.commit()

        group_id = int(form.group_id.data)
        coordinator_id = int(form.coordinator_id.data)

        # Add coordinator to BC
        bc_group = Group.query.filter(Group.name == "BC").first()
        if bc_group is not None:
            new_coordinator = User.query.filter(
                User.id == coordinator_id).first()
            bc_group.add_user(new_coordinator)

        new_revision = CommitteeRevision(
            page, committee_nl_title, committee_en_title,
            form.comment.data.strip(), current_user.id,
            form.nl_description.data.strip(), form.en_description.data.strip(),
            group_id, coordinator_id, form.interim.data)

        db.session.add(new_revision)
        db.session.commit()

        flash(_('The committee has been saved.'), 'success')

        return redirect(url_for('page.get_page', path=path))
    else:
        flash_form_errors(form)

    return render_template('committee/edit.htm', page=page,
                           form=form, path=path)

Example 21

Project: get5-web Source File: match.py
@match_blueprint.route('/match/create', methods=['GET', 'POST'])
def match_create():
    if not g.user:
        return redirect('/login')

    form = MatchForm(request.form)
    form.add_teams(g.user)
    form.add_teams(User.get_public_user())
    form.add_servers(g.user)

    if request.method == 'POST':
        num_matches = g.user.matches.count()
        max_matches = config_setting('USER_MAX_MATCHES')

        if max_matches >= 0 and num_matches >= max_matches and not g.user.admin:
            flash('You already have the maximum number of matches ({}) created'.format(
                num_matches))

        if form.validate():
            mock = config_setting('TESTING')

            server = GameServer.query.get_or_404(form.data['server_id'])

            match_on_server = g.user.matches.filter_by(
                server_id=server.id, end_time=None, cancelled=False).first()

            server_avaliable = False
            json_reply = None

            if g.user.id != server.user_id:
                server_avaliable = False
                message = 'This is not your server!'
            elif match_on_server is not None:
                server_avaliable = False
                message = 'Match {} is already using this server'.format(
                    match_on_server.id)
            elif mock:
                server_avaliable = True
                message = 'Success'
            else:
                json_reply, message = util.check_server_avaliability(
                    server)
                server_avaliable = (json_reply is not None)

            if server_avaliable:
                skip_veto = 'preset' in form.data['series_type']
                try:
                    max_maps = int(form.data['series_type'][2])
                except ValueError:
                    max_maps = 1

                match = Match.create(
                    g.user, form.data['team1_id'], form.data['team2_id'],
                    form.data['team1_string'], form.data['team2_string'],
                    max_maps, skip_veto, form.data['match_title'],
                    form.data['veto_mappool'], form.data['server_id'])

                # Save plugin version data if we have it
                if json_reply and 'plugin_version' in json_reply:
                    match.plugin_version = json_reply['plugin_version']
                else:
                    match.plugin_version = 'unknown'

                server.in_use = True

                db.session.commit()
                app.logger.info('User {} created match {}, assigned to server {}'
                                .format(g.user.id, match.id, server.id))

                if mock or match.send_to_server():
                    return redirect('/mymatches')
                else:
                    flash('Failed to load match configs on server')
            else:
                flash(message)

        else:
            get5.flash_errors(form)

    return render_template('match_create.html', form=form, user=g.user, teams=g.user.teams)

Example 22

Project: DockCI Source File: core.py
@APP.route('/config', methods=('GET', 'POST'))
@login_required
@roles_required('admin')
def config_edit_view():
    """
    View to edit global config
    """
    restart_fields = (
        'secret',
        'docker_use_env_vars', 'docker_hosts',
        'mail_host_string', 'mail_use_tls', 'mail_use_ssl',
        'mail_username', 'mail_password', 'mail_default_sender',
        'security_registerable_form', 'security_login_form',
        'security_registerable_github', 'security_login_github',
        'security_registerable_gitlab', 'security_login_gitlab',
        'security_recoverable',
        'external_url', 'external_rabbit_uri',
        'github_key', 'github_secret',
        'gitlab_key', 'gitlab_secret', 'gitlab_base_url',
        'live_log_message_timeout', 'live_log_session_timeout',
        'redis_len_expire',
        'auth_fail_max', 'auth_fail_ttl_sec',
        'oauth_authorized_redirects',
    )
    all_fields = restart_fields + ()
    blanks = (
        'external_url', 'external_rabbit_uri',
        'github_key', 'gitlab_key', 'gitlab_base_url',
        'mail_host_string', 'mail_default_sender', 'mail_username',
    )

    if request.method == 'POST':
        saved = request_fill(CONFIG, all_fields, accept_blank=blanks)
    else:
        saved = False

    try:
        CONFIG.load()

    except py.error.ENOENT:
        pass

    if saved:
        restart_needed = any((
            (
                attr in request.form and
                request.form[attr] != getattr(CONFIG, attr)
            )
            for attr in restart_fields
        ))
        if restart_needed:
            CONFIG.restart_needed = True

    return render_template('config_edit.html')

Example 23

Project: pagure Source File: __init__.py
@API.route('/')
def api():
    ''' Display the api information page. '''
    api_git_tags_doc = load_doc(project.api_git_tags)
    api_projects_doc = load_doc(project.api_projects)

    issues = []
    if pagure.APP.config.get('ENABLE_TICKETS', True):
        issues.append(load_doc(issue.api_new_issue))
        issues.append(load_doc(issue.api_view_issues))
        issues.append(load_doc(issue.api_view_issue))
        issues.append(load_doc(issue.api_view_issue_comment))
        issues.append(load_doc(issue.api_comment_issue))

    ci_doc = []
    if pagure.APP.config.get('PAGURE_CI_SERVICES', True):
        if 'jenkins' in pagure.APP.config['PAGURE_CI_SERVICES']:
            ci_doc.append(load_doc(jenkins.jenkins_ci_notification))

    api_pull_request_views_doc = load_doc(fork.api_pull_request_views)
    api_pull_request_view_doc = load_doc(fork.api_pull_request_view)
    api_pull_request_merge_doc = load_doc(fork.api_pull_request_merge)
    api_pull_request_close_doc = load_doc(fork.api_pull_request_close)
    api_pull_request_add_comment_doc = load_doc(
        fork.api_pull_request_add_comment)
    api_pull_request_add_flag_doc = load_doc(fork.api_pull_request_add_flag)

    api_new_project_doc = load_doc(project.api_new_project)

    api_version_doc = load_doc(api_version)
    api_users_doc = load_doc(api_users)
    api_view_user_doc = load_doc(user.api_view_user)
    if pagure.APP.config.get('ENABLE_TICKETS', True):
        api_project_tags_doc = load_doc(api_project_tags)
    api_groups_doc = load_doc(api_groups)
    api_error_codes_doc = load_doc(api_error_codes)

    extras = [
        api_version_doc,
        api_error_codes_doc,
    ]

    if pagure.APP.config.get('ENABLE_TICKETS', True):
        extras.append(api_project_tags_doc)

    return flask.render_template(
        'api.html',
        version=__api_version__.split('.'),
        api_doc=APIDOC,
        projects=[
            api_new_project_doc,
            api_git_tags_doc,
            api_projects_doc,
        ],
        issues=issues,
        requests=[
            api_pull_request_views_doc,
            api_pull_request_view_doc,
            api_pull_request_merge_doc,
            api_pull_request_close_doc,
            api_pull_request_add_comment_doc,
            api_pull_request_add_flag_doc,
        ],
        users=[
            api_users_doc,
            api_view_user_doc,
            api_groups_doc,
        ],
        ci=ci_doc,
        extras=extras,
    )

Example 24

Project: utter-va Source File: configurehandlers.py
@mod.route('/configure/openstack', methods=['GET', 'POST'])
@login_required
def configure_openstack():
# quote strip
	def dequote(string):
		if string.startswith('"') and string.endswith('"'):
			string = string[1:-1]
		return string

	# check configuration
	settings = Status().check_settings()

	# get the form
	form = OpenStackForm(request.form)

	# try to select one and only record
	openstack = db.session.query(OpenStack).first()


	# create new entry if configuration doesn't exist
	if not openstack:
		openstack = OpenStack()

	if request.method == 'POST':
		# clear settings cache
		Status().flush()

		# handle a file upload		
		try:
			file = request.files['file']
		except:
			file = False

		if file and allowed_file(file.filename):
			keyvals = {}
			for line in file:
				keyval = dict(re.findall(r'(\S+)=(".*?"|\S+)', line))
				if len(keyval) > 0:
					keyvals.update(keyval)
			
			# set values from extracted lines above - needs SQL injection protection?
			openstack.authurl = "%s" % dequote(keyvals['OS_AUTH_URL'])
			openstack.tenantname = "%s" % dequote(keyvals['OS_TENANT_NAME'])
			openstack.tenantid = "%s" % dequote(keyvals['OS_TENANT_ID'])
			try:
				openstack.region = "%s" % dequote(keyvals['OS_REGION_NAME'])

				if openstack.region == None:
					openstack.region = ""
			except:
				# don't need it
				openstack.region = ""
				pass
			openstack.osusername = "%s" % dequote(keyvals['OS_USERNAME'])
			openstack.ospassword = "changeme"

			# update entry
			openstack.update(openstack)

		elif file:
			# file type not allowed
			flash("File type not allowed or empty.  Try again.", "file-error")
		
		else:
			# user is manually updating form
			current_password = openstack.ospassword

			if form.validate_on_submit():
				# populate with form and update
				form.populate_obj(openstack)

				# check if password was blank and use old one
				if openstack.ospassword == "":
					openstack.ospassword = current_password

				openstack.update(openstack)

				flash("OpenStack settings updated!", "success")

			else:
				flash("There were form errors. Please check your entries and try again.", "error")

			# having to do this to get the form to update on password update
			return redirect("/configure/openstack")

	# get existing form data
	openstack = db.session.query(OpenStack).first()

	# if notice, show message
	return render_template(
		'configure/openstack.html', 
		settings=settings, 
		form=form, 
		openstack=openstack
	)	

Example 25

Project: runbook Source File: views.py
@reaction_blueprint.route(
    '/dashboard/reactions/<rname>', methods=['GET', 'POST'])
def addreaction_page(rname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/reactions/' + rname
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js']
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:

            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            if request.method == 'POST':
                if form.validate():
                    reaction = Reaction()
                    reaction.config = app.config
                    reaction.name = form.name.data
                    reaction.trigger = form.trigger.data
                    reaction.frequency = form.frequency.data
                    reaction.uid = user.uid
                    reaction.rtype = rname
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    reaction.data = tmpdata

                    if reaction.count(user.uid, g.rdb_conn) < data['rlimit']:
                        results = reaction.createReaction(g.rdb_conn)
                    else:
                        results = "toomany"

                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                            Reaction creation failed: exists".format(rname))
                        flash('{0} seems to already exist. Try using a \
                              different name.'.format(reaction.name), 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - Reaction \
                              edit failed: doesn't exist".format(rname))
                        flash('{0} cannot be edited as it does not \
                              exist.'.format(reaction.name), 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited: {0}.'.format(
                            reaction.name), 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited: {0}.'.format(
                            reaction.name), 'danger')
                    elif results == "toomany":
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: too many".format(rname))
                        flash('Could not create reaction: \
                              Too many reactions already created.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction creation failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction creation successful".format(rname))
                        flash('Reaction "{0}" successfully added.'.format(
                            reaction.name), 'success')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction creation failed: form invalid".format(rname))
                    flash('Form is not valid.', 'success')

        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 26

Project: python-indieweb Source File: indieweb.py
@app.route('/login', methods=['GET', 'POST'])
def handleLogin():
    app.logger.info('handleLogin [%s]' % request.method)

    form = LoginForm(me='', client_id=cfg['client_id'], 
                     redirect_uri='%s/success' % cfg['baseurl'], 
                     from_uri=request.args.get('from_uri'))

    if form.validate_on_submit():
        app.logger.info('me [%s]' % form.me.data)

        me            = baseDomain(form.me.data)
        authEndpoints = ninka.indieauth.discoverAuthEndpoints(me)

        if 'authorization_endpoint' in authEndpoints:
            authURL = None
            for url in authEndpoints['authorization_endpoint']:
                authURL = url
                break

            if authURL is not None:
                url = ParseResult(authURL.scheme, 
                                  authURL.netloc,
                                  authURL.path,
                                  authURL.params,
                                  urllib.urlencode({ 'me':            me,
                                                     'redirect_uri':  form.redirect_uri.data,
                                                     'client_id':     form.client_id.data,
                                                     'scope':         'post',
                                                     'response_type': 'id'
                                                   }),
                                  authURL.fragment).geturl()
                if db is not None:
                    key = 'login-%s' % me
                    data = db.hgetall(key)
                    if data: # clear any existing auth data
                        db.delete('token-%s' % data['token'])
                        db.hdel(key, 'token')
                    db.hset(key, 'from_uri',     form.from_uri.data)
                    db.hset(key, 'redirect_uri', form.redirect_uri.data)
                    db.hset(key, 'client_id',    form.client_id.data)
                    db.hset(key, 'scope',        'post')
                    db.expire(key, cfg['auth_timeout']) # expire in N minutes unless successful
                return redirect(url)
        else:
            return 'insert fancy no auth endpoint found error message here', 403

    templateData['title'] = 'Sign In'
    templateData['form']  = form
    return render_template('login.jinja', **templateData)

Example 27

Project: webapp Source File: recording.py
Function: index
@mod.route('/index')
def index():

    mount_failed = False
    files = {}

    try:
        subprocess.check_call("sudo mount | grep media | grep mmc", shell=True)
    except subprocess.CalledProcessError, e:
        mount_failed = True

    if not mount_failed:
        for flac_file in glob.glob('/media/*.flac'):
            ctime = time.strftime('%d.%m.%Y', time.gmtime(os.path.getmtime(flac_file)))
            total_samples = subprocess.check_output("metaflac --show-total-samples "+flac_file, shell=True)
            duration_min = int(total_samples) / 48000 / 60
            duration_sec = (int(total_samples) / 48000) - (duration_min * 60)
            duration_min_str = str(duration_min).zfill(2)
            duration_sec_str = str(duration_sec).zfill(2)
            files[flac_file[7:]] = {'date': ctime, 'duration_min': duration_min_str, 'duration_sec': duration_sec_str}

    try:
        capture_systemd_status = subprocess.check_output(['sudo',
                                                          'systemctl',
                                                          'is-active',
                                                          'studio-capture'])
    except subprocess.CalledProcessError, e:
        capture_systemd_status = 'failed'

    if capture_systemd_status == 'active\n':
        capture_status = True
        store.set('capture_status', 'true')
    else:
        capture_status = False
        store.set('capture_status', 'false')

    if mount_failed:
        sd_usage_percent = 100
    else:
        sd_usage_percent = int(subprocess.check_output("df -m /media | awk '{ print $5 }' | tail -1 | tr -d '%'", shell=True))

    sd_usage_message = 'success'
    if sd_usage_percent >= 70:
        sd_usage_message = 'warning'
    if sd_usage_percent >= 85:
        sd_usage_message = 'danger'

    return render_template('recording.html',mount_failed=mount_failed,
                                            files=files,
                                            sd_usage_message=sd_usage_message,
                                            sd_usage_percent=sd_usage_percent,
                                            capture_status=capture_status,
                                            playback=store.get('playback'))

Example 28

Project: straw Source File: views.py
def attach_views(app):

    @app.route('/_fetch_messages')
    def fetch_messages():
        # get a redis connection
        redis_connection = redis.Redis(connection_pool=app.pool)

        # update the query list in the view
        if session.get('sid') is not None:
            matches = redis_connection.lrange(session.get('sid'), 0, MAX_RESULTS)
        return jsonify(result=matches)

    @app.route('/', methods=['GET'])
    def index():
        if session.get('sid') is None:
            session['sid'] = uuid.uuid4().hex
        try:
            query_list = session['queries']
        except KeyError:
            query_list = []
        return render_template('index.html', query_list=query_list)

    @app.route('/', methods=['POST'])
    def search_box_control():
        '''add to or clear the list of queries.'''

        # we need a session
        if session.get('sid') is None:
            raise RuntimeError("No session.")
        sid = session.get('sid')       

        # get a redis connection
        redis_connection = redis.Redis(connection_pool=app.pool)
         
        # if clear button pressed:
        if 'clear' in request.form:
            app.clear_user(session.get('sid'))
            if session.has_key('queries'):
                del session['queries']
            return render_template("index.html", query_list=[], session=session)

        # create a new query
        text = request.form['text'].lower().split(" ")

        # generate a unique query id
        msg = {"type":"terms-query","terms":text,"minimum-match":len(text)}
        data = json.dumps(msg)
        qid = md5.new(data).hexdigest()
        query_string = " ".join(text)

        # add the qid and value to the query lookup store
        try:
            session['queries'].append(query_string)
        except KeyError:
            # sanity: clear any queries stored for this user but not in the session.
            redis_connection.delete(sid+"-queries")
            session['queries'] = [query_string]

        # try three times to do the post to kafka.
        post_success = False
        for i in range(3):
            try:
                app.producer.send_messages("queries", data)
            except (FailedPayloadsError, NotLeaderForPartitionError, KafkaUnavailableError) as e:
                # wait a bit and try again
                print("Failed to post query {0} to kafka. Try #{1}".format(data, i))
                sleep(0.25)
                continue
            post_success=True
            break

        if post_success==True:
            # subscribe the user to the query            
            try:
                app.user_channels[qid].add(sid)
            except KeyError:
                app.user_channels[qid] = set([sid])
                app.subscriber.add_query(qid)

            # link the id to the query text
            redis_connection.set(qid, " ".join(text))

            # add query to the list of things the user has subscribed to
            redis_connection.lpush(sid +"-queries", qid)

        # update the query list in the view
        query_list = session["queries"]
        return render_template("index.html", query_list=query_list)

    @app.route('/about')
    def about():
        return render_template('%s.html' % 'about')


    @app.route('/straw.pdf')
    def pdf():
        return app.send_static_file('assets/straw.pdf')

Example 29

Project: nbdiff Source File: DiffURLCommand.py
    def process(self, request, filename, db_session):
        errMsg = ""
        parser = NotebookParser()
        # Max Size of a notebook accepted is 20M.
        max_size = 20*1024*1024

        try:
            beforeURL = request.form['beforeURL']
            afterURL = request.form['afterURL']
        except BadRequestKeyError:
            errMsg = """Invalid notebook Diff Request. <br/>
                Please return to the home page and submit the request again."""
            return render_template('Error.html', err=errMsg)

        try:
            beforeFile = urllib2.urlopen(beforeURL)
            if int(beforeFile.info()['Content-Length']) > max_size:
                errMsg = errMsg + """The Before notebook exceeds 20MB.
                    Only notebooks below 20MB are accepted.<br/>"""
        except:
            errMsg = errMsg + """We are unable to access the Before
                notebook file from the given URL.<br/>"""

        try:
            afterFile = urllib2.urlopen(afterURL)
            if int(afterFile.info()['Content-Length']) > max_size:
                errMsg = errMsg + """The After notebook exceeds 20MB.
                    Only notebooks below 20MB are accepted.<br/>"""
        except:
            errMsg = errMsg + """We are unable to access the After
                notebook file from the given URL.<br/>"""

        if len(errMsg) == 0:
            try:
                nb_before = parser.parse(beforeFile)
            except nbformat.NotJSONError:
                errMsg = errMsg + """The Before notebook contains
                    invalid JSON data. <br/>"""
            try:
                nb_after = parser.parse(afterFile)
            except nbformat.NotJSONError:
                errMsg = errMsg + """The After notebook contains
                    invalid JSON data. <br/>"""

            beforeFile.close()
            afterFile.close()

        if len(errMsg) == 0:
            diffedNotebook = notebook_diff(nb_before, nb_after)

            # bitarray used to convert notebook to binary for BLOB
            ba = bitarray.bitarray()
            ba.fromstring(json.dumps(diffedNotebook, indent=2))

            # object to be saved to database
            obj = nbdiffModel(ba.to01())

            # add to database and commit it.
            try:
                db_session.add(obj)
                db_session.commit()
            except OperationalError:
                db_session.rollback()
                print """The database is not initialized.
                    Please restart server with argument init_db."""
                errMsg = """There was an error with the database. <br/>
                   Please contact administrator to resolve this issue."""
                return render_template('Error.html', err=errMsg)
            except:
                db_session.rollback()
                errMsg = """There was an unexpected error with the database.
                    <br/>Please try again later. <br/>
                    If this problem persists please contact administrator."""
                return render_template('Error.html', err=errMsg)

            # return the id of the object.
            nb_id = obj.id

            # redirect is used because we want
            # user to have a easier url to return to.
            return redirect("/Comparison/"+str(nb_id), code=302)
        else:
            return render_template('Error.html', err=errMsg)

Example 30

Project: blohg Source File: __init__.py
Function: create_app
def create_app(repo_path=None, revision_id=REVISION_DEFAULT,
               autoinit=True, embedded_extensions=False, debug=False):
    """Application factory.

    :param repo_path: the path to the mercurial repository.
    :return: the WSGI application (Flask instance).
    """

    # create the app object
    app = Flask(__name__, static_folder=None)
    app.debug = debug

    # register some sane default config values
    app.config.setdefault('AUTHOR', u'Your Name Here')
    app.config.setdefault('POSTS_PER_PAGE', 10)
    app.config.setdefault('TAGLINE', u'Your cool tagline')
    app.config.setdefault('TITLE', u'Your title')
    app.config.setdefault('TITLE_HTML', u'Your HTML title')
    app.config.setdefault('CONTENT_DIR', u'content')
    app.config.setdefault('ATTACHMENT_DIR', u'content/attachments')
    app.config.setdefault('ROBOTS_TXT', True)
    app.config.setdefault('SHOW_RST_SOURCE', True)
    app.config.setdefault('POST_EXT', u'.rst')
    app.config.setdefault('OPENGRAPH', True)
    app.config.setdefault('TIMEZONE', 'UTC')
    app.config.setdefault('LOCALE', 'en')
    app.config.setdefault('RST_HEADER_LEVEL', 3)
    app.config.setdefault('EXTENSIONS', [])
    app.config.setdefault('EXTENSIONS_DIR', 'ext')

    app.config['REPO_PATH'] = repo_path

    blohg = Blohg(app, embedded_extensions)

    app.add_url_rule('/static/<path:filename>', endpoint='static',
                     view_func=BlohgStaticFile('static'))
    app.add_url_rule('/attachments/<path:filename>', endpoint='attachments',
                     view_func=BlohgStaticFile(app.config['ATTACHMENT_DIR']))

    # setup extensions
    babel = Babel(app)

    @app.before_request
    def before_request():
        app.blohg.reload()

    @app.context_processor
    def setup_jinja2():
        return dict(
            version=__version__,
            is_post=lambda x: x.startswith('post/'),
            current_path=request.path.strip('/'),
            active_page=request.path.strip('/').split('/')[0],
            tags=app.blohg.content.tags,
            config=app.config,
        )

    @babel.timezoneselector
    def get_timezone():
        return app.config['TIMEZONE']

    @babel.localeselector
    def get_locale():
        return app.config['LOCALE']

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('404.html'), 404

    app.register_blueprint(views)

    if autoinit:
        blohg.init_repo(revision_id)

    return app

Example 31

Project: autologin Source File: server.py
@app.route("/", methods=["GET", "POST"])
def index():
    """
    Main app route.
    Hosts form used for testing autologin.
    User can submit credentials and URL,
    authenticated cookies returned.
    Also makes a request using extracted cookies,
    saves the source and allows you to view in browser.
    Useful for checking whether login was successful.
    """
    from flask import request
    form = LoginForm(request.form)
    auto_login = AutoLogin()
    login_cookies = None
    login_links = None
    filename = None
    # Process form submission
    if request.method == 'POST' and form.validate():
        url = form.url.data
        username = form.username.data
        password = form.password.data
        msg = ('Login requested for {url} with username={username} '
               'and password={password}'.format(
                   url=url, username=username, password=password))
        # Attempt login
        try:
            login_cookie_jar = auto_login.auth_cookies_from_url(
                url, username, password)
        except AutoLoginException as e:
            flash(e, 'danger')
        else:
            # If we've extracted some cookies,
            # use them to request a page and download html source
            # for viewing in browser,
            login_cookies = login_cookie_jar.__dict__
            error, filename = download_page(form.url.data, login_cookie_jar)
            if error:
                flash(error, 'danger')
            else:
                flash(msg, 'success')
    else:
        flash_errors(form)
    return render_template(
        'index.html',
        form=form,
        login_cookies=login_cookies,
        login_links=login_links,
        filename=filename
    )

Example 32

Project: sagenb Source File: base.py
@base.route('/openid_profiles', methods=['POST','GET'])
def set_profiles():
    if not g.notebook.conf()['openid']:
        return redirect(url_for('base.index'))

    from sagenb.notebook.challenge import challenge


    show_challenge=g.notebook.conf()['challenge']
    if show_challenge:
        chal = challenge(g.notebook.conf(),
                         is_secure = g.notebook.secure,
                         remote_ip = request.environ['REMOTE_ADDR'])

    if request.method == 'GET':
        if 'openid_response' in session:
            from sagenb.notebook.misc import valid_username_chars
            re_invalid_username_chars = re.compile('[^(%s)]' % valid_username_chars)
            openid_resp = session['openid_response']
            if openid_resp.fullname is not None:
                openid_resp.fullname = re.sub(re_invalid_username_chars, '_', openid_resp.fullname)
            template_dict={}
            if show_challenge:
                template_dict['challenge_html'] = chal.html()

            return render_template('html/accounts/openid_profile.html', resp=openid_resp,
                                   challenge=show_challenge, **template_dict)
        else:
            return redirect(url_for('base.index'))


    if request.method == 'POST':
        if 'openid_response' in session:
            parse_dict = {'resp':session['openid_response']}
        else:
            return redirect(url_for('base.index'))

        try:
            resp = session['openid_response']
            username = request.form.get('username')
            from sagenb.notebook.user import User
            from sagenb.notebook.misc import is_valid_username, is_valid_email

            if show_challenge:
                parse_dict['challenge'] = True
                status = chal.is_valid_response(req_args = request.values)
                if status.is_valid is True:
                    pass
                elif status.is_valid is False:
                    err_code = status.error_code
                    if err_code:
                        parse_dict['challenge_html'] = chal.html(error_code = err_code)
                    else:
                        parse_dict['challenge_invalid'] = True
                    raise ValueError("Invalid challenge")
                else:
                    parse_dict['challenge_missing'] = True
                    raise ValueError("Missing challenge")

            if not is_valid_username(username):
                parse_dict['username_invalid'] = True
                raise ValueError("Invalid username")
            if g.notebook.user_manager().user_exists(username):
                parse_dict['username_taken'] = True
                raise ValueError("Pre-existing username")
            if not is_valid_email(request.form.get('email')):
                parse_dict['email_invalid'] = True
                raise ValueError("Invalid email")
            try:
                new_user = User(username, '', email = resp.email, account_type='user')
                g.notebook.user_manager().add_user_object(new_user)
            except ValueError as msg:
                parse_dict['creation_error'] = True
                raise ValueError("Error in creating user\n%s"%msg)
            g.notebook.user_manager().create_new_openid(resp.identity_url, username)
            session['username'] = g.username = username
            session.modified = True
        except ValueError:
            return render_template('html/accounts/openid_profile.html', **parse_dict)
        return redirect(url_for('base.index'))

Example 33

Project: touchandgo Source File: __init__.py
@with_config_dir
def serve(py_exec=None):
    log_set_up(DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python2")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")
    template_path = join(dirname(__file__), "templates")
    app.jinja_loader = FileSystemLoader(template_path)

    def get_torrent(name, season=None, episode=None):
        interface = get_interface()
        path = abspath(__file__)
        dir_path = dirname(path)
        exec_ = join(dir_path, "__init__.py")
        command = '%s %s \"%s\" ' % (py_exec, exec_, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        lock = Lock(LOCKFILE)
        if lock.is_same_file(name, season, episode) and \
                is_process_running(lock.get_pid()):
            data = lock._get_file_data()
            port = data[4]
        else:
            port = get_free_port()
            command += "--daemon --port %s " % port
            log.debug(command)
            process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
            sleep(1)

        redirect_url = "http://%s:%s" % (interface, port)
        serving = False
        while not serving:
            try:
                req = requests.get("%s/status" % redirect_url)
                serving = True
            except requests.ConnectionError, e:
                sleep(1)
        log.info("redirecting to %s" % redirect_url)
        return redirect(redirect_url)

    @app.route("/favicon.ico")
    def favicon():
        return ""

    @app.route("/magnet")
    def magnet():
        # Maybe someone wanted to search the movie "magnet", who knows
        return get_torrent(request.args.get('m', 'magnet'))

    @app.route("/<name>")
    @app.route("/<name>/<season>/<episode>")
    def redirect_to(name, season=None, episode=None):
        log.info("Requesting %s %s %s", name, season, episode)
        return get_torrent(name, season, episode)

    @app.route("/l/<name>/<season>/<episode>")
    @app.route("/l/<name>/<season>/<episode>/")
    def list_(name, season, episode):
        url = "http://%s:5000/%s/%s" % (get_interface(), name, season)
        episode = int(episode)

        template = app.jinja_env.get_template("m3u.j2")
        ret = template.render(episodes=range(episode, episode + 10),
                              series=name, season=episode, url=url)
        return Response(response=ret, status=200,
                        mimetype="application/x-mpegurl",
                        content_type="application/x-mpegurl")

    @app.route("/kill")
    def kill_():
        lock = Lock(LOCKFILE)
        try:
            kill(lock.get_pid(), signal.SIGQUIT)
        except Exception, e:
            pass
        return "OK"

    @app.route("/")
    def main():
        series = []
        keys = []
        items = History.many(sorted="-date,-season,-episode")

        # Filter duplicate entries in the history list
        for item in items:
            key = (item.name, item.season is not None)
            if key not in keys:
                series.append(item)
                keys.append(key)

        return render_template("main.html", items=series, magnet=request.args.get('m', ''))

    app.debug = True
    kill_()
    app.run(host="0.0.0.0")

Example 34

Project: guides-cms Source File: views.py
def render_article_view(request_obj, article, only_visible_by_user=None):
    """
    Render article view

    :param request_obj: Request object
    :param article: Article object to render view for
    :param branch: Branch of article to read
    :param only_visible_by_user: Name of user that is allowed to view article
                                 or None to allow anyone to read it
    """

    g.review_active = True
    login = session.get('login', None)
    collaborator = session.get('collaborator', False)

    recently_saved = request.args.get('saved', 0)
    status = request.args.get('status', PUBLISHED)

    publish_statuses = ()

    if login == article.branch or article.author_name == login:
        allow_delete = True

        # Regular users cannot directly publish
        publish_statuses = (IN_REVIEW, DRAFT)
    else:
        allow_delete = False

    # Collaborators aka editors can use all statuses
    if collaborator:
        publish_statuses = STATUSES

    # Use http as canonical protocol for url to avoid having two separate
    # comment threads for an article. Disqus uses this variable to save
    # comments.
    canonical_url = request_obj.base_url.replace('https://', 'http://')

    article_identifier = article.first_commit
    redirect_url = None
    if article_identifier is None:
        # Backwards compatability for disqus comments. We didn't track the
        # first commit before version .2 and all disqus comments used the
        # slugified title for the unique id.  Disqus doesn't allow for changing
        # this so we're stuck with it if we want to maintain the comments
        # before version .2.
        article_identifier = utils.slugify(article.title)

        # Hack to save our old social shares. The po.st service doesn't handle
        # 301 redirects so need to share with the old url to keep the counts.
        redirect_url = u'%s/review/%s' % (app.config['DOMAIN'],
                                          article_identifier)
    else:
        # Use full domain for redirect_url b/c this controls the po.st social
        # sharing numbers.  We want these numbers to stick with the domain
        # we're running on so counts go with us.
        redirect_url = filters.url_for_article(article,
                                               base_url=app.config['DOMAIN'])

    # Filter out the current branch from the list of branches
    branches = [b for b in article.branches if b != article.branch]

    # Always include a link to original article if this is a branched version
    if article.branch != u'master':
        branches.append([article.author_name, u'master'])

    g.header_white = True

    user = models.find_user(article.author_name)
    if only_visible_by_user is not None and only_visible_by_user != user.login:
        return redirect(url_for('index'))

    # Don't allow comments when we're testing b/c disqus will create a
    # 'discussion' for every article and there's no way to delete them!
    allow_comments = not app.debug

    allow_set_featured = collaborator and (
                         models.allow_set_featured_article()) and (
                         article.published)

    hearted = False
    if login is not None:
        hearted = models.has_hearted(article.stacks[0], article.title, login)

    return render_template('article.html',
                           article=article,
                           hearted=hearted,
                           allow_delete=allow_delete,
                           canonical_url=canonical_url,
                           article_identifier=article_identifier,
                           branches=branches,
                           allow_set_featured=allow_set_featured,
                           user=user,
                           publish_statuses=publish_statuses,
                           redirect_url=redirect_url,
                           allow_comments=allow_comments,
                           recently_saved=recently_saved,
                           status=status)

Example 35

Project: bepasty-server Source File: display.py
    def get(self, name):
        if not may(READ):
            raise Forbidden()
        try:
            item = current_app.storage.openwrite(name)
        except (OSError, IOError) as e:
            if e.errno == errno.ENOENT:
                raise NotFound()
            raise

        with item as item:
            complete = item.meta['complete']
            if not complete and not may(ADMIN):
                error = 'Upload incomplete. Try again later.'
                return render_template('error.html', heading=item.meta['filename'], body=error), 409

            if item.meta['locked'] and not may(ADMIN):
                raise Forbidden()

            if delete_if_lifetime_over(item, name):
                raise NotFound()

            def read_data(item):
                # reading the item for rendering is registered like a download
                data = item.data.read(item.data.size, 0)
                item.meta['timestamp-download'] = int(time.time())
                return data

            size = item.meta['size']
            ct = item.meta['type']
            try:
                get_lexer_for_mimetype(ct)
                use_pygments = True
                ct_pygments = ct
            except NoPygmentsLexer:
                if ct.startswith('text/'):
                    # seems like we found a text type not supported by pygments
                    # use text/plain so we get a display with line numbers
                    use_pygments = True
                    ct_pygments = 'text/plain'
                else:
                    use_pygments = False

            if rendering_allowed(ct, size, use_pygments, complete):
                if ct.startswith('text/x-bepasty-'):
                    # special bepasty items - must be first, don't feed to pygments
                    if ct == 'text/x-bepasty-list':
                        names = read_data(item).decode('utf-8').splitlines()
                        files = sorted(file_infos(names), key=lambda f: f['filename'])
                        rendered_content = Markup(render_template('filelist_tableonly.html', files=files))
                    else:
                        rendered_content = u"Can't render this content type."
                elif ct.startswith('image/'):
                    src = url_for('bepasty.download', name=name)
                    rendered_content = Markup(u'<img src="%s" alt="the image" width="800">' % src)
                elif ct.startswith('audio/'):
                    src = url_for('bepasty.download', name=name)
                    alt_msg = u'html5 audio element not supported by your browser.'
                    rendered_content = Markup(u'<audio controls src="%s">%s</audio>' % (src, alt_msg))
                elif ct.startswith('video/'):
                    src = url_for('bepasty.download', name=name)
                    alt_msg = u'html5 video element not supported by your browser.'
                    rendered_content = Markup(u'<video controls src="%s">%s</video>' % (src, alt_msg))
                elif ct in ['application/pdf', 'application/x-pdf', ]:
                    src = url_for('bepasty.inline', name=name)
                    link_txt = u'Click to see PDF'
                    rendered_content = Markup(u'<a href="%s">%s</a>' % (src, link_txt))
                elif use_pygments:
                    text = read_data(item)
                    # TODO we don't have the coding in metadata
                    try:
                        text = text.decode('utf-8')
                    except UnicodeDecodeError:
                        # well, it is not utf-8 or ascii, so we can only guess...
                        text = text.decode('iso-8859-1')
                    lexer = get_lexer_for_mimetype(ct_pygments)
                    formatter = CustomHtmlFormatter(linenos='table', lineanchors="L",
                                                    lineparagraphs="L", anchorlinenos=True)
                    rendered_content = Markup(highlight(text, lexer, formatter))
                else:
                    rendered_content = u"Can't render this content type."
            else:
                if not complete:
                    rendered_content = u"Rendering not allowed (not complete). Is it still being uploaded?"
                else:
                    rendered_content = u"Rendering not allowed (too big?). Try download"

            return render_template('display.html', name=name, item=item,
                                   rendered_content=rendered_content)

Example 36

Project: pybossa Source File: account.py
@blueprint.route('/<name>/update', methods=['GET', 'POST'])
@login_required
def update_profile(name):
    """
    Update user's profile.

    Returns Jinja2 template.

    """
    user = user_repo.get_by_name(name)
    if not user:
        return abort(404)
    ensure_authorized_to('update', user)
    show_passwd_form = True
    if user.twitter_user_id or user.google_user_id or user.facebook_user_id:
        show_passwd_form = False
    usr = cached_users.get_user_summary(name)
    # Extend the values
    user.rank = usr.get('rank')
    user.score = usr.get('score')
    if request.form.get('btn') != 'Profile':
        update_form = UpdateProfileForm(formdata=None, obj=user)
    else:
        update_form = UpdateProfileForm(obj=user)
    update_form.set_locales(current_app.config['LOCALES'])
    avatar_form = AvatarUploadForm()
    password_form = ChangePasswordForm()

    title_msg = "Update your profile: %s" % user.fullname

    if request.method == 'POST':
        # Update user avatar
        succeed = False
        if request.form.get('btn') == 'Upload':
            succeed = _handle_avatar_update(user, avatar_form)
        # Update user profile
        elif request.form.get('btn') == 'Profile':
            succeed = _handle_profile_update(user, update_form)
        # Update user password
        elif request.form.get('btn') == 'Password':
            succeed = _handle_password_update(user, password_form)
        # Update user external services
        elif request.form.get('btn') == 'External':
            succeed = _handle_external_services_update(user, update_form)
        # Otherwise return 415
        else:
            return abort(415)
        if succeed:
            return redirect(url_for('.update_profile', name=user.name))
        else:
            return render_template('/account/update.html',
                                   form=update_form,
                                   upload_form=avatar_form,
                                   password_form=password_form,
                                   title=title_msg,
                                   show_passwd_form=show_passwd_form)

    return render_template('/account/update.html',
                           form=update_form,
                           upload_form=avatar_form,
                           password_form=password_form,
                           title=title_msg,
                           show_passwd_form=show_passwd_form)

Example 37

Project: galah Source File: _view_assignment.py
@app.route("/assignments/<assignment_id>/")
@account_type_required(("student", "teacher", "teaching_assistant"))
def view_assignment(assignment_id):
    simple_archive_form = SimpleArchiveForm()

    # Convert the assignment in the URL into an ObjectId
    try:
        id = ObjectId(assignment_id)
    except InvalidId:
        logger.info("Invalid Assignment ID requested.")

        abort(404)

    # Retrieve the assignment
    try:
        assignment = Assignment.objects.get(id = id)
    except Assignment.DoesNotExist:
        logger.info("Non-extant ID requested.")

        abort(404)

    assignment.apply_personal_deadlines(current_user)

    # Get all of the submissions for this assignment
    submissions = list(
        Submission.objects(
            user = current_user.id,
            assignment = id
        ).order_by(
            "-most_recent",
            "-timestamp"
        )
    )

    # Get student submissions if being viewed as teacher
    student_submissions = []
    students = []
    if current_user.account_type in ["teacher", "teaching_assistant"]:
        students = list(
            User.objects(
                classes = assignment.for_class,
                account_type = "student"
            ).order_by(
                "-email"
            )
        )

        student_submissions = list(
            Submission.objects(
                user__in = [i.email for i in students],
                assignment = assignment_id,
                most_recent = True
            )
        )

    test_results = list(
        TestResult.objects(
            id__in = [i.test_results for i in submissions if i.test_results]
        )
    )

    # Match test results to submissions
    for i in submissions:
        for j in test_results:
            if i.test_results == j.id:
                i.test_results_obj = j

    # Current time to be compared to submission test_request_timestamp
    now = datetime.datetime.now()

    # Flag to set refresh trigger if user is waiting on test results
    wait_and_refresh = False

    # Add the pretty version of each submissions timestamp
    for i in submissions:
        i.timestamp_pretty = pretty_time(i.timestamp)
        i.status = "Submitted"

        # If the user submitted a test request and there aren't any results
        if (i.test_request_timestamp and not i.test_results):
            timedelta = now - i.test_request_timestamp
            i.show_resubmit = (timedelta > config["STUDENT_RETRY_INTERVAL"])
            if not i.show_resubmit:
                i.status = "Waiting for test results..."
            else:
                i.status = "Test request timed out"
        elif (i.test_results and i.test_results_obj.failed):
            i.status = "Tests Failed"
            i.show_resubmit = True
        elif (i.test_results and not i.test_results_obj.failed):
            i.status = "Tests Completed"

    wait_and_refresh = \
        any(i.status == "Waiting for test results..." for i in submissions)

    return render_template(
        "assignment.html",
        now = datetime.datetime.today(),
        create_time_element = create_time_element,
        assignment = assignment,
        submissions = submissions,
        simple_archive_form = simple_archive_form,
        wait_and_refresh = wait_and_refresh,
        new_submissions = [v for k, v in get_flashed_messages(with_categories = True) if k == "new_submission"],
        view_as_teacher = (current_user.account_type in ["teacher",
                                                         "teaching_assistant"]),
        students = students,
        student_submissions = student_submissions,
        enumerate = enumerate
    )

Example 38

Project: groundstation Source File: __init__.py
def make_airship(station):
    app = Flask(__name__)
    app.has_signing_key = False

    def set_signing_key(self, keyname):
        app.has_signing_key = True
        self.private_crypto_adaptor = \
                station.get_private_crypto_adaptor(keyname)
    app.set_signing_key = lambda key: set_signing_key(app, key)

    def _update_gref(gref, tips, parents):
        if app.has_signing_key:
            tips = map(lambda tip: Tip(tip.tip, app.private_crypto_adaptor.sign(tip.tip)), tips)
        station.update_gref(gref, tips, parents)

    @app.route("/")
    def index():
        return render_template("index.html",
                channels_json=channels_json(station, True),
                current_time=time.time())

    @app.route("/channels")
    def list_channels():
        return channels_json(station)

    @app.route("/channels/new", methods=['PUT'])
    def new_channel():
        channel = request.form.keys()[0]
        station.create_channel(channel)
        return ""

    @app.route("/grefs/<channel>")
    def list_grefs(channel):
        return grefs_json(station, channel)

    @app.route("/gref/<channel>/<path:identifier>")
    def fetch_gref(channel, identifier):
        crypto_adaptor = station.get_crypto_adaptor()
        adaptor = GithubReadAdaptor(station, channel)
        gref = Gref(station.store, channel, identifier)
        log.info("Trying to fetch channel: %s identifier: %s" %
                (channel, identifier))
        marshalled_thread = adaptor.get_issue(gref, crypto_adaptor=crypto_adaptor)
        root_obj = marshalled_thread["roots"].pop()
        root = root_obj.as_json()
        root["hash"] = oid2hex(pygit2.hash(root_obj.as_object()))

        response = []

        while marshalled_thread["thread"]:
            node = marshalled_thread["thread"].pop()
            data = json.loads(node.data)
            data["parents"] = list(node.parents)
            data["hash"] = oid2hex(pygit2.hash(node.as_object()))
            response.append(data)
        return jsonate({"content": response,
                        "root": root,
                        "tips": marshalled_thread["tips"],
                        "signatures": marshalled_thread["signatures"]}, False)

    @app.route("/gref/<channel>/<path:identifier>", methods=['POST'])
    def update_gref(channel, identifier):
        # adaptor = github_protocol.GithubWriteAdaptor(station, channel)
        gref = Gref(station.store, channel, identifier)
        # Ugly type coercion
        user = request.form["user"]
        body = request.form["body"]
        parents = map(str, json.loads(request.form["parents"]))
        payload = {
                "type": "comment",
                "id": None,
                "body": body,
                "user": user
                }
        update_object = UpdateObject(parents, json.dumps(payload))
        oid = station.write(update_object.as_object())
        _update_gref(gref, [Tip(oid,"")], parents)
        return jsonate({"response": "ok"}, False)

    @app.route("/grefs/<channel>", methods=['PUT'])
    def create_gref(channel):
        def _write_object(obj):
            return station.write(obj.as_object())

        name = request.form["name"]
        protocol = request.form["protocol"]
        user = request.form["user"]
        body = request.form["body"]
        title = request.form["title"]
        gref = Gref(station.store, channel, name)
        root = RootObject(name, channel, protocol)
        root_oid = _write_object(root)

        _title = UpdateObject([root_oid], json.dumps({
            "type": "title",
            "id": None,
            "body": title,
            "user": user
            }))
        title_oid = _write_object(_title)

        _body = UpdateObject([title_oid], json.dumps({
            "type": "body",
            "id": None,
            "body": body
            }))
        body_oid = _write_object(_body)

        _update_gref(gref, [Tip(body_oid, "")], [])
        return ""



    return app

Example 39

Project: plenario Source File: views.py
@views.route('/workers')
def workers():
    q = session.query(Workers).all()
    workerlist = [row.__dict__ for row in q]
    now = datetime.now()
    nominal = 0
    loaded = 0
    dead = 0

    for worker in workerlist:

        if not worker["job"]:
            continue

        job = json.loads(get_job(worker["job"]).get_data())

        if job.get("error"):
            worker["status"] = "dead"
            worker["jobinfo"] = {
                "status": "TIMED OUT",
                "workers": "",
                "queuetime": "",
                "worktime": "",
                "endpoint": ""
            }
            continue

        if job["status"]["meta"].get("lastStartTime"):
            diff = dateutil.relativedelta.relativedelta(
                now,
                datetime.strptime(job["status"]["meta"]["lastStartTime"],
                                  "%Y-%m-%d %H:%M:%S.%f"))

        else:
            diff = dateutil.relativedelta.relativedelta(now,
                                                    datetime.strptime(job["status"]["meta"]["startTime"],
                                                                          "%Y-%m-%d %H:%M:%S.%f"))
        worker["jobinfo"] = {
            "status": job["status"]["status"],
            "workers": ", ".join(job["status"]["meta"]["workers"]),
            "queuetime": job["status"]["meta"]["queueTime"],
            "worktime": " {}h {}m {}s".format(diff.hours, diff.minutes, diff.seconds).replace(
                " 0h ", "  ").replace(" 0m ", " ")[1:],
            "endpoint": job["request"]["endpoint"]
        }

        lastseen = (now - datetime.strptime(worker["timestamp"], "%Y-%m-%d %H:%M:%S.%f")).total_seconds()
        if lastseen > 1200 or worker.get("status"):
            worker["status"] = "dead"
            dead += 1
        elif lastseen > 300:
            worker["status"] = "overload"
            loaded += 1
        elif lastseen > 60:
            worker["status"] = "load"
            loaded += 1
        else:
            worker["status"] = "nominal"
            nominal += 1

        diff = dateutil.relativedelta.relativedelta(now, datetime.fromtimestamp(worker["uptime"]))
        worker["humanized_uptime"] = " {}d {}h {}m {}s".format(
            diff.days, diff.hours, diff.minutes, diff.seconds).replace(
            " 0d ", "  ").replace(" 0h ", " ").replace(" 0m ", " ")[1:]
        diff = dateutil.relativedelta.relativedelta(datetime.fromtimestamp(lastseen),
                                                    datetime.fromtimestamp(0))
        worker["lastseen"] = " {}d {}h {}m {}s ago".format(
            diff.days, diff.hours, diff.minutes, diff.seconds).replace(
            " 0d ", "  ").replace(" 0h ", " ").replace(" 0m ", " ")[1:]

    workerlist.sort(key=lambda worker: worker["name"])
    jobs = job_queue.attributes['ApproximateNumberOfMessages']
    workercounts = {
        "total": len(workerlist),
        "nominal": nominal,
        "loaded": loaded,
        "dead": dead
    }
    return render_template('workers.html', workers=workerlist,
                           workercounts=workercounts, queuelength=jobs, overload=(jobs>=8))

Example 40

Project: ldapass Source File: ldapass.py
@app.route('/', methods=['GET', 'POST'])
def index():
    error = None
    form = EmailForm(request.form)
    if request.method == 'GET':
        return render_template('index.html', error=error, form=form)

    elif request.method == 'POST':
        if form.validate():
            ldap_uri = 'ldap://{addr}:{port}'.format(
                addr=conf.get('ldap', 'addr'), port=conf.get('ldap', 'port'))
            try:
                ldap.set_option(
                    ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                l = ldap.initialize(
                    ldap_uri, trace_level=conf.get('app', 'ldap_debug'))
                l.start_tls_s()
            except ldap.LDAPError as error:
                return render_template('index.html', error=error, form=form)
            try:
                search_filter = 'mail={mail}'.format(mail=form.mail.data)
                ldap_result_id = l.search(
                    conf.get('ldap', 'basedn'), ldap.SCOPE_SUBTREE,
                    search_filter, None)
            except ldap.LDAPError as error:
                return render_template('index.html', error=error, form=form)
            result_type, result_data = l.result(ldap_result_id, 0)
            if len(result_data) == 1:
                link_id = '{uuid}-{account}'.format(
                    uuid=str(uuid.uuid4()),
                    account=form.mail.data.split('@')[0]
                )

                db_conn = sqlite3.connect(conf.get('app', 'database'))
                db_curs = db_conn.cursor()
                db_curs.execute(
                    "SELECT id FROM mails WHERE mail='{mail}'".format(
                        mail=form.mail.data))
                db_data = db_curs.fetchall()
                if len(db_data) == 0:
                    db_curs.execute(
                        "INSERT INTO mails (mail, link_id, created) VALUES \
                        ('{mail}', '{link_id}', '{created}')".format(
                        mail=form.mail.data,
                        link_id=link_id,
                        created=datetime.datetime.now()
                    ))
                    flash('Email containing password reset url has been sent \
                        to {mail}'.format(mail=form.mail.data))
                else:
                    db_curs.execute(
                        "DELETE FROM mails WHERE mail='{mail}'".format(
                            mail=form.mail.data))
                    db_curs.execute(
                        "REPLACE INTO mails (mail, link_id, created) VALUES \
                        ('{mail}', '{link_id}', '{created}')".format(
                        mail=form.mail.data,
                        link_id=link_id,
                        created=datetime.datetime.now()
                    ))
                    flash('Email containing password reset url has been sent \
                        to {mail}. Previous reset urls have been \
                        invalidated.'.format(mail=form.mail.data))
                db_conn.commit()
                db_conn.close()

                reset_url = 'http://{hostname}:{port}/reset/{link_id}'.format(
                    hostname=conf.get('app', 'hostname'),
                    port=conf.get('app', 'listen_port'),
                    link_id=link_id
                )
                send_mail(form.mail.data, reset_url)
            elif len(result_data) > 1:
                error = 'More than one user found with email address of \
                    {mail}. Plese, get in touch with LDAP administration \
                    team.'.format(mail=form.mail.data)
            else:
                error = 'No user found with email address of {mail}. Plese, \
                    get in touch with LDAP administration.'.format(
                    mail=form.mail.data)
            return render_template('index.html', error=error, form=form)

        else:
            error = 'The mail address you have filled is invalid.'
            return render_template('index.html', error=error, form=form)

Example 41

Project: zipnish Source File: views.py
@index.route('/', methods=['GET'])
def index():
    # read GET values
    spanName = request.args.get('spanName')

    lastServiceName = request.cookies.get('last-serviceName')
    serviceName = request.args.get('serviceName') or '' if lastServiceName is None else unquote(lastServiceName)

    timestamp = request.args.get('timestamp')
    limit = request.args.get('limit') or 10

    formSubmitted = True

    if timestamp is None or timestamp.strip() == '':
        formSubmitted = False
        timestamp = int(time.time() * 1000000)

    # get database engine connection
    connection = db.engine.connect()

    # query results
    traceResults = None

    # query database based on query parameters if service is given
    if formSubmitted:
        # query results that would be sent over to view
        traceResults = []

        # find all traces to which related to this service
        query = "SELECT DISTINCT trace_id \
                FROM zipnish_annotations "

        # where
        whereQuery = ''

        if serviceName is not None and len(serviceName) > 0:
            whereQuery += " service_name = '%s' " % serviceName

        if spanName is not None and len(spanName) > 0 and spanName != 'all':
            if len(whereQuery) > 0:
                whereQuery += " AND "
            whereQuery += " span_name = '%s' " % spanName

        if timestamp is not None and len(timestamp) > 0:
            if len(whereQuery) > 0:
                whereQuery += " AND "
            whereQuery += " a_timestamp < %s " % timestamp

        # attach where clause only if there is a criteria
        if len(whereQuery) > 0:
            whereQuery = " WHERE %s " % whereQuery
            query += whereQuery

        # order by
        orderByQuery = " ORDER BY a_timestamp DESC"
        query += orderByQuery

        # limit search results
        limitQuery = ""

        if limit is not None:
            limitQuery += " LIMIT 0, %s" % limit
            query += limitQuery

        traceIds = []
        resultTraceIds = connection.execute(query)

        for row in resultTraceIds:
            traceIds.append(row['trace_id'])

        if len(traceIds) > 0:
            # find the number of DISTINCT spans, that above service connects with
            query = "SELECT COUNT(DISTINCT span_id) as spanCount, parent_id, created_ts, trace_id \
                    FROM zipnish_spans \
                    GROUP BY trace_id \
                    HAVING \
                    trace_id IN (%s) \
                    ORDER BY created_ts DESC" \
                    % (",".join(str(traceId) for traceId in traceIds))
            result = connection.execute(query)

            for row in result:
                trace = {}

                trace['serviceName'] = serviceName
                trace['spanCount'] = row['spanCount']
                trace['trace_id_long'] = row['trace_id']
                trace['trace_id'] = GenerateTraceURLId(row['trace_id'])

                startTime = (int(row['created_ts']) / 1000000)
                trace['startTime'] = time.strftime('%m-%d-%YT%H:%M:%S%z', time.gmtime(startTime))

                servicesQuery = "SELECT service_name, `value`, a_timestamp \
                        FROM zipnish_annotations \
                        WHERE trace_id = %s AND \
                        `value` IN ('cs', 'sr', 'ss', 'cr') \
                        ORDER BY service_name ASC" % (row['trace_id'])
                servicesResult = connection.execute(servicesQuery)

                services = {}
                service = None

                for serviceRow in servicesResult:
                    if serviceRow['service_name'] not in services:
                        services[serviceRow['service_name']] = {}
                        service = services[serviceRow['service_name']]
                        service['count'] = 0

                    if serviceRow['value'] == 'sr':
                        service['count'] += 1

                    service[serviceRow['value']] = serviceRow['a_timestamp']

                duration = 0
                serviceDuration = 0
                serviceDurations = []

                minTimestamp = sys.maxint
                maxTimestamp = 0

                selectedServiceDuration = 0
                totalTraceDuration = 0

                for key in services:
                    service = services[key]
                    if 'cs' in service:
                        minTimestamp = min(service['cr'], minTimestamp)
                        maxTimestamp = max(service['cs'], maxTimestamp)

                        serviceDuration = service['cr'] - service['cs']
                    else:
                        minTimestamp = min(service['sr'], minTimestamp)
                        maxTimestamp = max(service['ss'], maxTimestamp)

                        serviceDuration = service['ss'] - service['sr']

                    if serviceName == key:
                        selectedServiceDuration = serviceDuration

                    totalTraceDuration = max(totalTraceDuration, serviceDuration)

                    # service duration
                    serviceDurations.append({
                            'name': key,
                            'count': service['count'],
                            'duration': serviceDuration
                        })

                # total duration for a trace
                trace['duration'] = selectedServiceDuration

                # service durations

                # sort service durations
                serviceDurations = sorted(serviceDurations, key=lambda x: x['name'])

                trace['serviceDurations'] = serviceDurations

                #trace['serviceTimestampMin'] = minTimestamp
                #trace['serviceTimestampMax'] = maxTimestamp

                trace['servicesTotalDuration'] = '{:.3f}'.format(totalTraceDuration / 1000.0)

                selectedServicePercentage = float(float(selectedServiceDuration) / float(totalTraceDuration)) * 100.0
                trace['selectedServicePercentage'] = '{:.2f}'.format(selectedServicePercentage)

                traceResults.append( trace )

        #return json.dumps(traceResults)

    # populate services
    services = []
    result = connection.execute("SELECT DISTINCT service_name FROM zipnish_annotations")

    for row in result:
        services.append( row['service_name'] )

    spans = []

    if serviceName:
        query = "SELECT DISTINCT span_name FROM zipnish_annotations WHERE service_name='%s'" % serviceName
        result = connection.execute(query)

        for row in result:
            spans.append( row['span_name'] )

    if len(spans) > 0:
        spans.insert(0, 'all')

    # close connection
    connection.close()

    return render_template('index.html', \
            results=traceResults, \
            services=services, spans=spans, \
            get_SpanName=spanName, get_ServiceName=serviceName, \
            get_Timestamp=timestamp, get_Limit=limit)

Example 42

Project: pjuu Source File: views.py
@users_bp.route('/settings', methods=['GET', 'POST'])
@users_bp.route('/settings/profile', methods=['GET', 'POST'])
@login_required
def settings_profile():
    """Allows users to customize their profile direct from this view."""
    # Create the form and initialize the `select` field this can not be done
    # in the template.
    form = ChangeProfileForm(
        feed_pagination_size=(current_user.get('feed_pagination_size') or
                              app.config.get('FEED_ITEMS_PER_PAGE')),
        replies_pagination_size=(current_user.get('replies_pagination_size') or
                                 app.config.get('REPLIES_ITEMS_PER_PAGE')),
        alerts_pagination_size=(current_user.get('alerts_pagination_size') or
                                app.config.get('ALERT_ITEMS_PER_PAGE')),
        homepage=current_user.get('homepage', ''),
        location=current_user.get('location', '')
    )

    if request.method == 'POST':
        form = ChangeProfileForm()

        if form.validate():
            # If there is an uploaded File pass it on else pass nothing
            if form.upload.data:
                # Pass the BytesIO stream to the backend.
                upload = form.upload.data.stream
            else:
                upload = None

            # Update the current user in the session
            current_user['about'] = form.about.data
            current_user['hide_feed_images'] = form.hide_feed_images.data

            current_user['feed_pagination_size'] = \
                int(form.feed_pagination_size.data)
            current_user['replies_pagination_size'] = \
                int(form.replies_pagination_size.data)
            current_user['alerts_pagination_size'] = \
                int(form.alerts_pagination_size.data)

            # Sort order but be 1 or -1 due to MongoDB requirements
            if form.reply_sort_order.data:
                reply_sort_order = 1
            else:
                reply_sort_order = -1

            current_user['reply_sort_order'] = reply_sort_order

            current_user['homepage'] = form.homepage.data
            current_user['location'] = form.location.data
            current_user['default_permission'] = int(form.permission.data)

            # Update the user in the database
            user = update_profile_settings(
                current_user.get('_id'),
                about=form.about.data,
                hide_feed_images=form.hide_feed_images.data,
                feed_size=form.feed_pagination_size.data,
                replies_size=form.replies_pagination_size.data,
                alerts_size=form.alerts_pagination_size.data,
                reply_sort_order=reply_sort_order,
                homepage=form.homepage.data,
                location=form.location.data,
                upload=upload,
                permission=form.permission.data
            )

            # Reload the current_user
            current_user.update(user)

            flash('Your profile has been updated', 'success')
        else:
            flash('Oh no! There are errors in your form', 'error')

    return render_template('settings_profile.html', form=form)

Example 43

Project: viaduct Source File: activity.py
@blueprint.route('/create/', methods=['GET', 'POST'])
@blueprint.route('/edit/<int:activity_id>/', methods=['GET', 'POST'])
def create(activity_id=None):
    # Need to be logged in + actie group or admin etc.
    if not ModuleAPI.can_write('activity'):
        return abort(403)

    if activity_id:

        activity = Activity.query.get(activity_id)

        if not activity:
            abort(404)

        title = _("Edit") + " " + str(activity.name)
    else:
        activity = Activity()
        title = _('Create activity')

    form = CreateForm(request.form, activity)

    if request.method == 'POST':
        if form.validate_on_submit():

            picture = activity.picture

            form.populate_obj(activity)

            file = request.files['picture']

            if file.filename and allowed_file(file.filename):
                picture = secure_filename(file.filename)

                if not activity.picture and os.path.isfile(
                        os.path.join('app/static/activity_pictures', picture)):
                    flash(_('An image with this name already exists.'),
                          'danger')
                    return render_template('activity/create.htm',
                                           activity=activity,
                                           form=form,
                                           title=title)

                fpath = os.path.join('app/static/activity_pictures', picture)
                file.save(fpath)
                os.chmod(fpath, 0o644)

                # Remove old picture
                if activity.picture:
                    try:
                        os.remove(os.path.join(
                            'app/static/activity_pictures',
                            activity.picture))
                    except OSError:
                        print(_('Cannot delete image, image does not exist') +
                              ": " + str(activity.picture))

            elif not picture:
                picture = None

            activity.venue = 1  # Facebook ID location, not used yet  # noqa

            # Set a custom_form if it actually exists
            form_id = int(form.form_id.data)
            if form_id == 0:
                form_id = None

            activity.form_id = form_id

            activity.picture = picture
            activity.owner_id = current_user.id

            if activity.id and activity.google_event_id:
                flash(_('The activity has been edited.'), 'success')

                google.update_activity(activity.google_event_id,
                                       form.nl_name.data,
                                       form.nl_description.data,
                                       form.location.data,
                                       form.start_time.data.isoformat(),
                                       form.end_time.data.isoformat())
            else:
                flash(_('The activity has been created.'), 'success')

                google_activity = google.insert_activity(
                    form.nl_name.data, form.nl_description.data,
                    form.location.data, form.start_time.data.isoformat(),
                    form.end_time.data.isoformat())

                if google_activity:
                    activity.google_event_id = google_activity['id']

            db.session.add(activity)
            db.session.commit()

            return redirect(url_for('activity.get_activity',
                                    activity_id=activity.id))
        else:
            flash_form_errors(form)

    return render_template('activity/create.htm', activity=activity, form=form,
                           title=title)

Example 44

Project: sopython-site Source File: __init__.py
def create_app(info=None):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('sopy.config')
    app.config.from_pyfile('config.py', True)

    app.cli.add_command(alembic_cli, 'db')

    app.jinja_env.trim_blocks = True
    app.jinja_env.lstrip_blocks = True

    alembic.init_app(app)
    babel.init_app(app)
    db.init_app(app)

    from sopy.ext import views

    views.init_app(app)

    from sopy import auth, tags, se_data, canon, salad, wiki, pages, admin, transcript, spoiler

    app.register_blueprint(auth.bp, url_prefix='/auth')
    app.register_blueprint(tags.bp, url_prefix='/tags')
    app.register_blueprint(se_data.bp, url_prefix='/se_data')
    app.register_blueprint(canon.bp, url_prefix='/canon')
    app.register_blueprint(salad.bp, url_prefix='/salad')
    app.register_blueprint(wiki.bp, url_prefix='/wiki')
    app.register_blueprint(pages.bp, url_prefix='/pages')
    app.register_blueprint(admin.bp, url_prefix='/admin')
    app.register_blueprint(transcript.bp, url_prefix='/transcript')
    app.register_blueprint(spoiler.bp, url_prefix='/spoiler')

    @app.route('/')
    def index():
        return render_template('index.html')

    app.add_url_rule('/favicon.ico', None, app.send_static_file, defaults={'filename': 'favicon.ico'})
    app.add_url_rule('/robots.txt', None, app.send_static_file, defaults={'filename': 'robots.txt'})

    @app.errorhandler(403)
    def forbidden(e):
        return render_template('errors/403.html'), 403

    @app.errorhandler(404)
    def not_found(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('errors/500.html'), 500

    @app.route('/pycon2016')
    def pycon2016():
        return redirect(url_for('wiki.detail', title='PyCon US 2016'))

    if not app.debug:
        handler = logging.StreamHandler(sys.stderr)
        handler.setLevel(logging.ERROR)
        app.logger.addHandler(handler)

    return app

Example 45

Project: runbook Source File: views.py
@monitor_blueprint.route('/dashboard/monitors/<cname>', methods=['GET', 'POST'])
def addcheck_page(cname):
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/monitors/' + cname
        tmpl = 'monitors/create.html'
        data['js_bottom'] = ['monitors/monitorlist.js', 'monitors/base.js',]
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            # Get list of reactions and validate that there are some
            data['reactions'] = user.getReactions(g.rdb_conn)
            # Proces the form
            cform = __import__(
                "monitorforms." + cname, globals(), locals(), ['CheckForm'], -1)
            form = cform.CheckForm(request.form)
            if form.__contains__("timer"):
                form.timer.choices = data['choices']
            reactchoices = []
            for key in data['reactions'].keys():
                reactchoices.append(
                    (data['reactions'][key]['id'],
                        data['reactions'][key]['name']))
            form.reactions.choices = reactchoices
            if request.method == 'POST':
                if form.validate():
                    monitor = Monitor()
                    monitor.config = app.config
                    monitor.name = form.name.data
                    monitor.ctype = cname
                    monitor.uid = user.uid
                    monitor.status = "queued"
                    monitor.url = None
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                    monitor.data = tmpdata

                    # Check if the user already exceeds their limit
                    if monitor.count(user.uid, g.rdb_conn) < data['limit']:
                        # Create the monitor if all checks out
                        results = monitor.createMonitor(g.rdb_conn)
                    else:
                        if data['upgraded']:
                            payment = __import__("payments." + user.payments, globals(),
                                                 locals(), ['Payments'], -1)
                            subscription = payment.Payments(user=user, config=app.config, rdb=g.rdb_conn)
                            quantity = user.subplans + 1
                            results = subscription.adjust(quantity=quantity)
                            if results:
                                results = monitor.createMonitor(g.rdb_conn)
                        else:
                            results = "toomany"

                    if results == "exists":
                        print("/dashboard/monitors/{0} - \
                              Monitor already exists".format(cname))
                        flash('{0} seems to already exist. \
                              Try using a different name.'.format(
                              monitor.name), 'danger')
                    elif results is False:
                        print("/dashboard/monitors/{0} - \
                            Monitor creation failed".format(cname))
                        flash('Could not create monitor.', 'danger')
                    elif results == 'toomany':
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Too many health checks',
                            1)
                        flash('You have too many monitors. \
                              Please upgrade your plan or clean \
                              up old ones.', 'danger')
                        print("/dashboard/monitors/{0} - \
                              Monitor creation failed: toomany".format(cname))
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Monitor Added', 1)
                        print("/dashboard/monitors/%s - \
                              Monitor creation successful") % cname
                        flash('Monitor "{0}" successfully added.'.format(
                            monitor.name), 'success')
                        newmonitor = Monitor()
                        newmonitor.config = app.config
                        newmonitor.get(results, g.rdb_conn)
                        if newmonitor.uid == user.uid:
                            data['monitor'] = {
                                'cid': newmonitor.cid,
                                'name': newmonitor.name,
                                'uid': newmonitor.uid,
                                'ctype': newmonitor.ctype,
                                'url': newmonitor.url,
                                'data': newmonitor.data
                            }
                else:
                    print("/dashboard/monitors/{0} - \
                          Monitor creation failed: Form invalid".format(cname))
                    flash('Form is not valid.', 'danger')
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 46

Project: pjuu Source File: views.py
@posts_bp.route('/<username>/<post_id>', methods=['GET'])
def view_post(username, post_id):
    """Displays a post along with its comments paginated. I am not sure if this
    should be here or in the 'posts' app.

    .. note: Viewable to the public if the post is public!
    """
    if not check_post(get_uid(username), post_id):
        return abort(404)

    # Get post and comments for the current page
    _post = get_post(post_id)

    # Stop a reply from ever being shown here
    if 'reply_to' in _post:
        return abort(404)

    _user = get_user(get_uid(username))

    # Only get the permission if the post is not owned by the current user
    if current_user:
        current_user_id = current_user.get('_id')
    else:
        current_user_id = None

    permission = get_user_permission(_user.get('_id'), current_user_id)

    if permission < _post.get('permission', k.PERM_PUBLIC):
        return abort(403)

    # Pagination
    page = handle_page(request)

    # Handle explicit sort order
    # Fall back to user default else default
    sort = request.args.get('sort', None)
    if sort is None:
        if current_user:
            sort = current_user.get('reply_sort_order', -1)
        else:
            sort = -1
    else:
        try:
            sort = 1 if int(sort) > 0 else -1
        except ValueError:
            if current_user:
                sort = current_user.get('reply_sort_order', -1)
            else:
                sort = -1

    # Get the page sizes taking in to account non-logged in users
    if current_user:
        page_size = current_user.get(
            'replies_pagination_size',
            app.config.get('REPLIES_ITEMS_PER_PAGE', 25)
        )
    else:
        page_size = app.config.get('REPLIES_ITEMS_PER_PAGE', 25)

    pagination = get_replies(post_id, page, page_size, sort)

    post_form = PostForm()
    return render_template('view_post.html', post=_post,
                           pagination=pagination, post_form=post_form,
                           sort=sort)

Example 47

Project: plivohelper-python Source File: phonemenu.py
@response_server.route('/phonemenu/', methods=['GET', 'POST'])
def phonemenu():
    # Default destination
    destination = 'default'
    # Get destination from url query string:
    # 'node' : destination
    # 'Digits' : input digits from user
    if request.method == 'POST':
        node = request.args.get('node', None)
        dtmf = request.form.get('Digits', -1)
    else:
        node = request.args.get('node', None)
        dtmf = request.args.get('Digits', -1)
    if not node:
        node = 'default'
    try:
        digits = int(dtmf)
    except ValueError:
        digits = -1

    if digits >= 0:
        try:
            destination = web[node][digits]
        except (KeyError, IndexError):
            destination = 'default'

    print "Destination %s" % str(destination)
    print "Digits %s" % str(digits)

    r = plivohelper.Response()

    if destination == 'hours':
        r.addSpeak("Initech is open Monday through Friday, 9am to 5pm")
        r.addSpeak("Saturday, 10am to 3pm and closed on Sundays")
    elif destination == 'location':
        g = r.addGetDigits(numDigits=1,
                   action='http://127.0.0.1:5000/phonemenu/?node=location')
        g.addSpeak("For directions from the East Bay, press 1")
        g.addSpeak("For directions from San Jose, press 2")
    elif destination == 'east-bay':
        r.addSpeak("Take BART towards San Francisco / Milbrae. Get off on Powell Street. Walk a block down 4th street")
    elif destination == 'san-jose':
        r.addSpeak("Take Cal Train to the Milbrae BART station. Take any Bart train to Powell Street")
    elif destination == 'duck':
        r.addPlay("http://127.0.0.1:5000/static/duck.mp3")
    elif destination == 'receptionist':
        r.addSpeak("Please wait while we connect you")
        g = r.addDial()
        g.addNumber("NNNNNNNN")
    else:
        # default menu
        g = r.addGetDigits(numDigits=1,
                           action='http://127.0.0.1:5000/phonemenu/?node=default')
        g.addSpeak("Hello and welcome to the Initech Phone Menu")
        g.addSpeak("For business hours, press 1")
        g.addSpeak("For directions, press 2")
        g.addSpeak("To hear a duck quack, press 3")
        g.addSpeak("To speak to a receptionist, press 0")

    print "RESTXML Response => %s" % r
    return render_template('response_template.xml', response=r)

Example 48

Project: arch-home Source File: index.py
Function: fetch_feed
@app.route('/feed/<name>')
def fetch_feed(name):
    if name == 'news':
        rss_feed = 'https://www.archlinux.org/feeds/news/'
        cache_file = './cache/news'
    elif name == 'pkgs_x64':
        rss_feed = 'https://www.archlinux.org/feeds/packages/x86_64/'
        cache_file = './cache/pkgs_x64'
    elif name == 'pkgs_x86':
        rss_feed = 'https://www.archlinux.org/feeds/packages/i686/'
        cache_file = './cache/pkgs_x86'
    else:
        abort(404)

    def write_feed(cache_file, feed):
        data = (time.time(), feed)
        pickle.dump(data, open(cache_file, "wb"))
        return

    expire_cache = 3600
    mtime = None

    try:
        cache = pickle.load(open(cache_file, 'rb'))
    except (IOError, KeyError) as e:
        # nothing to do, this is expecte
        pass
    else:
        mtime, cached_feed = cache

    # we must have a valid cache file
    if mtime:
        now = time.time()
        diff = int(now - mtime)

        # if cache file is stale
        if diff > expire_cache:
            feed = feedparser.parse(rss_feed, etag=cached_feed.etag)
            # feed has not been modified, update mtime so we don't check again
            if feed.status == 304:
                feed = cached_feed
                # write updated mtime to pickle file
                write_feed(cache_file, feed)
            # feed has been modified, lets update our cache
            else:
                # write new data pickle file
                write_feed(cache_file, feed)
        # cache is not stale, use cache
        else:
            feed = cached_feed
    # no cache file, that is okay
    else:
        feed = feedparser.parse(rss_feed)
        # write data to pickle file
        write_feed(cache_file, feed)

    if name == 'news':
        items = [(x.title, x.link) for x in feed.entries]
        return render_template('news.html', news=items)
    elif 'pkgs' in name:
        pkgs = []
        for x in feed.entries[:MAX_PKGS]:
            full, short = format_pkg_name(x.title)
            pkgs.append({'name':full, 'short_name':short, 'cat':x.category, 'link':x.link, 'summary':x.summary})
        return render_template('pkgs.html', pkgs=pkgs)

    return 'None'

Example 49

Project: runbook Source File: views.py
@reaction_blueprint.route(
    '/dashboard/edit-reactions/<rname>/<rid>', methods=['GET', 'POST'])
def editreact_page(rname, rid):
    ''' This is a generic edit page for reactions '''
    verify = verifyLogin(
        app.config['SECRET_KEY'], app.config['COOKIE_TIMEOUT'], request.cookies)
    if verify:
        user = User()
        user.config = app.config
        user.get('uid', verify, g.rdb_conn)
        data = startData(user)
        data['active'] = 'dashboard'
        data['url'] = '/dashboard/edit-reactions/' + rname + '/' + rid
        tmpl = 'reactions/create.html'
        data['js_bottom'] = ['reactions/base.js', ]
        data['edit'] = True
        # Check Users Status
        if user.status != "active":
            data['url'] = '/dashboard/mod-subscription'
            tmpl = 'member/mod-subscription.html'
        else:
            reform = __import__(
                "reactionforms." + rname, globals(),
                locals(), ['ReactForm'], -1)
            form = reform.ReactForm(request.form)
            reaction = Reaction()
            reaction.config = app.config
            # If Edit get information
            reaction.get("rid", rid, g.rdb_conn)
            if reaction.uid == user.uid:
                data['reaction'] = {
                    'rid': reaction.rid,
                    'name': reaction.name,
                    'trigger': reaction.trigger,
                    'frequency': reaction.frequency,
                    'uid': reaction.uid,
                    'rtype': reaction.rtype,
                    'data': reaction.data
                }
            data['selects'] = []
            for item in form.__iter__():
                if item.type == "SelectField" or \
                        item.type == "SelectMultipleField":
                    item.default = data['reaction']['data'][item.name]
            tmpl = 'reactions/create.html'
            if request.method == 'POST':
                if form.validate():
                    reaction2 = Reaction()
                    reaction2.config = app.config
                    reaction2.rid = reaction.rid
                    reaction2.name = form.name.data
                    reaction2.trigger = form.trigger.data
                    reaction2.frequency = form.frequency.data
                    reaction2.lastrun = reaction.lastrun
                    reaction2.uid = user.uid
                    reaction2.rtype = reaction.rtype
                    tmpdata = {}
                    for item in form.__iter__():
                        tmpdata[item.name] = item.data
                        if item.type == "SelectField" or\
                                item.type == "SelectMultipleField":
                            item.default = item.data
                    reaction2.data = tmpdata

                    data['reaction'] = {
                        'rid': reaction2.rid,
                        'name': reaction2.name,
                        'trigger': reaction2.trigger,
                        'frequency': reaction2.frequency,
                        'uid': reaction2.uid,
                        'rtype': reaction2.rtype,
                        'data': reaction2.data
                    }
                    if reaction.uid == user.uid:
                        results = reaction2.editReaction(g.rdb_conn)
                    else:
                        results = False
                        print("/dashboard/reactions/{0} - \
                            Reaction edit failed: not owner".format(rname))
                        flash("It doesn't appear that you own this reaction.",
                              'danger')
                    if results == "exists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction seems to already exist. \
                              Try using a different name.', 'danger')
                    elif results == "edit noexists":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: exists".format(rname))
                        flash('This reaction can not be edited \
                              as it does not exist.', 'danger')
                    elif results == "edit true":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit successful".format(rname))
                        flash('Reaction successfully edited.', 'success')
                    elif results == "edit failed":
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Reaction not successfully edited.', 'danger')
                    elif results is False:
                        print("/dashboard/reactions/{0} - \
                              Reaction edit failed: unknown".format(rname))
                        flash('Could not create reaction.', 'danger')
                    else:
                        stathat.ez_count(
                            app.config['STATHAT_EZ_KEY'],
                            app.config['ENVNAME'] + ' Reaction Added', 1)
                        print("/dashboard/reactions/{0} - \
                              Reaction edit success".format(rname))
                        flash('Reaction "{0}" successfully \
                              added.'.format(reaction2.name), 'danger')
                else:
                    print("/dashboard/reactions/{0} - \
                          Reaction edit failed: form invalid".format(rname))
                    flash('Form is not valid.', 'danger')
        form.process()
        page = render_template(tmpl, data=data, form=form)
        return page
    else:
        flash('Please Login.', 'warning')
        return redirect(url_for('user.login_page'))

Example 50

Project: translator Source File: __init__.py
@main_module.route('/')
@main_module.route('/tr/<translation_id>')
def index(translation_id=None):
    """The main page."""

    if request.host == 'translator.suminb.com':
        return redirect('http://better-translator.com')

    # NOTE: Do not use HTTP GET parameters 'sl', 'tl', 'm' and 't'. These are
    # reserved for special purposes.

    # FIXME: The following values must exist in other pages as well
    user_agent = request.headers.get('User-Agent', [])
    is_android = 'Android' in user_agent
    is_iphone = 'iPhone' in user_agent
    is_msie = 'MSIE' in user_agent

    context = dict(
        version=__version__,
        locale=get_locale(),
        is_android=is_android,
        is_iphone=is_iphone,
        is_mobile=is_android or is_iphone,
        is_msie=is_msie,
        language_options=language_options_html(),
        debug=os.environ.get('DEBUG', None),
    )

    tresponse = None

    translation_id = translation_id or request.args.get('tr', None)

    #if translation_id != None:
    #    tresponse = TranslationResponse.fetch(id_b62=translation_id)

    if translation_id is not None and tresponse is None:
        return redirect(url_for('main.index'))

    if tresponse is not None:
        translation = tresponse.serialize()
        translation['original_text'] = tresponse.request.original_text
        #translation['translated_text_dictlink'] = link_dictionary(
        #translation['translated_text'], translation['source'], translation['target'])

        context['og_description'] = tresponse.request.original_text
        context['translation'] = json.dumps(translation)
    else:
        context['og_description'] = _('app-description-text')

    return render_template('index.html', **context)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4