Python flask.escape() Examples

The following are 30 code examples of flask.escape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask , or try the search function .
Example #1
Source File: user.py    From cve-portal with GNU Affero General Public License v3.0 7 votes vote down vote up
def change_email_request():
    form = form_class.ChangeEmailForm()
    if form.validate_on_submit():
        if current_user.verify_password(form.password.data):
            new_email = escape(form.email.data)
            token = current_user.generate_email_change_token(new_email)
            send_email(new_email,
                       'CVE-PORTAL -- Confirm your email address',
                       '/emails/change_email',
                       user=current_user,
                       token=token)
            syslog.syslog(syslog.LOG_WARNING,
                          "User as requested an email change: Old:" + current_user.email + " New: " + form.email.data)
            flash('An email with instructions to confirm your new email address has been sent to you.', 'info')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid email or password.', 'danger')
    return render_template("auth/change_email.html", form=form) 
Example #2
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def update_username():
    resp = {'msg': 'Username Changed Successfully', 'resp_code': -1}

    if not 'username' in request.form:
        resp['msg'] = 'Incomplete form'
        return jsonify(resp)

    username = escape(request.form['username'].strip().lower())
    username_error = invalid_username(username)

    if username_error:
        resp['msg'] = username_error
        return jsonify(resp)

    if account_db.account_exists(username):
        resp['msg'] = 'Username already exists'
        return jsonify(resp)

    user_id = session['user_id']
    account_db.update_username(user_id, username)

    resp['resp_code'] = 0
    return jsonify(resp) 
Example #3
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def get_note():
    if not ('topic_id' in request.args and 'note_id' in request.args):
        return redirect(url_for('index'))

    user_id = session['user_id']
    topic_id = escape(request.args.get('topic_id'))
    note_id = escape(request.args.get('note_id'))

    if not (profile_db.topic_exists(user_id, topic_id) and profile_db.note_exists(topic_id, note_id)):
        return redirect(url_for('index'))

    user_key = get_user_key()
    topic = profile_db.decrypt_topic(topic_id, user_key, False)
    topic_info = {'topic_id': topic_id, 'topic_name':  topic['topic_name']}

    note = dict(topic_info, **profile_db.decrypt_note(note_id, user_key))

    return render_template('note.html', note=note, PermissionConst=PermissionConst) 
Example #4
Source File: main.py    From python-docs-samples with 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 #5
Source File: main.py    From python-docs-samples with 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 #6
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def save_note():
    resp = {'resp': 'success-msg'}

    if not ('topic_id' in request.form and 'note_id' in request.form and 'content' in request.form):
        return jsonify(resp)

    user_id = session['user_id']
    user_key = get_user_key()
    note_id = escape(request.form['note_id'].strip())
    topic_id = escape(request.form['topic_id'].strip())
    note_content = escape(request.form['content'].strip())

    if not (profile_db.topic_exists(user_id, topic_id) and profile_db.note_exists(topic_id, note_id)):
        return jsonify(resp)

    profile_db.modify_note_content(topic_id, note_id, note_content, user_key)
    return jsonify(resp) 
Example #7
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def delete_note():
    resp = {'resp': 'error-msg'}

    if not ('topic_id' in request.form and 'note_id' in request.form):
        return jsonify(resp)

    user_id = session['user_id']
    note_id = escape(request.form['note_id'])
    topic_id = escape(request.form['topic_id'])

    if not (profile_db.topic_exists(user_id, topic_id) and profile_db.note_exists(topic_id, note_id)):
        return jsonify(resp)

    profile_db.delete_note(topic_id, note_id)

    resp['resp'] = 'success-msg'
    return jsonify(resp) 
