Here are the examples of the python api flask.request.form taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
193 Examples
5
Example 1
Project: pwnableweb Source File: views.py
@app.route('/register', methods=['POST'])
def register():
try:
user = models.User.register(
flask.request.form['username'],
flask.request.form['email'],
flask.request.form['password'])
flask.session['user'] = user.uid
flask.flash('Registration successful.', 'success')
except exc.IntegrityError:
flask.flash('Duplicate username or email.', 'danger')
return flask.redirect(flask.url_for('home'))
3
Example 2
def _get_csrf_token(self):
# find the ``csrf_token`` field in the subitted form
# if the form had a prefix, the name will be
# ``{prefix}-csrf_token``
for key in request.form:
if key.endswith('csrf_token'):
csrf_token = request.form[key]
if csrf_token:
return csrf_token
for header_name in self._app.config['WTF_CSRF_HEADERS']:
csrf_token = request.headers.get(header_name)
if csrf_token:
return csrf_token
return None
3
Example 3
@app.route('/comment/', methods=['POST'])
def comment():
comment = Comment()
form = CommentForm(request.form, obj=comment)
if form.validate():
form.populate_obj(comment)
comment.save()
flash('Thank you for your comment!', 'success')
else:
flash('There were errors with your comment', 'error')
return redirect(url_for('detail', id=comment.post.id))
3
Example 4
@tasks.route('/edit/<int:id>', methods=['GET', 'POST'])
@must_be_able_to('edit_task')
def edit(id):
task = get_or_404(Task, id=id)
form = TaskForm(request.form, task)
if form.validate_on_submit():
# Since we don't show deployments in form, we need to set them here.
form.deployments.data = task.deployments
form.populate_obj(task)
db.session.add(task)
db.session.commit()
notify(u'Task "{0}" has been updated.'.format(task.name),
category='success', action='edit_task')
return redirect(url_for('tasks.view', id=task.id))
return render_template('tasks/edit.html', task=task, form=form)
3
Example 5
@student.route('/<assignment_name:name>/group/invite/', methods=['POST'])
@login_required
def group_invite(name):
assignment = get_assignment(name)
email = request.form['email']
invitee = User.lookup(email)
if not invitee:
flash("{0} is not enrolled".format(email), 'warning')
else:
try:
Group.invite(current_user, invitee, assignment)
success = "{0} has been invited. They can accept the invite by logging into okpy.org".format(email)
invite_email(current_user, invitee, assignment)
flash(success, "success")
except BadRequest as e:
flash(e.description, 'danger')
return redirect(url_for('.assignment', name=assignment.name))
3
Example 6
@app.route('/logged_in', methods=['POST'])
def login_callback():
token = request.form['token']
payload = {'format': 'json', 'token': token}
response = requests.get(request.host_url + 'velruse/auth_info', params=payload)
return render_template('result.html', result=response.json)
3
Example 7
Project: unshred-tag Source File: app.py
@app.route("/skip", methods=["POST"])
@login.login_required
def skip():
Cluster.objects(pk=request.form["_id"]).update_one(
add_to_set__users_skipped=g.user.id)
User.objects(pk=g.user.id).update_one(inc__skipped=1)
return redirect(url_for("next"))
3
Example 8
Project: sagenb Source File: worksheet.py
@worksheet_command('save')
def worksheet_save(worksheet):
"""
Save the contents of a worksheet after editing it in plain-text
edit mode.
"""
if 'button_save' in request.form:
E = request.values['textfield']
worksheet.edit_save(E)
worksheet.record_edit(g.username)
return redirect(url_for_worksheet(worksheet))
3
Example 9
@app.route('/login', methods = ['POST'])
def login():
"""Attempts to log the user in"""
from werkzeug.security import check_password_hash
username = request.form['user']
password = request.form['password']
user = db['users'].find_one(username=username)
if user is None:
return redirect('/error/invalid_credentials')
if check_password_hash(user['password'], password):
session_login(username)
return redirect('/tasks')
return redirect('/error/invalid_credentials')
3
Example 10
@blueprint.route('/create/', methods = ['POST', ])
@admin_required
def create():
"""create a blog entry"""
blog_entry = db.session.query(BlogEntry).filter_by(evernote_url = request.form['evernote_url']).first()
if not blog_entry:
blog_entry = BlogEntry(evernote_url = request.form['evernote_url'])
blog_entry.synchronize()
db.session.add_then_commit(blog_entry)
return redirect(url_for('admin.index'))
3
Example 11
@app.route('/clipper/progress', methods=['POST'])
def updateprogress():
pos = json.loads(request.form['pos'])
app.logger.debug(pos)
if pos is not None:
updatepos(pos)
return jsonify(status=200, message='ok')
3
Example 12
@app.route('/users', methods=['POST'])
@auto.doc(groups=['users', 'private'],
form_data=['username'])
def post_user(id):
"""Creates a new user."""
User(request.form['username'])
redirect('/users')
3
Example 13
Project: the-listserve-archive Source File: tla.py
@app.route('/cio/webhook', methods=['POST'])
def receive_mail():
"""POSTed to by context.IO when a new post is received."""
app.logger.debug("received new post")
app.logger.debug(request.form)
app.logger.debug(request.json)
if not verify_webhook_post(request.json):
return "invalid"
commit_post_data(request.json)
return "ok"
3
Example 14
Project: scout Source File: views.py
@core.route('/institutes/<institute_id>/settings', methods=['POST'])
@login_required
def institute_settings(institute_id):
"""Update institute settings."""
inst_mod = validate_user(current_user, institute_id)
inst_mod.coverage_cutoff = int(request.form['coverage_cutoff'])
inst_mod.frequency_cutoff = float(request.form['frequency_cutoff'])
inst_mod.save()
return redirect(request.referrer)
3
Example 15
Project: azure-sdk-for-python Source File: views.py
@app.route('/deletestorageaccount', methods=['POST'])
@auth.require_login
def storageaccount_delete_rest_post():
subscription_id = request.form['subscriptionid']
resource_group_name = request.form['resourcegroup']
account_name = request.form['name']
creds = _get_credentials()
result = models.delete_storage_account(subscription_id, creds, resource_group_name, account_name)
return '', 200
3
Example 16
Project: flask-genshi Source File: flaskr.py
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
g.db.execute('insert into entries (title, text) values (?, ?)',
[request.form['title'], request.form['text']])
g.db.commit()
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
3
Example 17
@app.route('/score', methods=['POST'])
def add_score():
data = request.form
try:
record = json.dumps({'user': data['user'], 'score': int(data['score'])})
print record
result = r.lpush('scoreboard', record)
return jsonify(error=result)
except KeyError:
return jsonify(error=True)
3
Example 18
@app.route('/', methods=['POST', 'GET'])
def hello():
if request.form:
form = Form(request.form, False)
if form.is_valid():
print 'Cool!'
# Use form.data as validated structure
else:
form = Form(validate=False)
return render_template('form.html', form=form)
3
Example 19
Project: eb-py-flask-signup Source File: application.py
@application.route('/signup', methods=['POST'])
def signup():
signup_data = dict()
for item in request.form:
signup_data[item] = request.form[item]
try:
store_in_dynamo(signup_data)
publish_to_sns(signup_data)
except ConditionalCheckFailedException:
return Response("", status=409, mimetype='application/json')
return Response(json.dumps(signup_data), status=201, mimetype='application/json')
3
Example 20
@app.route('/set_message', methods=['POST'])
@authenticated
def set_message():
"""Generate the image for this message and return
the url and image to the user.
"""
lex.get_or_create_email(session['lex_email'])
image_filename = '%s.png' % str(int(time.time()))
lex.encrypt_message(request.form['message'],
'tmp/',
image_filename,
session.get('lex_token'))
return redirect(url_for('your_messages'))
3
Example 21
@app.route('/user/<uuid>', methods=['POST'])
def forward(uuid):
user = User.query.filter_by(uuid=uuid).first()
if not user:
return ('User not found', 406)
message = {
'to': [{'email': user.email}],
'from_email': request.form['email'],
'subject': 'Message from {}'.format(request.form['name']),
'text': request.form['message'],
}
result = mandrill_client.messages.send(message=message)
if result[0]['status'] != 'sent':
abort(500)
if 'next' in request.form:
return redirect(request.form['next'])
return 'Your message was sent successfully'
3
Example 22
Project: docklet Source File: userlist.py
@classmethod
def post(self):
try:
dockletRequest.post('/user/modify/', request.form)
except:
return self.render('user/mailservererror.html')
return redirect('/user/list/')
3
Example 23
@user_blueprint.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm(request.form)
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user and bcrypt.check_password_hash(
user.password, request.form['password']):
login_user(user)
flash('Welcome.', 'success')
return redirect(url_for('main.home'))
else:
flash('Invalid email and/or password.', 'danger')
return render_template('user/login.html', form=form)
return render_template('user/login.html', form=form)
3
Example 24
Project: view-upload Source File: app.py
@app.route('/url-upload', methods=['POST'])
def url_upload_docuement():
"""
"""
box_view_client = BoxViewClient()
docuement_url = request.form['docuement-url']
try:
docuement = box_view_client.upload_docuement(docuement_url)
except(BoxViewError):
return jsonify({'error': 'an error occurred'}), 400
docuement_id = docuement.json()['id']
print 'Docuement ID is {}'.format(docuement_id)
return jsonify(docuement.json())
3
Example 25
Project: lighthouse Source File: sprockets.py
@app.route('/api/sprockets', methods=["POST"])
def create_sprocket():
conn = redis.Redis("127.0.0.1", port=REDIS_PORT)
if "sprocket" not in request.form or not request.form["sprocket"]:
abort(400)
conn.sadd("sprockets", request.form["sprocket"])
return jsonify(token=get_token(), success=True)
3
Example 26
@app.route("/upload_url", methods=['POST'])
def upload_url():
data = request.form
url = data['video_url']
use_rgb = data['use_rgb']
use_flow = data['use_flow']
try:
file_info = ydl.extract_info(unicode(url))
except:
return jsonify(error='invalid URL'), 200, {'ContentType': 'application/json'}
filename = os.path.join('tmp',file_info['id']+'.'+file_info['ext'])
# classify the video
return run_classification(filename, use_rgb, use_flow)
3
Example 27
@app.route("/publish/parameters/", methods=['POST'])
def handle_params():
data = json.loads(request.form['data'])
name = data.pop("name")
new_str = "<div class='parameters'><h1>{}</h1>".format(name)
for k,v in data.items():
new_str += "<div class='param_item'><b>{}</b> ::: {}</div>".format(k, v)
new_str += "</div>"
with SqliteDict("web.db") as db:
db['experiment'] = new_str
print("saving to db =)")
db['logs'] = []
db.commit()
return '', 204
3
Example 28
@app.route('/login', methods=['POST'])
def login():
u = User.query.filter(User.username == request.form["username"]).first()
if not u or u.password != request.form["password"]:
return error("E1")
s = Session.get_by_user(u)
if s is not None:
db_session.delete(s)
db_session.commit()
s = Session(u)
db_session.add(s)
db_session.commit()
return jsonify(s.values)
3
Example 29
def get_form_kwargs(self):
"""
Return parameters for creating the form instance.
:return:
A ``dict`` containing the arguments for creating the form instance.
"""
kwargs = {'formdata': request.form}
kwargs.update(self.get_initial())
return kwargs
3
Example 30
@recipyGui.route('/annotate', methods=['POST'])
def annotate():
notes = request.form['notes']
run_id = int(request.form['run_id'])
query = request.args.get('query', '')
db = utils.open_or_create_db()
db.update({'notes': notes}, eids=[run_id])
db.close()
return redirect(url_for('run_details', id=run_id, query=query))
3
Example 31
@app.route('/', methods=['POST'])
def shorten():
url = request.form['url'].strip()
if not valid_url(url):
return jsonify({'error': str(e)}, 400)
key, token = store.insert(url)
url = url_for('bounce', key=key, _external=True)
revoke = url_for('revoke', token=token, _external=True)
return jsonify({'url': url, 'revoke': revoke})
3
Example 32
Project: Skier Source File: pgpapi.py
@pgpapi.route("/sync/new", methods=["POST"])
def handle_key_broadcast():
# Recieve a new key broadcast.
if 'key' in request.form:
key = request.form["key"]
else:
# Prevent crashes from recieving an empty post.
return
res = pgp.add_pgp_key(key)
if res[0]:
return "", 200
else:
return "", 600 + res[1]
3
Example 33
@flask_app.route("/", methods=['GET', 'POST'])
@prism.public_endpoint
def login():
if is_logged_in():
return redirect(url_for('dashboard.DashboardView'))
form = LoginForm(request.form)
if request.method == 'POST' and form.validate():
user = User.query.filter_by(username=form.username.data).first()
if user:
if sha256_crypt.verify(form.password.data, user.password):
flask_login.login_user(user, remember=True)
return redirect(url_for('dashboard.DashboardView'))
flask.flash('Sorry, that username/password combination was incorrect.')
return render_template('other/login.html', title='Login', form=form)
3
Example 34
@blueprint.route("/settings/change", methods=["POST"])
@api_wrapper
@require_admin
def change_settings():
data = bson.json_util.loads(request.form["json"])
api.config.change_settings(data)
return WebSuccess("Settings updated")
3
Example 35
Project: flask-ldap-login Source File: test_login_form.py
def test_login_form(self):
data = {'username':'user1', 'password':'pass1'}
self._user = None
with self.app.test_request_context('/login', method="POST", data=data):
form = LDAPLoginForm(flask.request.form, csrf_enabled=False)
self.assertTrue(form.validate_on_submit())
# Test that save_user was called
self.assertIsNotNone(self._user)
3
Example 36
def _on_before_request(self):
g.sijax = self
self._sijax = sijax.Sijax()
self._sijax.set_data(request.form)
url_relative = request.url[len(request.host_url) - 1:]
self._sijax.set_request_uri(url_relative)
if self._json_uri is not None:
self._sijax.set_json_uri(self._json_uri)
3
Example 37
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
db['entries'].append(request.form)
flash('New entry was successfully posted')
return redirect(url_for('show_entries'))
3
Example 38
Project: puzzle Source File: views.py
@blueprint.route('/<case_id>/synopsis', methods=['POST'])
def synopsis(case_id):
"""Update the case synopsis."""
text = request.form['text']
case_obj = app.db.case(case_id)
app.db.update_synopsis(case_obj, text)
return redirect(request.referrer)
3
Example 39
Project: debsources Source File: views.py
def recv_search(self, **kwargs):
searchform = SearchForm(request.form)
if searchform.validate_on_submit():
params = dict(query=searchform.query.data)
suite = searchform.suite.data
if suite:
params["suite"] = suite
return redirect(url_for(".search", **params))
else:
# we return the form, to display the errors
return self.render_func(searchform=searchform)
3
Example 40
def remove_track(self, playlist):
if 'index' not in request.form:
abort(HTTP.BAD_REQUEST)
try:
playlist.remove_at(request.form.get('index'))
except (ValueError, IndexError):
abort(HTTP.BAD_REQUEST)
return self.Response('')
3
Example 41
Project: playa Source File: api.py
@app.route('/api/set_volume', methods=['POST'])
@api
def set_volume():
value = request.form['value']
app.player.set_volume(value)
return {
'value': app.player.get_volume()
}
3
Example 42
Project: LivingDex Source File: livingdex.py
@app.route('/uncatchPokemon', methods=['POST'])
def uncatchPokemon():
username = request.form['username']
if username == currentUser():
pokemon = request.form['pokemon']
user = database.userForUsername(username)
database.uncatchPokemonForUser(user, int(pokemon), db)
return 'OK'
3
Example 43
Project: learning-python Source File: views.py
@app.route('/add', methods=['POST',])
def add():
form = request.form
content = form.get('content')
todo = Todo(content=content,time=datetime.now())
todo.save()
return jsonify(status="success")
3
Example 44
Project: appointment-reminders-flask Source File: appointment.py
def post(self):
form = NewAppointmentForm(request.form)
if form.validate():
from tasks import send_sms_reminder
appt = Appointment(**form.data)
appt.time = arrow.get(appt.time, appt.timezone).to('utc').naive
reminders.db.session.add(appt)
reminders.db.session.commit()
send_sms_reminder.apply_async(
args=[appt.id], eta=appt.get_notification_time())
return redirect(url_for('appointment.index'), code=303)
else:
return render_template('appointments/new.html', form=form), 400
3
Example 45
Project: lerner Source File: webserver.py
@app.route('/twilio', methods=['POST'])
def twilio():
channel = request.form['To']
title = 'Message from ' + request.form['From']
message = title + ':' + request.form['Body']
notified = r.publish(channel, message)
response = make_response(channel + " " + str(notified), 200)
response.headers['Content-Type'] = 'text/plain'
return response
3
Example 46
Project: spin-docker Source File: views.py
@app.route('/v1/check-in', methods=['POST'])
def check_in():
"""Processes activity reports from the containers."""
active = request.form['active']
container_ip = request.remote_addr
container_id = r.get('ips:%s' % container_ip)
if container_id is not None:
r.hset('containers:%s' %
container_id, 'active', active)
return ''
3
Example 47
@blueprint.route('/delete', methods=['POST'])
@api_wrapper
@check_csrf
@require_teacher
def delete_group_hook():
api.group.delete_group_request(api.common.flat_multi(request.form))
return WebSuccess("Successfully deleted group")
3
Example 48
@user_blueprint.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form)
if form.validate_on_submit():
user = User(
email=form.email.data,
password=form.password.data
)
db.session.add(user)
db.session.commit()
login_user(user)
flash('Thank you for registering.', 'success')
return redirect(url_for("user.members"))
return render_template('user/register.html', form=form)
3
Example 49
Project: sixpack Source File: web.py
@app.route("/experiments/<experiment_name>/winner/", methods=['POST'])
def set_winner(experiment_name):
experiment = find_or_404(experiment_name)
experiment.set_winner(request.form['alternative_name'])
return redirect(url_for('details', experiment_name=experiment.name))
3
Example 50
@api.disabled_on_demo()
@api.acl_admin_required(message='Sorry, you don\'t have rights to access the setting panel')
@ns.doc(
responses={
200: 'Success',
403: 'Insufficient permissions',
500: 'Internal failure',
}
)
def post(self, conf=None, server=None):
"""Saves the server configuration"""
noti = bui.cli.store_conf_srv(request.form, conf, server)
return {'notif': noti}, 200