i am a beginner programmer in flask and i encounter a problem i rly don't see the problem with my code.
In the login file i have a form and it will send a req to /check but i get an err like: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
I also have the register file with the action route '/' and this works.
Here is the code:
from flask import Flask, render_template, request, url_for, redirect
from models.Data_Base import DataBase
app = Flask(__name__)
db = DataBase()
#app.route('/')
def main_page_render():
return render_template('home.html')
#app.route('/login')
def login_page_render():
return render_template('login.html')
#app.route('/check')
def check_page_render():
print('{} {}'.format(request.form['user_name'], request.form['password']))
if request.form['user_name'] == 'admin' and request.form['password']:
return redirect(url_for('admin_page_render'))
elif db.verify_login(request.form['user_name'], request.form['password']) == True:
return redirect('/fighter/{}'.format(request.form['user_name']))
#app.route('/admin')
def admin_page_render():
return 'Admin Page'
#app.route('/fighter/<username>')
def fighter_page_render(username):
return 'Fighter page'
#app.route('/register')
def register_page_render():
return render_template('register.html')
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login_page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="/check">
<label for="user_name">User name:</label><br>
<input type="text" id="user_name" name="user_name"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<p>Click submit in order to get to your account</p>
</body>
</html>
A Solution can be this, try to do these changes.
app.py
...
#app.route('/check', methods=["GET", "POST"])
def check_page_render():
print('{} {}'.format(request.form['user_name'], request.form['password']))
if request.form['user_name'] == 'admin' and request.form['password']:
return redirect(url_for('admin_page_render'))
elif db.verify_login(request.form['user_name'], request.form['password']) == True:
return redirect('/fighter/{}'.format(request.form['user_name']))
...
/templates/home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login_page</title>
</head>
<body>
<h2>Login Page</h2>
<form action="/check" method="POST">
<label for="user_name">User name:</label><br>
<input type="text" id="user_name" name="user_name"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
<p>Click submit in order to get to your account</p>
</body>
</html>
Related
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.
I have been working on a web interface using Flask and having some issues with back button in browser as after logging out hitting it takes user back inside. I have found similar questions and tried their answers but the issue is not resolved. I am attaching a simple example kindly have a look at it.
Main
from flask import Flask, request,session, redirect, url_for, render_template
from os import urandom
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.secret_key = urandom(24)
#app.route('/', methods=['POST', 'GET'])
def index():
if request.method == 'POST':
session['Email id'] = request.form.get('Email Id')
Pass = request.form.get('Password')
try:
if session['Email id'] == 'KK#gmail.com' and Pass == 'KKK':
return render_template('Logged_in.html')
except:
return render_template('login.html')
return render_template('login.html')
#app.route('/sign_out')
def sign_out():
session.pop('Email id')
return redirect(url_for('index'))
#app.after_request
def add_header(r):
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r
if __name__ == '__main__':
app.run(host="0.0.0.0", debug=True, threaded=True)
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="{{ url_for('index') }}" method="POST" id="login" class="input-group">
<input type="text" class="input-field" placeholder="Email Id" required name="Email Id">
<input type="text" class="input-field" placeholder="Password" required name="Password">
<button type="submit" class="submit-btn" style="color: white;">Log in</button>
</form>
</body>
</html>
Logged_in.html
<h2>You are Logged in</h2>
<i class="fas fa-sign-out-alt"></i>Log out
Your problem is that when users push the back button their browser will re-do the POST request. You need to use the POST/redirect/GET pattern to prevent this. For this you need four endpoints in totalt:
GET / : Check in the session that the user is logged in and render Logged_in.html, otherwise redirect to /login.html
GET /login.html : Render login.html
POST /sign_in : Check username and password. If successful, update the session and redirect to /
POST /sign_out : Log out the user session and redirect to /login.html
Do not render templates in your POST endpoints, just make them manipulate the session and then redirect.
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
I get data from input. When I click to search button I need to open webbrowser page and see my input data in google. How can I do that? Many thanks.
This is my code:
views.py:
from django.http import HttpResponse
from django.shortcuts import render
def index(request):
if request.method == 'GET':
return render(request, 'index.html', context={})
# Handles the search once the submit button in the form is pressed
# which sends a "POST" request
if request.method == 'POST':
# Get the input data from the POST request
search_query = request.POST.get('search', None)
# Validate input data
if search_query and search_query != "":
return HttpResponse(search_query)
try:
from googlesearch import search
except ImportError:
print("No module named 'google' found")
for j in search(search_query, tld="co.in", num=10, stop=1, pause=2):
print(j)
else:
return HttpResponse('Invalid input.')
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form method="POST">
{% csrf_token %}
<input type="text" name="search" placeholder="some text"><br>
<button class="button" name="submit" type="submit">Search</button>
</form>
</body>
</html>
urls.py
from django.urls import path
from firstapp import views
urlpatterns = [
path('', views.index, name='home')
]
All files are in hello folder. My app namely firstapp path: C:\Users\user\Desktop\hello\firstapp
index.html path is:
C:\Users\user\Desktop\hello\firstapp\templates
In order to redirect to google you need to have your search textfield to use a parameter called q. Here is an index.html file that would work:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="https://google.com" method="GET">
{% csrf_token %}
<input type="text" name="q" placeholder="some text"><br>
<input type="submit" name="submit" value="Search">
</form>
</body>
</html>
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', '')