Passing data with GET request instead of POST in flask app - python

I am building flask app and I am trying to understand the routes , methods in flask documentation. I wrote a code which uses GET to submit the fields of a form :
#app.route('/',endpoint='buf')
def index():
page = """
<DOCTYPE! html>
<html lang="en-US">
<head>
<meta charset=utf-8">
</head>
<body>
<form action="/hello" method="GET">
First name: <input type="text" name="fname" id="fname" ><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
"""
return page
#app.route('/hello',endpoint="new",methods=['GET','POST'])
def index():
if request.method=='POST':
return 'Hello %s' % (request.form['fname'])
else:
return 'Hello %s' % (request.form['fname'])
I get an error when I use 'GET' instead of 'POST' in my html form tag. Is there a way I can access the fields of the form using GET instead of POST?

From the relevant section at the quickstart guide
To access parameters submitted in the URL (?key=value) you can use the args attribute:
searchword = request.args.get('key', '')

Related

python flask session , login and index not working

I have a python flask app with login module implemented using extension python flask. In my login method.
The Error Message
app.py
# import the Flask class from the flask module
from flask import Flask, render_template, redirect, url_for, request, session
# create the application object
app = Flask(__name__)
app.secret_key = "hello"
# use decorators to link the function to a url
##app.route('/')
#def home():
# return "Hello, World!" # return a string
#app.route('/index', methods=['GET'])
def index():
if session.get ('username'):
return render_template('index.html')
else:
return render_template('login.html') # render a template
# route for handling the login page logic
#app.route('/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or request.form['password'] != 'admin':
error = 'Invalid Credentials. Please try again.'
else:
session['username'] = True
return redirect(url_for('index'))
return render_template('login.html', error=error)
# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)
login page
login.html
<html>
<head>
<title>Flask Intro - login page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<h1>Please login</h1>
<br>
<form action="" method="post">
<input type="text" placeholder="Username" name="username" value="{{
request.form.username }}">
<input type="password" placeholder="Password" name="password" value="{{
request.form.password }}">
<input class="btn btn-default" type="submit" value="Login">
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}</p>
{% endif %}
</div>
</body>
</html>
index.html
<DOCTYPE Html>
<html>
<head>
<tile>Addressing a Site</tile>
</head>
<body>
<address>welcome.</address>
</body>
</html>
i am trying to create a session between login and index page,just getting started with python flask framework, login session not working well.
It seems like you are actually having an issue with the methods rather than the session not working.
The Method Not Allowed error means that you are sending a GET/POST request to a page that does not accept that type of request.
Try changing the start of your login form to this
<form action="{{ url_for('login') }}" method="POST">
I just got it running on my computer and this works, the reason it did not work before was because the form was sending the post request to the /index route, which only accepts GET request.
Also, I noticed something else you may want to change.
You currently have this on your index route
if session.get ('username'):
return render_template('index.html')
else:
return render_template('login.html')
But it would be better to change that to this
if session.get ('username'):
return render_template('index.html')
else:
return redirect(url_for('login'))
That way the user is sent back to the login page rather than just being shown the login template from the index page.
I hope all of that helps.

Basic question: How to send data from forms properly on HTML to Flask. What am I doing wrong?

Python code:
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template("test1.html")
#app.route('/pass', methods=['POST', 'GET'])
def takename():
if request.method == 'POST':
fname = request.form.get('firstname')
lname = request.form.get('lastname')
print(fname)
print("test")
print(lname)
return render_template('pass.html', f=fname, l=lname)
else:
return("Did not work")
Form:
<form action="/pass" method=”POST”>
<label> First Name</label>
<input type=”text” name=”firstname”>
<label> Last Name </label>
<input type=”text” name=”lastname”>
<input type="submit">
</form>
Pass.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> "{{f}} </h1>
</body>
</html>
I always end up with "Did not work" the goal is for the user to enter their first and last name, and then be redirected to the the pass.html page with the first and last name as variables. What am I doing wrong? Thank you

Flask Saving a selected value from a field and displaying it on another page