Example #8
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def edit_user():
    if not 'id' in request.args:
        return redirect(url_for('admin'))

    user_id = escape(request.args.get('id'))

    if not account_db.user_id_exists(user_id):
        return redirect(url_for('admin'))

    user = {}

    user['user_id'] = user_id
    permission = account_db.get_access_level(user_id)
    user['ip_address'] = account_db.get_ip_address(user_id)
    user['last_online'] = account_db.get_last_online(user_id)
    user['date_created'] = account_db.get_date_created(user_id)
    user['username'] = account_db.get_user_name(user_id).title()
    user['total_notes'] = '{:02,}'.format(profile_db.get_total_notes(user_id))
    user['total_topics'] = '{:02,}'.format(
        profile_db.get_total_topics(user_id))
    user['access_level'] = ('Admin' if permission == PermissionConst.ROOT.value
                            else 'View Only' if permission == PermissionConst.VIEW.value else 'User')

    return render_template('adminedit.html', user=user, PermissionConst=PermissionConst) 
Example #9
Source File: fhost.py    From 0x0 with 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 #10
Source File: views.py    From Flask-Blogging with 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 #11
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 6 votes vote down vote up
def searchnotif():
    notification = models.Notification(user_id=current_user.id,
                                       fulltxt=True,
                                       vendor=escape(request.json['searchquery']),
                                       product='',
                                       version='')
    # Checking Integrity Before Insert  #
    if models.Notification.query.filter_by(user_id=notification.user_id,
                                           vendor=notification.vendor,
                                           fulltxt=notification.fulltxt).first() is None:
        models.db.session.add(notification)
        models.db.session.commit()
        flash('Notification Successfully Created.', 'success')
        syslog.syslog(syslog.LOG_DEBUG, "New notification created by: " + current_user.email)
        return redirect(url_for("notif.notiftab"))
    else:
        flash('Notification Already existing.', 'warning')
        syslog.syslog(syslog.LOG_ERR, "Notification Already existing: " + current_user.email)
        return redirect(url_for("notif.notiftab")) 
Example #12
Source File: notif.py    From cve-portal with GNU Affero General Public License v3.0 6 votes vote down vote up
def checknotif():
    if request.json["product"] == '':
        req = ':' + request.json['vendor'] + ':'
    else:
        req = request.json["vendor"] + ':' + request.json["product"] + ':' + request.json["version"]

    tab = []
    keytab = ['summary']
    for cves in mongo.db.cves.find({'vulnerable_configuration': {'$regex': req}}).sort("Modified", DESCENDING):
        dic = {}
        for key, value in cves.items():
            if key in keytab:
                dic[key] = cgi.escape(value, quote=True)
            else:
                if isinstance(value, datetime):
                    value = str(value)
                dic[key] = value
        tab.append(dic)
    return json.dumps(tab, sort_keys=True, default=json_util.default) 
Example #13
Source File: output.py    From analytics-quarry-web with MIT License 6 votes vote down vote up
def html_formatter(reader, resultset_id):
    rows = _stringify_results(reader.get_rows(resultset_id))
    header = next(rows)

    def respond():
        yield '<table>\n'
        yield '<tr>'
        for col in header:
            yield '<th scope="col">%s</th>' % escape(col)
        yield'</tr>\n'

        for row in rows:
            yield '<tr>'
            for col in row:
                yield '<td>%s</td>' % escape(col)
            yield'</tr>\n'

        yield '</table>'

    return Response(_join_lines(respond()),
                    content_type='text/html; charset=utf-8') 
Example #14
Source File: mongo_task_conversion.py    From FACT_core with GNU General Public License v3.0 6 votes vote down vote up
def _get_meta_from_request(request):
    meta = {
        'device_name': escape(request.form['device_name']),
        'device_part': escape(request.form['device_part']),
        'device_class': escape(request.form['device_class']),
        'vendor': escape(request.form['vendor']),
        'version': escape(request.form['version']),
        'release_date': escape(request.form['release_date']),
        'requested_analysis_systems': request.form.getlist('analysis_systems'),
        'tags': escape(request.form['tags'])
    }
    _get_meta_from_dropdowns(meta, request)

    if 'file_name' in request.form.keys():
        meta['file_name'] = escape(request.form['file_name'])
    return meta 
