Python flask.request.form() Examples

The following are 30 code examples of flask.request.form(). 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.request , or try the search function .
Example #1
Source Project: video2commons   Author: toolforge   File: upload.py    License: GNU General Public License v3.0 15 votes vote down vote up
def upload():
    f = request.files['file']
    assert f, "Where's my file?"

    filekey = request.form.get('filekey') or str(uuid.uuid1())
    assert RE_ALLOWED_FILEKEYS.match('filekey'), 'Unacceptable file key'

    permpath = getpath(filekey)

    content_range = (f.headers.get('Content-Range') or
                     request.headers.get('Content-Range'))

    if content_range:
        result, kwargs = handle_chunked(f, permpath, content_range)
    else:
        result, kwargs = handle_full(f, permpath)

    kwargs['filekey'] = filekey

    return jsonify(result=result, **kwargs)


# Flask endpoint 
Example #2
Source Project: grlc   Author: CLARIAH   File: server.py    License: MIT License 8 votes vote down vote up
def query(user, repo, query_name, subdir=None, spec_url=None, sha=None, content=None):
    """Execute SPARQL query for a specific grlc-generated API endpoint"""
    glogger.info("-----> Executing call name at /{}/{}/{}/{} on commit {}".format(user, repo, subdir, query_name, sha))
    glogger.debug("Request accept header: " + request.headers["Accept"])

    requestArgs = request.args
    acceptHeader = request.headers['Accept']
    requestUrl = request.url
    formData = request.form

    query_response, status, headers = utils.dispatch_query(user, repo, query_name, subdir, spec_url,
                                                           sha=sha, content=content, requestArgs=requestArgs,
                                                           acceptHeader=acceptHeader,
                                                           requestUrl=requestUrl, formData=formData)
    if isinstance(query_response, list):
        query_response = jsonify(query_response)

    return make_response(query_response, status, headers)

### Server routes ### 
Example #3
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 8 votes vote down vote up
def block_friend():
    data = request.form
    user_one = data['user_one']
    user_two = data['user_two']

    database.block_friend(user_one, user_two)

    return jsonify({
        "success": True
    }) 
Example #4
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 6 votes vote down vote up
def get_message_history():
    conversation_db_path = get_conversation_db_path_for_users(request.form)
    conversation = Conversation(conversation_db_path)

    history = conversation.get_history()

    return jsonify({
        "history": history
    }) 
Example #5
Source Project: dino   Author: thenetcircle   File: routes.py    License: Apache License 2.0 6 votes vote down vote up
def update_channel_name(channel_uuid: str):
    form = request.get_json()
    name = form['name']

    try:
        channel_manager.rename(channel_uuid, name)
    except ChannelNameExistsException:
        return api_response(400, message='A channel with that name already exists')
    except EmptyChannelNameException:
        return api_response(400, message='Blank channel name is not allowed')

    return api_response(200) 
Example #6
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def create_conversation_db():
    conversation_db_path = get_conversation_db_path_for_users(request.form)
    print(conversations_dir)

    if not os.path.exists(conversation_db_path):
        with open(conversation_db_path, 'w') as f:
            pass
        conversation = Conversation(conversation_db_path)
        conversation.initialise_table()

    return jsonify({
        "success": True,
    }) 
Example #7
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def add_contact():
    data = request.form
    username = data['username'] 
Example #8
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def send_me_data():
    data = request.form
    for key, value in data.items():
        print("received", key, "with value", value)

    return "Thanks" 
Example #9
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def user_exists():
    username = request.form.get("username")
    exists = database.user_exists(username)

    return jsonify({
        "exists": exists
    }) 
Example #10
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def create_conversation_db():
    conversation_db_path = get_conversation_db_path_for_users(request.form)

    if not os.path.exists(conversation_db_path):
        with open(conversation_db_path, 'w') as f:
            pass
        conversation = Conversation(conversation_db_path)
        conversation.initialise_table()

    return jsonify({
        "success": True,
    }) 
Example #11
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def send_message(username):
    data = request.form
    author = data["author"]
    message = data["message"]
    date_sent = arrow.now().timestamp

    conversation_db_path = get_conversation_db_path_for_users({"user_one": author, "user_two": username})
    conversation = Conversation(conversation_db_path)
    conversation.add_message(author, message, date_sent)

    return jsonify({
        "success": True
    }) 
