Python flask.escape() Examples

The following are code examples for showing how to use flask.escape(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Blogging   Author: gouthambs   File: views.py    MIT License 6 votes vote down vote up
def _store_form_data(blog_form, storage, user, post, escape_text=True):
    title = blog_form.title.data
    text = escape(blog_form.text.data) if escape_text \
        else blog_form.text.data
    tags = blog_form.tags.data.split(",")
    draft = blog_form.draft.data
    user_id = user.get_id()
    current_datetime = datetime.datetime.utcnow()
    post_date = post.get("post_date", current_datetime)
    last_modified_date = datetime.datetime.utcnow()
    post_id = post.get("post_id")
    pid = storage.save_post(title, text, user_id, tags, draft=draft,
                            post_date=post_date,
                            last_modified_date=last_modified_date,
                            post_id=post_id)
    return pid 
Example 2
Project: python-docs-samples   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 6 votes vote down vote up
def hello_name(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    request_args = request.args

    if request_args and "name" in request_args:
        name = request_args["name"]
    else:
        name = "World"
    return "Hello {}!".format(flask.escape(name)) 
Example 3
Project: python-docs-samples   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 6 votes vote down vote up
def hello_http(request):
    """HTTP Cloud Function.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'name' in request_json:
        name = request_json['name']
    elif request_args and 'name' in request_args:
        name = request_args['name']
    else:
        name = 'World'
    return 'Hello {}!'.format(escape(name))
# [END functions_helloworld_http]


# [START functions_helloworld_pubsub] 
Example 4
Project: d4-core   Author: D4-project   File: Sensor.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def register_sensor(req_dict):
    sensor_uuid = req_dict.get('uuid', None)
    hmac_key = req_dict.get('hmac_key', None)
    user_id = req_dict.get('mail', None)
    third_party = req_dict.get('third_party', None)
    # verify uuid
    if not is_valid_uuid_v4(sensor_uuid):
        return ({"status": "error", "reason": "Invalid uuid"}, 400)
    sensor_uuid = sensor_uuid.replace('-', '')
    # sensor already exist
    if r_serv_db.exists('metadata_uuid:{}'.format(sensor_uuid)):
        return ({"status": "error", "reason": "Sensor already registred"}, 409)

    # hmac key
    if not hmac_key:
        return ({"status": "error", "reason": "Mandatory parameter(s) not provided"}, 400)
    else:
        hmac_key = escape(hmac_key)
        if len(hmac_key)>100:
            hmac_key=hmac_key[:100]
    if third_party:
        third_party = True

    res = _register_sensor(sensor_uuid, hmac_key, user_id=user_id, third_party=third_party, description=None)
    return res 
Example 5
Project: 0x0   Author: lachs0r   File: fhost.py    ISC License 6 votes vote down vote up
def notfound(e):
    return u"""<pre>Process {0} stopped
* thread #1: tid = {0}, {1:#018x}, name = '{2}'
    frame #0:
Process {0} stopped
* thread #8: tid = {0}, {3:#018x} fhost`get(path='{4}') + 27 at fhost.c:139, name = 'fhost/responder', stop reason = invalid address (fault address: 0x30)
    frame #0: {3:#018x} fhost`get(path='{4}') + 27 at fhost.c:139
   136   get(SrvContext *ctx, const char *path)
   137   {{
   138       StoredObj *obj = ctx->store->query(shurl_debase(path));
-> 139       switch (obj->type) {{
   140           case ObjTypeFile:
   141               ctx->serve_file_id(obj->id);
   142               break;
(lldb) q</pre>
""".format(os.getpid(), id(app), "fhost", id(get), escape(request.path)), e.code 
Example 6
Project: Publ   Author: PlaidWeb   File: markdown.py    MIT License 6 votes vote down vote up
def _render_image(self, spec, show, container_args, alt_text=None):
        """ Render an image specification into an <img> tag """

        try:
            path, image_args, title = image.parse_image_spec(spec)
        except Exception as err:  # pylint: disable=broad-except
            LOGGER.exception("Got error on spec %s: %s", spec, err)
            return ('<span class="error">Couldn\'t parse image spec: ' +
                    '<code>{}</code> {}</span>'.format(flask.escape(spec),
                                                       flask.escape(str(err))))

        composite_args = {**container_args, **image_args}

        try:
            img = image.get_image(path, self._search_path)
        except Exception as err:  # pylint: disable=broad-except
            LOGGER.exception("Got error on image %s: %s", path, err)
            return ('<span class="error">Error loading image {}: {}</span>'.format(
                flask.escape(spec), flask.escape(str(err))))

        return img.get_img_tag(title,
                               alt_text,
                               **composite_args,
                               _show_thumbnail=show,
                               _mark_rewritten=True) 
Example 7
Project: schort   Author: sqozz   File: schort.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def short(shortLink=""):
	if request.method == "GET":
		if shortLink:
			noauto = shortLink[-1] == "+"
			if noauto: shortLink = shortLink[:-1]
			conn = sqlite3.connect("data/links.sqlite")
			c = conn.cursor()
			result = c.execute('SELECT longLink FROM links WHERE shortLink=?', (shortLink, )).fetchone()
			conn.close()
			if result:
				url = result[0]
				parsedUrl = urlparse(url)
				if parsedUrl.scheme == "":
					url = "http://" + url

				if "resolve" in request.args:
					return escape(url)
				else:
					if noauto:
						url = str(escape(url))
						html = "<a href=" + url + ">" + url + "</a>"
						return html
					else:
						return redirect(url, code=301) # Redirect to long URL saved in the database
			else:
				return render_template("index.html", name=shortLink, message="Enter long URL for "+ request.url_root + shortLink+":", message_type="info") # Custom link page
		else:
			return render_template("index.html", name=shortLink) # Landing page
	elif request.method == "POST": # Someone submitted a new link to short
		longUrl = request.form.get("url", "")
		wishId = request.form.get("wishId")
		if len(longUrl) <= 0:
			abort(400)

		databaseId = insertIdUnique(longUrl, idToCheck=wishId)
		return request.url_root + databaseId # Short link in plain text 
Example 8
Project: flask-sqlalchemy-web   Author: ypmc   File: start.py    MIT License 5 votes vote down vote up
def index():
    logger.debug("index page")
    logger.debug("cookie name %s" % request.cookies.get('username'))

    if 'username' in session:
        logger.debug("login user is %s" % flask_login.current_user)
        logger.debug('Logged in as %s' % escape(session['username']))
        return render_template('index.html', name=session['username'])
    else:
        logger.debug("you are not logged in")
        return render_template('login.html') 
Example 9
Project: no-frills-online-notepad   Author: schollz   File: server.py    MIT License 5 votes vote down vote up
def test_message(message):
	#message['data'] = escape(message['data'])
	print message
	cursor = mysql.connect().cursor()
	cursor.execute("SELECT * from text where sitename='" + message['page'] + "' and version="+message['version'])
	data = cursor.fetchone()
	if data is None:
		print "Inserting into database"
		conn = mysql.connect()
		cursor = conn.cursor()
		query = '''INSERT INTO text (sitename,document,date_modified,date_created,version) VALUES (%s,%s,NOW(),NOW(),1)'''
		cursor.execute(query,(message['page'],message['data'],))
		conn.commit()
	else:
		currentSize = len(data[2])
		newSize = len(message['data'])
		currentVersion = int(data[5])
		if currentSize-newSize>10: # if deleting a lot of stuff, archive the old version
			print "archiving old version"
			currentVersion +=1
			conn = mysql.connect()
			cursor = conn.cursor()
			query = '''INSERT INTO text (sitename,document,date_modified,date_created,version) VALUES (%s,%s,NOW(),NOW(),%s)'''
			cursor.execute(query,(message['page'],message['data'],str(currentVersion),))
			conn.commit()
		else:
			print "updating into database, old version"
			conn = mysql.connect()
			cursor = conn.cursor()
			query = '''UPDATE text set document =%s, date_modified=NOW() where sitename=%s and version=%s'''
			cursor.execute(query,(message['data'],message['page'],str(currentVersion)))
			conn.commit()
		
	emit('newtitle', {'success':True,'data':'None'}) 
Example 10
Project: learning-python   Author: Akagi201   File: single.py    MIT License 5 votes vote down vote up
def test_session():
    if 'username' in session:
        return 'logged in as %s' % escape(session['username'])
    return redirect(url_for('login')) 
Example 11
Project: autoseamless   Author: alawibaba   File: flask_frontend.py    GNU General Public License v3.0 5 votes vote down vote up
def index():
    if 'username' not in session:
        return redirect(url_for('login'))
    user = User.query.filter_by(username=session['username']).first()
    return '''Welcome %s.<br/><br/>
<form action=%s method=post>
Your favorites:<br/><textarea name=favorites cols=80 rows=20>%s</textarea><br/>
Order time:<br/><input name=minute type=text value=%d:%02d /><br/>
Don't order tomorrow: <input type=checkbox name=disabled value=True %s /><br/>
<input type=submit name=save /> <br/>
</form> <a href="%s">logout</a> <br/><br/>Messages:<br/>%s''' % (escape(user.username), url_for('update_settings'), user.favorites, user.minute/60, user.minute%60, {True: "checked", False: ""}[user.disabled], url_for('logout'), ("<hr/>").join(map(lambda x: "%s <pre style='white-space: pre-wrap;'>%s</pre>" % (x.created_at.strftime("%m/%d/%Y %H:%M %p"), x.message), Message.query.filter_by(user_id=user.id).order_by(Message.created_at.desc()).limit(5)))) 
Example 12
Project: amazon-elasticache-samples   Author: aws-samples   File: example-3.py    Apache License 2.0 5 votes vote down vote up
def index():
    if 'username' in session:
        username = escape(session['username'])

        visits = store.hincrby(username, 'visits', 1)

        store.expire(username, 10)

        return '''
            Logged in as {0}.<br>
            Visits: {1}
        '''.format(username, visits)

    return 'You are not logged in' 
Example 13
Project: amazon-elasticache-samples   Author: aws-samples   File: example-2.py    Apache License 2.0 5 votes vote down vote up
def index():
    if 'username' in session:
        username = escape(session['username'])

        visits = store.hincrby(username, 'visits', 1)

        return '''
            Logged in as {0}.<br>
            Visits: {1}
        '''.format(username, visits)

    return 'You are not logged in' 
Example 14
Project: amazon-elasticache-samples   Author: aws-samples   File: example-1.py    Apache License 2.0 5 votes vote down vote up
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in' 
Example 15
Project: amazon-elasticache-samples   Author: aws-samples   File: example-4.py    Apache License 2.0 5 votes vote down vote up
def index():
    if 'username' in session:
        username = escape(session['username'])

        store = SessionStore(username, REDIS_URL)

        visits = store.incr('visits')

        return '''
            Logged in as {0}.<br>
            Visits: {1}
        '''.format(username, visits)

    return 'You are not logged in' 
Example 16
Project: bbotte.github.io   Author: bbotte   File: message_board.py    Apache License 2.0 5 votes vote down vote up
def nl2br_filters(s):
    return escape(s).replace('\n', Markup('</br>'))

#添加过滤器,评论时间显示到了毫秒 
Example 17
Project: pythonture   Author: yonetici   File: blog.py    GNU General Public License v3.0 5 votes vote down vote up
def about():
    return render_template("about.html")
# @app.route("/article/<id>")
# def detail(id):
#     try:
#         return 'Post %s' % escape id
#     except:
#         return 'hatalı url girdiniz.' 
Example 18
Project: pythonture   Author: yonetici   File: blog.py    GNU General Public License v3.0 5 votes vote down vote up
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(username)
#Makale Ekle 
Example 19
Project: miv-tracker   Author: team-miv   File: views.py    MIT License 5 votes vote down vote up
def pending_data(status, event_id):
    """Return server side data."""
    # defining columns
    columns = []
    columns.append(ColumnDT('id'))
    columns.append(ColumnDT('ioc'))
    columns.append(ColumnDT('itype.name'))
    columns.append(ColumnDT('control.name'))
    columns.append(ColumnDT('comment'))
    columns.append(ColumnDT('enrich'))
    columns.append(ColumnDT('first_seen'))

    base_query = db.session.query(Indicator).join(Control).join(Itype)

    if status == 'pending':
        columns.append(ColumnDT('event_id'))
        columns.append(ColumnDT('event.name'))
        query = base_query.join(Event).filter(Indicator.pending == True)
    elif status == 'search':
        columns.append(ColumnDT('event_id'))
        columns.append(ColumnDT('event.name'))
        query = base_query.join(Event).filter(Indicator.pending == False)
    elif status == 'approved':
        columns.append(ColumnDT('last_seen'))
        columns.append(ColumnDT('rel_list'))
        query = base_query.filter(Indicator.event_id == event_id).filter(Indicator.pending == False )
    else:
        query = base_query.filter(Indicator.pending == True)

    rowTable = DataTables(request.args, Indicator, query, columns)

    #xss catch just to be safe
    res = rowTable.output_result()
    for item in res['data']:
        for k,v in item.iteritems():
            item[k] = escape(v)

    return jsonify(res) 
Example 20
Project: miv-tracker   Author: team-miv   File: views.py    MIT License 5 votes vote down vote up
def event_data(status):
    """Return server side data."""
    # defining columns
    columns = []
    columns.append(ColumnDT('id'))
    columns.append(ColumnDT('name'))
    columns.append(ColumnDT('status.name'))
    columns.append(ColumnDT('source.name'))
    columns.append(ColumnDT('tlp.name'))
    columns.append(ColumnDT('confidence'))
    columns.append(ColumnDT('created'))
    columns.append(ColumnDT('indicator_count'))

    base_query = db.session.query(Event).join(Source).join(Tlp).join(Status)

    if status in ['New', 'Open', 'Resolved']:
        query = base_query.filter(Status.name == status)
    else:
        query = base_query

    rowTable = DataTables(request.args, Event, query, columns)

    #xss catch just to be safe
    res = rowTable.output_result()
    for item in res['data']:
        for k,v in item.iteritems():
            item[k] = escape(v)

    return jsonify(res)


###
# API Calls
### 
Example 21
Project: arxiv-search   Author: arXiv   File: highlighting.py    MIT License 5 votes vote down vote up
def _escape(value: str) -> str:
    """
    Escape anything that isn't part of highlighting.

    Ideally, we'd use bleach.clean to do this for us. Unfortunately, it just
    gets too tripped up on equation content to use it reliably. Sometimes it
    throws exceptions when it hits equations that look like (but are not)
    HTML, and other times it panics. Since we really only have one tag-pair
    that we care to preserve, this approach works well enough for our purposes.
    """
    tag_o = HIGHLIGHT_TAG_OPEN
    tag_c = HIGHLIGHT_TAG_CLOSE
    _new = ""
    i = 0
    while True:
        i_o = value[i:].index(tag_o) if tag_o in value[i:] else None
        i_c = value[i:].index(tag_c) if tag_c in value[i:] else None
        if i_o is None and i_c is None:
            _new += str(escape(value[i:]))
            break
        if i_o is not None and i_c is not None:
            if i_o < i_c:
                _sub = str(escape(value[i:i + i_o])) + tag_o
                i += i_o + len(tag_o)
            elif i_c < i_o:
                _sub = str(escape(value[i:i + i_c])) + tag_c
                i += i_c + len(tag_c)
        elif i_o is not None and i_c is None:
            _sub = str(escape(value[i:i + i_o])) + tag_o
            i += i_o + len(tag_o)
        elif i_c is not None and i_o is None:
            _sub = str(escape(value[i:i + i_c])) + tag_c
            i += i_c + len(tag_c)
        _new += _sub
    return _new 
Example 22
Project: dash-docs   Author: plotly   File: server.py    MIT License 5 votes vote down vote up
def redirect_to_enterprise_part(subpath):
    return redirect('/dash-enterprise/{}'.format(escape(subpath)), code=301) 
Example 23
Project: dash-docs   Author: plotly   File: server.py    MIT License 5 votes vote down vote up
def redirect_table_part(subpath):
    return redirect('/datatable/{}'.format(escape(subpath)), code=301) 
Example 24
Project: dash-docs   Author: plotly   File: server.py    MIT License 5 votes vote down vote up
def redirect_daq_part(subpath):
    return redirect('/dash-daq/{}'.format(escape(subpath)), code=301)

# normalized components 
Example 25
Project: python-docs-samples   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 5 votes vote down vote up
def hello_content(request):
    """ Responds to an HTTP request using data from the request body parsed
    according to the "content-type" header.
    Args:
        request (flask.Request): The request object.
        <http://flask.pocoo.org/docs/1.0/api/#flask.Request>
    Returns:
        The response text, or any set of values that can be turned into a
        Response object using `make_response`
        <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>.
    """
    content_type = request.headers['content-type']
    if content_type == 'application/json':
        request_json = request.get_json(silent=True)
        if request_json and 'name' in request_json:
            name = request_json['name']
        else:
            raise ValueError("JSON is invalid, or missing a 'name' property")
    elif content_type == 'application/octet-stream':
        name = request.data
    elif content_type == 'text/plain':
        name = request.data
    elif content_type == 'application/x-www-form-urlencoded':
        name = request.form.get('name')
    else:
        raise ValueError("Unknown content type: {}".format(content_type))
    return 'Hello {}!'.format(escape(name))
# [END functions_http_content]


# [START functions_http_methods] 
Example 26
Project: ds-study-group   Author: study-groups   File: boxcox.py    MIT License 5 votes vote down vote up
def py2web(py):
    py_json = json.dumps(py.tolist())
    strtype= type(py)
    str = "<pre>"
    str += "py2web called with py:<br>"
    str += "type: {arg}\n".format(arg=escape(strtype))
    str += "shape: {shape})\n".format(shape=escape(py.shape))
    str += "{arg}".format(arg=py)
    str +="</pre>"
    return str; 
Example 27
Project: d4-core   Author: D4-project   File: Flask_server.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def set_uuid_hmac_key():
    uuid_sensor = request.args.get('uuid')
    user = request.args.get('redirect')
    key = request.args.get('key')
    hmac_key = escape(key)
    if len(hmac_key)>100:
        hmac_key=hmac_key[:100]
    redis_server_metadata.hset('metadata_uuid:{}'.format(uuid_sensor), 'hmac_key', hmac_key)
    if user:
        return redirect(url_for('uuid_management', uuid=uuid_sensor))


# demo function 
Example 28
Project: ostip   Author: kx499   File: views.py    MIT License 5 votes vote down vote up
def pending_data(status, event_id):
    """Return server side data."""
    # defining columns
    columns = []
    columns.append(ColumnDT('id'))
    columns.append(ColumnDT('ioc'))
    columns.append(ColumnDT('itype.name'))
    columns.append(ColumnDT('control.name'))
    columns.append(ColumnDT('comment'))
    columns.append(ColumnDT('enrich'))
    columns.append(ColumnDT('first_seen'))

    base_query = db.session.query(Indicator).join(Control).join(Itype)

    if status == 'pending':
        columns.append(ColumnDT('event_id'))
        columns.append(ColumnDT('event.name'))
        query = base_query.join(Event).filter(Indicator.pending == True)
    elif status == 'search':
        columns.append(ColumnDT('event_id'))
        columns.append(ColumnDT('event.name'))
        query = base_query.join(Event).filter(Indicator.pending == False)
    elif status == 'approved':
        columns.append(ColumnDT('last_seen'))
        columns.append(ColumnDT('rel_list'))
        query = base_query.filter(Indicator.event_id == event_id).filter(Indicator.pending == False )
    else:
        query = base_query.filter(Indicator.pending == True)

    rowTable = DataTables(request.args, Indicator, query, columns)

    #xss catch just to be safe
    res = rowTable.output_result()
    for item in res['data']:
        for k,v in item.iteritems():
            item[k] = escape(v)

    return jsonify(res) 
Example 29
Project: ostip   Author: kx499   File: views.py    MIT License 5 votes vote down vote up
def event_data(status):
    """Return server side data."""
    # defining columns
    columns = []
    columns.append(ColumnDT('id'))
    columns.append(ColumnDT('name'))
    columns.append(ColumnDT('status.name'))
    columns.append(ColumnDT('source.name'))
    columns.append(ColumnDT('tlp.name'))
    columns.append(ColumnDT('confidence'))
    columns.append(ColumnDT('created'))
    columns.append(ColumnDT('indicator_count'))

    base_query = db.session.query(Event).join(Source).join(Tlp).join(Status)

    if status in ['New', 'Open', 'Resolved']:
        query = base_query.filter(Status.name == status)
    else:
        query = base_query

    rowTable = DataTables(request.args, Event, query, columns)

    #xss catch just to be safe
    res = rowTable.output_result()
    for item in res['data']:
        for k,v in item.iteritems():
            item[k] = escape(v)

    return jsonify(res)


###
# API Calls
### 
Example 30
Project: BlackSheep   Author: RobertoPrevato   File: flask_app.py    MIT License 5 votes vote down vote up
def hello_world():
    name = request.args.get('name', 'World')
    return f'Hello, {escape(name)}!', 200, {'Content-Type': 'text/plain'} 
Example 31
Project: Publ   Author: PlaidWeb   File: markdown.py    MIT License 5 votes vote down vote up
def blockcode(self, text, lang):
        """ Pass a code fence through pygments """
        if lang and self._config.get('highlight_syntax', 'True'):
            try:
                lexer = pygments.lexers.get_lexer_by_name(lang, stripall=True)
            except pygments.lexers.ClassNotFound:
                lexer = None

            if lexer:
                formatter = pygments.formatters.HtmlFormatter()  # pylint: disable=no-member
                return pygments.highlight(text, lexer, formatter)

        return '\n<div class="highlight"><pre>{}</pre></div>\n'.format(
            flask.escape(text.strip())) 
Example 32
Project: trending-on-the-bay   Author: randomecho   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def search():
    keyword = request.args.get('keyword')
    results = ebay.search_sold(keyword)
    stats = sell_stats.generate_stats(results)

    return render_template("search.html",
                           keyword=escape(keyword),
                           results=results,
                           stats=stats) 
Example 33
Project: hipfrog   Author: wardweistra   File: glassfrog_tests.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_configure(self, mock_getCircles, mock_HipchatApiHandler, mock_getInstallationFromJWT):
        mock_installation = self.defaultInstallation(set_glassfrogToken=False)
        assert mock_installation.glassfrogToken is None
        mock_getInstallationFromJWT.return_value = mock_installation

        # Loading of page
        rv = self.app.get('/configure.html', follow_redirects=True,
                          query_string=test_values.mock_jwt_data('bogus'))
        assert b'Glassfrog Token' in rv.data

        # Wrong token
        mock_getCircles.return_value = [401, test_values.mock_401_responsebody['message']]
        rv = self.app.post('/configure.html', follow_redirects=True,
                           data=dict(glassfrogtoken=test_values.mock_glassfrogToken),
                           query_string=test_values.mock_jwt_data('bogus'))
        assert mock_getCircles.called
        assert escape(test_values.mock_401_flash_message) in rv.data.decode('utf-8')

        # Right token
        mock_getCircles.return_value = (200, test_values.mock_circles_message)
        rv = self.app.post('/configure.html', follow_redirects=True,
                           data=dict(glassfrogtoken=test_values.mock_glassfrogToken),
                           query_string=test_values.mock_jwt_data('bogus'))
        assert mock_getCircles.called
        assert escape(strings.configured_successfully_flash) in rv.data.decode('utf-8')
        mock_HipchatApiHandler.return_value.sendMessage.assert_called_with(
            color=strings.succes_color,
            message=strings.configured_successfully,
            installation=mock_installation) 
Example 34
Project: chatschoolette   Author: gorel   File: test_auth.py    MIT License 5 votes vote down vote up
def test_create_user(self):
        username = 'test_create_user'
        email = escape('[email protected]')
        password = 'hunter2'

        user = User(username, email, password)
        db.session.add(user)
        db.session.commit()

        assert user is not None 
Example 35
Project: SWEETer-Cat   Author: DanielAndreasen   File: test_app.py    MIT License 5 votes vote down vote up
def test_publication_titles(publication_response, publication_data, category):
    """Test all the publication titles are present."""
    for paper in publication_data[category]:
        title = escape(paper["title"]).encode('utf-8')
        assert title in publication_response.data 
Example 36
Project: SWEETer-Cat   Author: DanielAndreasen   File: test_app.py    MIT License 5 votes vote down vote up
def test_publication_links(publication_response, publication_data, category):
    """Test all the publication adsabs links are present.

    Test that links are inserted for the title and "read more" sections.
    """
    for paper in publication_data[category]:
        url = escape(paper["adsabs"])
        read_more = '...<a href="{0}" target="_blank"> read more</a>'.format(url)
        title_link = '<a href="{0}" target="_blank">{1}</a>'.format(url, paper["title"])
        assert read_more.encode('utf-8') in publication_response.data
        assert title_link.encode('utf-8') in publication_response.data 
Example 37
Project: SWEETer-Cat   Author: DanielAndreasen   File: test_app.py    MIT License 5 votes vote down vote up
def test_publication_authors(publication_response, publication_data, category):
    """Test all the publication authors are present."""
    for paper in publication_data[category]:
        authors = escape(paper["authors"]).encode('utf-8')
        assert authors in publication_response.data 
Example 38
Project: xl_auth   Author: libris   File: test_collection_view.py    Apache License 2.0 5 votes vote down vote up
def test_user_sees_error_message_if_collection_code_does_not_exist(user, testapp):
    """Show error when attempting to view a permission that does not exist."""
    # Goes to homepage.
    res = testapp.get('/')
    # Fills out login form.
    form = res.forms['loginForm']
    form['username'] = user.email
    form['password'] = 'myPrecious'
    # Submits.
    res = form.submit().follow()
    assert res.status_code is 200
    # Fails to figures out the correct ID for another user.
    res = testapp.get(url_for('collection.view', collection_code='FAKE1')).follow()
    # Sees error message.
    assert escape(_('Collection code "%(code)s" does not exist', code='FAKE1')) in res 
Example 39
Project: d4-core   Author: D4-project   File: Flask_server.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def get_uuid_disk_statistics(uuid_name, date_day='', type='', all_types_on_disk=[], all_stats=True):
    # # TODO: escape uuid_name

    stat_disk_uuid = {}
    uuid_data_directory = os.path.join(data_directory, uuid_name)
    if date_day:
        directory_date = os.path.join(date_day[0:4], date_day[4:6], date_day[6:8])
    all_types_on_disk = {}

    if all_types_on_disk:
        for type in all_types_on_disk:
            if date_day:
                uuid_type_path = os.path.join(uuid_data_directory, type, directory_date)
            else:
                uuid_type_path = os.path.join(uuid_data_directory, type)
            all_types_on_disk[type] = uuid_type_path
    else:
        # Get all types save on disk
        if os.path.isdir(uuid_data_directory):
            for file in os.listdir(uuid_data_directory):
                if date_day:
                    uuid_type_path = os.path.join(uuid_data_directory, file, directory_date)
                else:
                    uuid_type_path = os.path.join(uuid_data_directory, file)
                if os.path.isdir(uuid_type_path):
                    all_types_on_disk[file] = uuid_type_path

    nb_file = 0
    total_size = 0

    for uuid_type in all_types_on_disk:
        nb_file_type = 0
        total_size_type = 0
        for dirpath, dirnames, filenames in os.walk(all_types_on_disk[uuid_type]):
            stat_disk_uuid[uuid_type] = {}
            for f in filenames:
                fp = os.path.join(dirpath, f)
                file_size = os.path.getsize(fp)
                total_size_type += file_size
                total_size += file_size
                nb_file_type += 1
                nb_file += 1
            stat_disk_uuid[uuid_type]['nb_files'] = nb_file_type
            stat_disk_uuid[uuid_type]['total_size'] = total_size_type
    if all_stats:
        stat_all = {}
        stat_all['nb_files'] = nb_file
        stat_all['total_size'] = total_size
        stat_disk_uuid['All'] = stat_all
    return stat_disk_uuid

# ========== ERRORS ============