Example #15
Source File: notebook.py    From Notebook with MIT License 6 votes vote down vote up
def delete_topic():
    resp = {'resp': 'error-msg'}

    if not 'topic_id' in request.form:
        return jsonify(resp)

    user_id = session['user_id']
    topic_id = escape(request.form['topic_id'].strip())

    if not profile_db.topic_exists(user_id, topic_id):
        return jsonify(resp)

    profile_db.delete_topic(topic_id)

    resp['resp'] = 'success-msg'
    return jsonify(resp)

# note 
Example #16
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def createtopic():
    resp = {'topic_id': '', 'date_created': '', 'resp': 'error-msg'}

    if not ('topic_name' in request.form and 'time_stamp' in request.form):
        return jsonify(resp)

    timestamp = request.form['time_stamp']

    if not timestamp.isdigit():
        return jsonify(resp)

    current_time = int(timestamp)/1000

    try:
        datetime.fromtimestamp(current_time)
    except:
        return jsonify(resp)

    topic_name = escape(request.form['topic_name'].strip())
    topic_len = len(topic_name)

    if (
        (topic_len < ProfileConst.MIN_TOPIC_LENGTH.value) or
        (topic_len > ProfileConst.MAX_TOPIC_LENGTH.value)
    ):
        return jsonify(resp)

    if profile_db.get_total_topics(session['user_id']) >= ProfileConst.MAX_TOPICS.value:
        return jsonify(resp)

    resp['resp'] = 'success-msg'
    resp['topic_id'], resp['date_created'] = create_topic(
        topic_name, current_time)

    return jsonify(resp) 
Example #17
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def gettopic():
    if not 'id' in request.args:
        return render_template('topic.html', PermissionConst=PermissionConst)

    user_id = session['user_id']
    user_key = get_user_key()
    topic_id = escape(request.args.get('id'))

    if not profile_db.topic_exists(user_id, topic_id):
        return render_template('topic.html', PermissionConst=PermissionConst)

    topic = profile_db.decrypt_topic(topic_id, user_key)
    return render_template('topic.html', topic=topic, PermissionConst=PermissionConst) 
Example #18
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def settings_topic():
    if not 'topic_id' in request.args:
        return redirect(url_for('index'))

    user_id = session['user_id']
    user_key = get_user_key()
    topic_id = escape(request.args.get('topic_id'))

    if not profile_db.topic_exists(user_id, topic_id):
        return redirect(url_for('index'))

    topic = profile_db.decrypt_topic(topic_id, user_key, get_notes=False)

    return render_template('settingstopic.html', topic=topic, PermissionConst=PermissionConst) 
Example #19
Source File: helpers.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def changed_by_name(self) -> str:
        if self.created_by:
            return escape("{}".format(self.created_by))
        return "" 
Example #20
Source File: models.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def link(self) -> Markup:
        name = escape(self.datasource_name)
        return Markup(f'<a href="{self.url}">{name}</a>') 
Example #21
Source File: models.py    From incubator-superset with Apache License 2.0 5 votes vote down vote up
def link(self) -> Markup:
        name = escape(self.name)
        anchor = f'<a target="_blank" href="{self.explore_url}">{name}</a>'
        return Markup(anchor) 
Example #22
Source File: comment.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def post_comment():
    """ Post a comment underneath a post """

    path = request.args.get('path', '')
    comment_id = request.args.get('comment_id')
    data = request.get_json()

    post = (db_session.query(Post)
                      .filter(Post.path == path)
                      .first())

    if not post:
        raise Exception('Unable to find post')

    if comment_id:
        comment = (db_session.query(Comment)
                             .filter(Comment.id == comment_id)
                             .first())
    else:
        comment = Comment(post_id=post.id)
    comment.text = escape(data['text'])
    comment.user_id = current_user.id
    db_session.add(comment)
    db_session.commit()

    send_comment_email(path=path,
                       commenter=current_user.format_name,
                       comment_text=data['text'])
    return "OK" 