Example #12
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def update_avatar(username):
    img_b64 = request.form.get("img_b64")
    database.update_avatar(username, img_b64)

    return jsonify({
        "success": True
    }) 
Example #13
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def get_new_messages():
    data = request.form
    conversation_db_path = get_conversation_db_path_for_users(data)
    conversation_db = Conversation(conversation_db_path)

    timestamp = data["timestamp"]
    requester_username = data["user_one"]

    new_messages = conversation_db.get_new_messages(timestamp, requester_username)

    return jsonify({
        "messages": new_messages
    }) 
Example #14
Source Project: Tkinter-GUI-Programming-by-Example   Author: PacktPublishing   File: server.py    License: MIT License 5 votes vote down vote up
def add_friend():
    data = request.form
    user_one = data['user_one']
    user_two = data['user_two']

    if database.user_exists(user_two) and database.user_exists(user_one):
        database.add_friend(user_one, user_two)
        success = True
    else:
        success = False

    return jsonify({
        "success": success
    }) 
Example #15
Source Project: JJMumbleBot   Author: DuckBoss   File: web_helper.py    License: GNU General Public License v3.0 5 votes vote down vote up
def post_message():
    content = request.form['commandInput']
    if len(content) > 0:
        if content[0] == global_settings.cfg[C_MAIN_SETTINGS][P_CMD_TOKEN]:
            text = RemoteTextMessage(channel_id=global_settings.mumble_inst.users.myself['channel_id'],
                                     session=global_settings.mumble_inst.users.myself['session'],
                                     message=content,
                                     actor=global_settings.mumble_inst.users.myself['session'])
            global_settings.bot_service.message_received(text=text, remote_cmd=True)
            # print(text.message)
    return content 
Example #16
Source Project: flask-spark-docker   Author: mjhea0   File: views.py    License: MIT License 5 votes vote down vote up
def run_task():
    words = request.form['words']
    q = Queue()
    task = q.enqueue(create_task, words)
    response_object = {
        'status': 'success',
        'data': {
            'task_id': task.get_id()
        }
    }
    return jsonify(response_object), 202 
Example #17
Source Project: gryphon   Author: BusinessOptics   File: app.py    License: MIT License 5 votes vote down vote up
def ssh_parameters():
    if request.method == "POST":
        if "save" in request.form:
            session["ssh_signature"] = request.form["signature"]

        return redirect(request.args.get("next", "/"))

    return render_template(
        "ssh_parameters.html",
        ssh_signature=session.get("ssh_signature", ""),
        region=region,
    ) 
Example #18
Source Project: PT-help   Author: Rhilip   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_key(key):
    ret = ""
    if request.method == "POST":
        ret = request.form[key]
    elif request.method == "GET":
        ret = request.args.get(key)
    return ret 
Example #19
Source Project: pyspider   Author: binux   File: index.py    License: Apache License 2.0 5 votes vote down vote up
def runtask():
    rpc = app.config['scheduler_rpc']
    if rpc is None:
        return json.dumps({})

    projectdb = app.config['projectdb']
    project = request.form['project']
    project_info = projectdb.get(project, fields=('name', 'group'))
    if not project_info:
        return "no such project.", 404
    if 'lock' in projectdb.split_group(project_info.get('group')) \
            and not login.current_user.is_active():
        return app.login_response

    newtask = {
        "project": project,
        "taskid": "on_start",
        "url": "data:,on_start",
        "process": {
            "callback": "on_start",
        },
        "schedule": {
            "age": 0,
            "priority": 9,
            "force_update": True,
        },
    }

    try:
        ret = rpc.newtask(newtask)
    except socket.error as e:
        app.logger.warning('connect to scheduler rpc error: %r', e)
        return json.dumps({"result": False}), 200, {'Content-Type': 'application/json'}
    return json.dumps({"result": ret}), 200, {'Content-Type': 'application/json'} 