I'm new to Flask and am facing difficulties saving the value that is selected from an option of four different coffee roasts and displaying it on another page. One one page (Roast.html) the user has the option to select one coffee roast from Light, Medium, Dark, and Special. After the submit button is pressed, I want to show this selection on the next page (Brew.html) i.e. "Your _____ roast coffee is now brewing!" Any help would be greatly appreciated! I would prefer not to involve php or javascript in this code. Thank you
coffeeMaker.py:
from flask import Flask
from flask import render_template
from flask import url_for
from flask import request
app = Flask(__name__)
#app.route('/')
def welcome():
return render_template("welcome.html")
#app.route('/Roast', methods = ['GET','POST'])
def roast():
print "inside Roast"
return render_template("Roast.html")
#app.route('/Brew', methods = ['GET','POST'])
def brew():
if request.method == 'POST':
print 456
a = request.query_string
print 789
return render_template("Brew.html",selection = a )
else:
return "This is a GET request."
if __name__ == '__main__':
app.run()
welcome.html:
<html>
<head>
<title>Welcome to Coffee Maker</title>
</head>
<body>
<h1>This is a website for you to order your coffee of perference
</h1>
<a href = "/Roast" >ready for a coffee</a>
</body>
</html>
Roast.html:
<html>
<form action="/Brew" method="Post">
<h3>2. Choose your Roast</h3>
<input type="text" name="firstname" value="Mickey">
<br>
<input type="radio" name="roastType" value="Light">Light
<br>
<input type="radio" name="roastType" value="Medium" checked>Medium
<br>
<input type="radio" name="roastType" value="Dark">Dark
<br>
<input type="radio" name="roastType" value="HackGT Blend">Special Blend
<br><br>
<input type="submit" value="Brew It">
</form>
</html>
Brew.html:
<html>
<head>
<title>
brew
</title>
</head>
<body>
<h1> Brewing</h1>
<p>You selected{{selection}}</p>
<p>Get ready for your perfect cup of coffee~</p>
</body>
</html>
You just need to grab the element from the request.form object:
if request.method == 'POST':
brew_type = request.form["roastType"]
print(brew_type)
return render_template("Brew.html", selection=brew_type)
It's all covered in the quickstart guide.

How to get html element in python program

I have my python code where I use html file. Please see below code:
#app.route('/',endpoint='buf')
def index():
page = """
<DOCTYPE! html>
<html lang="en-US">
<head>
<title>Hello World Page</title>
<meta charset=utf-8">
</head>
<body>
<form action="/hello" method="GET">
First: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
"""
return page
#app.route('/hello',endpoint="new",methods=['GET'])
def login():
return 'hello %s ' % (request.form['fname'])
This gives me an html page , which has a form with two fields and a submit button. I use virtual env to run this.
Now I want to get the fields first name and last name in my program so that when user click submit I want to display Hello "first name""last name"
Purpose :- to learn how to get the html element values when provided with a code In a python file.
Several things to do to make it work:
add POST and GET to supported methods of an app.route:
#app.route('/', methods=['POST', 'GET'])
in the view, handle both GET (when the user opens up a web page) and POST (when the user submits the form)
extract html code into an html template file and render it in the view (docs on rendering templates)
Here's the code with changes:
from flask import render_template
...
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
# use request.form['fname'] and request.form['lname']
# to access form input values
else:
return render_template('index.html')
Also see documentation page.
Hope that helps.

Python Bottle how to pass parameter as json

I created an api for openerp using bottle
It works well while access using browser
I don't know how to pass it as json parameters
The Problem is
how can i call using api and pass json parameters like
http://localhost/api?name=admin&password=admin&submit=Submit
Here is my wsgi code app.wsgi
import json
import os
import sys
import bottle
from bottle import get, post, run,request,error,route,template,validate,debug
def login():
import xmlrpclib
username = request.forms.get('name')
pwd = request.forms.get('password')
dbname = 'more'
sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)
if uid:
return json.dumps({'Success' : 'Login Sucessful'])
def index():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>Welcome To PORTAL
<form method="GET" action="/api/links" enctype="multipart/form-data">
Name:<input name="name" type="text"/><br>
Password:<input name="password" type="password"/><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>'''
def links():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>
<a href="/api/advisor">Advisor<br>
</body>
</html>'''
application = bottle.default_app()
application.route('/', method="GET", callback=index)
application.route('/', method="POST",callback=login)
request.forms is used for POST or PUT requests. The form in your code uses GET, not POST, so you should use request.query.getall, which gives you access to "URL arguments".
I don't see anything wrong with the code (except pep8 changes), only problem I see is method of the form and location, see the fixed version below ...
import json
import os
import sys
import bottle
from bottle import get, post, run, validate, request, error, route, template, debug
def login():
import xmlrpclib
username = request.forms.get('name')
pwd = request.forms.get('password')
dbname = 'more'
sock_common = xmlrpclib.ServerProxy ('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)
if uid:
return json.dumps({'Success': 'Login Sucessful'})
def index():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>Welcome To PORTAL
<form method="POST" action="/" enctype="multipart/form-data">
Name:<input name="name" type="text"/><br>
Password:<input name="password" type="password"/><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>'''
def links():
return '''
<html>
<head>
<title> Portal</title>
</head>
<body>
<a href="/api/advisor">Advisor<br>
</body>
</html>'''
application = bottle.default_app()
application.route('/', method="GET", callback=index)
application.route('/', method="POST", callback=login)
application.run()

Categories

Resources