Example #23
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def createnote():
    resp = {'note_id': '', 'date_created': '', 'resp': 'error-msg'}

    if not ('topic_id' in request.form and 'note_title' in request.form and 'time_stamp' in request.form):
        return jsonify(resp)

    if profile_db.get_total_notes(session['user_id']) >= ProfileConst.MAX_NOTES.value:
        return jsonify(resp)

    note_title = escape(request.form['note_title'].strip())
    topic_id = escape(request.form['topic_id'].strip())
    timestamp = escape(request.form['time_stamp'])
    note_len = len(note_title)

    if (
        (note_len < ProfileConst.MIN_NOTE_LENGTH.value) or
        (note_len > ProfileConst.MAX_NOTE_LENGTH.value)
    ):
        return jsonify(resp)

    if not timestamp.isdigit():
        return jsonify(resp)

    current_time = int(timestamp)/1000

    try:
        datetime.fromtimestamp(current_time)
    except:
        return jsonify(resp)

    resp['resp'] = 'success-msg'
    resp['note_id'], resp['date_created'] = create_note(
        topic_id, note_title, current_time)

    return jsonify(resp) 
Example #24
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def getnotes():
    resp = {'notes': []}

    if not 'topic_id' in request.form:
        return jsonify(resp)

    topic_id = escape(request.form['topic_id'].strip())

    if not len(topic_id):
        return jsonify(resp)

    resp['notes'] = get_notes(topic_id)
    return jsonify(resp) 
Example #25
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def update_access():
    resp = {'resp': 'error-msg'}

    if not ('user_id' in request.form and 'access_id' in request.form):
        return jsonify(resp)

    user_id = escape(request.form['user_id'])
    access_id = escape(request.form['access_id'])

    if not account_db.user_id_exists(user_id):
        return jsonify(resp)

    if not access_id.isdigit():
        return jsonify(resp)

    access_id = int(access_id)

    if (access_id != PermissionConst.ROOT.value and
        access_id != PermissionConst.VIEW.value and
            access_id != PermissionConst.NONE.value):
        return jsonify(resp)

    if access_id == account_db.get_access_level(user_id):
        return jsonify(resp)

    if user_id == session['user_id']:
        if account_db.get_admin() == 1:
            # sorry, I can't allow you to do that
            return jsonify(resp)

    resp['resp'] = 'success-msg'
    account_db.update_permission(user_id, access_id)

    account_db.logout(user_id)
    return jsonify(resp) 
Example #26
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def logout_user():
    resp = {'resp': 'error'}

    if not 'user_id' in request.form:
        return jsonify(resp)

    user_id = escape(request.form['user_id'])

    if not account_db.user_id_exists(user_id):
        return jsonify(resp)

    resp['resp'] = 'success'
    account_db.logout(user_id)
    return jsonify(resp) 
Example #27
Source File: notebook.py    From Notebook with MIT License 5 votes vote down vote up
def delete_user():
    resp = {'resp': 'error'}

    if not 'user_id' in request.form:
        return jsonify(resp)

    user_id = escape(request.form['user_id'])

    if not account_db.user_id_exists(user_id):
        return jsonify(resp)

    if delete_usr(user_id):
        resp['resp'] = 'success'

    return jsonify(resp) 
Example #28
Source File: model_additions.py    From koschei with GNU General Public License v2.0 5 votes vote down vote up
def problem_html(self):
    return str(escape(str(self))).replace('\n', '<br>') 
Example #29
Source File: mongo_task_conversion.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def get_file_name_and_binary_from_request(request, config: ConfigParser):  # pylint: disable=invalid-name
    try:
        file_name = escape(request.files['file'].filename)
    except Exception:
        file_name = 'no name'
    file_binary = get_uploaded_file_binary(request.files['file'], config)
    return file_name, file_binary 
Example #30
Source File: mongo_task_conversion.py    From FACT_core with GNU General Public License v3.0 5 votes vote down vote up
def _get_meta_from_dropdowns(meta, request):
    for item in meta.keys():
        if not meta[item] and item in DROPDOWN_FIELDS:
            dd = request.form['{}_dropdown'.format(item)]
            if dd != 'new entry':
                meta[item] = escape(dd)