Example #20
Source Project: pyspider   Author: binux   File: debug.py    License: Apache License 2.0 5 votes vote down vote up
def save(project):
    projectdb = app.config['projectdb']
    if not projectdb.verify_project_name(project):
        return 'project name is not allowed!', 400
    script = request.form['script']
    project_info = projectdb.get(project, fields=['name', 'status', 'group'])
    if project_info and 'lock' in projectdb.split_group(project_info.get('group')) \
            and not login.current_user.is_active():
        return app.login_response

    if project_info:
        info = {
            'script': script,
        }
        if project_info.get('status') in ('DEBUG', 'RUNNING', ):
            info['status'] = 'CHECKING'
        projectdb.update(project, info)
    else:
        info = {
            'name': project,
            'script': script,
            'status': 'TODO',
            'rate': app.config.get('max_rate', 1),
            'burst': app.config.get('max_burst', 3),
        }
        projectdb.insert(project, info)

    rpc = app.config['scheduler_rpc']
    if rpc is not None:
        try:
            rpc.update_project()
        except socket.error as e:
            app.logger.warning('connect to scheduler rpc error: %r', e)
            return 'rpc error', 200

    return 'ok', 200 
Example #21
Source Project: llvm-zorg   Author: llvm   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def add_machine():
    # Check that we have an active user.
    user = current_app.get_active_user()
    if user is None:
        abort(401)

    # Check that the user has authority to access the lab.
    if not user.has_lab_access():
        abort(401)

    # If this isn't a post request, return the template.
    if request.method != 'POST':
        return render_template("add_machine.html", error=None)

    # Validate the entry data.
    id = request.form['id']
    hostname = request.form['hostname']
    if id in current_app.config.data.machines:
        return render_template("add_machine.html",
                               error='machine "%s" already exists' % id)
    if hostname in set(m.hostname
                       for m in current_app.config.data.machines.values()):
        return render_template("add_machine.html",
                               error='hostname "%s" already used' % hostname)

    # Add the machine record.
    machine = llvmlab.machine.Machine(id, hostname, user.id)
    current_app.config.data.machines[machine.id] = machine
    flask.flash('Added machine "%s"!' % machine.id)

    # Save the application data.
    current_app.save_data()
    flask.flash('Saved data!')

    return redirect(url_for("admin")) 
Example #22
Source Project: llvm-zorg   Author: llvm   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def login():
    # If this isn't a post request, return the login template.
    if request.method != 'POST':
        return render_template("login.html", error=None)

    # Authenticate the user.
    username = request.form['username']
    if not current_app.authenticate_login(username, request.form['password']):
        return render_template("login.html",
                               error="Invalid login")

    # Log the user in.
    session['logged_in'] = True
    session['active_user'] = username
    flask.flash('You were logged in as "%s"!' % username)
    return redirect(url_for("index")) 
Example #23
Source Project: app   Author: simple-login   File: resend_activation.py    License: MIT License 5 votes vote down vote up
def resend_activation():
    form = ResendActivationForm(request.form)

    if form.validate_on_submit():
        user = User.filter_by(email=form.email.data.strip().lower()).first()

        if not user:
            flash("There is no such email", "warning")
            return render_template("auth/resend_activation.html", form=form)

        if user.activated:
            flash("Your account was already activated, please login", "success")
            return redirect(url_for("auth.login"))

        # user is not activated
        LOG.d("user %s is not activated", user)
        flash(
            "An activation email has been sent to you. Please check your inbox/spam folder.",
            "warning",
        )
        send_activation_email(user, request.args.get("next"))
        return render_template("auth/register_waiting_activation.html")

    return render_template("auth/resend_activation.html", form=form) 
Example #24
Source Project: app   Author: simple-login   File: forgot_password.py    License: MIT License 5 votes vote down vote up
def forgot_password():
    form = ForgotPasswordForm(request.form)

    if form.validate_on_submit():
        email = form.email.data.strip().lower()
        flash(
            "If your email is correct, you are going to receive an email to reset your password",
            "success",
        )

        user = User.get_by(email=email)

        if user:
            send_reset_password_email(user)
            return redirect(url_for("auth.forgot_password"))

        # Trigger rate limiter
        g.deduct_limit = True

    return render_template("auth/forgot_password.html", form=form) 
Example #25
Source Project: app   Author: simple-login   File: login.py    License: MIT License 5 votes vote down vote up
def login():
    if current_user.is_authenticated:
        LOG.d("user is already authenticated, redirect to dashboard")
        return redirect(url_for("dashboard.index"))

    form = LoginForm(request.form)
    next_url = request.args.get("next")
    show_resend_activation = False

    if form.validate_on_submit():
        user = User.filter_by(email=form.email.data.strip().lower()).first()

        if not user or not user.check_password(form.password.data):
            # Trigger rate limiter
            g.deduct_limit = True
            form.password.data = None
            flash("Email or password incorrect", "error")
        elif not user.activated:
            show_resend_activation = True
            flash(
                "Please check your inbox for the activation email. You can also have this email re-sent",
                "error",
            )
        else:
            return after_login(user, next_url)

    return render_template(
        "auth/login.html",
        form=form,
        next_url=next_url,
        show_resend_activation=show_resend_activation,
    ) 
Example #26
Source Project: app   Author: simple-login   File: register.py    License: MIT License 5 votes vote down vote up
def register():
    if current_user.is_authenticated:
        LOG.d("user is already authenticated, redirect to dashboard")
        flash("You are already logged in", "warning")
        return redirect(url_for("dashboard.index"))

    if config.DISABLE_REGISTRATION:
        flash("Registration is closed", "error")
        return redirect(url_for("auth.login"))

    form = RegisterForm(request.form)
    next_url = request.args.get("next")

    if form.validate_on_submit():
        email = form.email.data.strip().lower()
        if not email_domain_can_be_used_as_mailbox(email):
            flash("You cannot use this email address as your personal inbox.", "error")
        else:
            if personal_email_already_used(email):
                flash(f"Email {email} already used", "error")
            else:
                LOG.debug("create user %s", email)
                user = User.create(
                    email=email,
                    name="",
                    password=form.password.data,
                    referral=get_referral(),
                )
                db.session.commit()

                try:
                    send_activation_email(user, next_url)
                except:
                    flash("Invalid email, are you sure the email is correct?", "error")
                    return redirect(url_for("auth.register"))

                return render_template("auth/register_waiting_activation.html")

    return render_template("auth/register.html", form=form, next_url=next_url) 
Example #27
Source Project: dino   Author: thenetcircle   File: routes.py    License: Apache License 2.0 5 votes vote down vote up
def create_channel():
    """ Create new channel """
    form = request.get_json()
    channel_name = form['name']
    channel_uuid = str(uuid())
    user_uuid = form['owner']
    
    message = {}
    if is_blank(channel_name):
        message['name'] = "Channel name can't be none."
    if is_blank(user_uuid):
        message['owner'] = "Owner can't be none."
    
    if len(message):
        return api_response(400, message=message)
    result = channel_manager.create_channel(channel_name, channel_uuid, user_uuid)

    if result is not None:
        return api_response(400, message=result)
    return api_response(200, {'sort': 1, 'name': channel_name, 'uuid': channel_uuid}) 
Example #28
Source Project: dino   Author: thenetcircle   File: routes.py    License: Apache License 2.0 5 votes vote down vote up
def update_channel_order(channel_uuid: str):
    form = request.get_json()
    order = form['order']
    channel_manager.update_sort(channel_uuid, order)
    return api_response(200) 
Example #29
Source Project: dino   Author: thenetcircle   File: routes.py    License: Apache License 2.0 5 votes vote down vote up
def add_channel_owner(channel_uuid: str):
    form = request.get_json()
    user_uuid = form['owner']

    if is_blank(user_uuid):
        return api_response(400, message='Blank user id is not allowed')

    try:
        user = user_manager.get_user(user_uuid)
        user['name'] = utils.b64d(user['name'])
    except NoSuchUserException:
        return api_response(400, message='No Such User.')

    user_manager.add_channel_owner(channel_uuid, user_uuid)
    return api_response(200, user) 
Example #30
Source Project: dino   Author: thenetcircle   File: routes.py    License: Apache License 2.0 5 votes vote down vote up
def add_channel_admin(channel_uuid: str):
    form = request.get_json()
    user_uuid = form['admin']

    if is_blank(user_uuid):
        return api_response(400, message='Blank user id is not allowed.')
    try:
        user = user_manager.get_user(user_uuid)
        user['name'] = utils.b64d(user['name'])
    except NoSuchUserException:
        return api_response(400, message='No Such User.')
    user_manager.add_channel_admin(channel_uuid, user_uuid)
    return api_response(200, user)