New to python and CS. SQlite, flask - python

I'm new to python and CS so this question might be a bit too easy. Thanks for your help I'm getting an error:
Bad Request
The browser (or proxy) sent a request that this server could not understand.
After implementing a new html template and python function:
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
session.clear()
if request.form["name"] == "" or request.form["password"] == "":
return render_template("apology.html")
elif request.form["password"] != request.form["confirmation"]:
return render_template("apology.html")
hash = pbkdf2_sha256.hash("password")
do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
name=request.form.get["name"], hash=hash)
session["user_id"] = rows[0]["id"]
return redirect(url_for("index"))
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block main %}
<form action="{{ url_for('register') }}" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<input class="form-control" name="confirmation" placeholder="Confirm Password" type="password"/>
</div>
<div class="form-group">
<button class="btn btn-default" type="submit">Register</button>
</div>
</fieldset>
</form>
{% endblock %}

First you should check if the request type is 'POST', after that you check all the conditions. Do like below to resolve the issue:
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user."""
session.clear()
if request.method == 'POST':
if request.form["name"] == "" or request.form["password"] == "":
return render_template("apology.html")
elif request.form["password"] != request.form["confirmation"]:
return render_template("apology.html")
hash = pbkdf2_sha256.hash("password")
do.execute("INSERT INTO finance (name, password) VALUES(:name, :password)",
name=request.form.get["name"], hash=hash)
session["user_id"] = rows[0]["id"]
return redirect(url_for("index"))
else:
// you can render the template to be shown for registration.

Related

405 Method Not Allowed : Flask web app login page

I am trying to create a login page for my flask web app code shown below:
# Route for handling the login page logic
#app.route('/logins', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'GET':
# Just render the initial form, to get input
return (render_template('login.html'))
if request.method == 'POST':
if request.form['username'] == 'admin' or request.form['password'] == 'P#55w0rd':
return redirect(url_for('main'))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('login.html', error=error)
# Set up the main route
#app.route('/main', methods=['GET', 'POST'])
def main():
if request.method == 'GET':
# Just render the initial form, to get input
return(render_template('main.html'))
This is my HTML login page code
<form id="login" action="/logins" method="POST" class="login100-form validate-form">
<span class="login100-form-logo">
<i class="zmdi zmdi-landscape"></i>
</span>
<span class="login100-form-title p-b-34 p-t-27">
Log in
</span>
<div class="wrap-input100 validate-input" data-validate = "Enter username">
<input class="input100" type="text" id="username" name="username" placeholder="Username" value={{request.form.username}}>
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="wrap-input100 validate-input" data-validate="Enter password">
<input class="input100" type="password" id="password" name="pass" placeholder="Password" value="{{
request.form.password }}">
<span class="focus-input100" data-placeholder=""></span>
</div>
<div class="container-login100-form-btn">
<button type="submit" class="login100-form-btn">
Login
</button>
</div>
</form>
{% if error %}
<p class="error"><strong>Error:</strong> {{ error }}
{% endif %}
but after clicking on login button
404 Method Not allowed
error is coming. what changes to be done in my code so that it can properly redirect to main.html?
Change 'password' to 'pass' :
if request.form['username'] == 'admin' or request.form['pass'] == 'P#55w0rd':

Form validation with flask without wtforms

I have problem with form validation in Flask. In login.html I have:
{% extends "base.html" %}
{% block content %}
<center>Sign In</center>
<form action="/login" method="post" >
<div class="login">
<input type="text" placeholder="Username" id="username" name="username">
<input type="password" placeholder="password" id="password" name="password">
<input type="submit" value="Sign In">
</div>
<div class="shadow"></div>
</form>
{% endblock %}
In routes.py I have:
#app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
return redirect(url_for('index'))
if request.method == 'POST'and form.validate():
if(request.form["username"] is None or request.form["password"] is None):
flash("fill inputs")
else:
user = User.query.filter_by(username=request.form["username"]).first()
if user is None or not user.check_password(request.form["password"]):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
userCookie = request.form['username']
resp = make_response(render_template('index.html'))
resp.set_cookie('user', userCookie)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return resp
return redirect(next_page)
return render_template('login.html', title='Sign In')
Unfortunately, after clicking to log in, nothing happens even if I write correct username and password. Before I was using WTForms and everything worked well, but I couldnt add css to modify form and after changing it, the validation dosnt work well. Can somebody help me with this problem?

Flask button redirects falsely to index

I have an input field that should save the content to a database:
{% for comment in comments %}
<div class="row">
{{ comment.content }}
</div>
{% endfor %}
<div class="row">
<form action="." method="POST">
<textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
<input type="submit" class="btn btn-warning" value="save">
</form>
</div>
in flask_app I check whether it is a POST or GET method. If it is POST it should reload the page with a redirect. However, it always returns me to "home".
#app.route('/photography', methods=["GET", "POST"])
def show_photography():
if request.method == "GET":
return render_template('photography.html', comments=Comment.query.all())
elif request.method == "POST":
comment = Comment(content=request.form["contents"])
db.sesson.add(comment)
db.session.commmit()
return 'welcome to flask!'
else:
flash('error message via flash')
return 'welcome to flaks' was just a test, it still redirects me to home after clicking the button. Can anyone help me?
It looks like your 'action="."' is the problem. Set it to url_for('show_photography') in the template.

Error 405 when trying to log in. Flask

I'm using Python 2.7 and Flask with Bootstrap:
When I log in my website, the page 405 Method Not Allowed shows after submitting my username and password. They do exist in the database and the page should at least show an error message.
The login function in my init.py:
#app.route('/login/', methods = ['GET','POST'])
def login():
try:
c, conn = connection()
error = None
if request.method == 'POST':
data = c.execute("SELECT * FROM users WHERE username = (%s)",
thwart(request.form['username']))
data = c.fetchone()[2]
if sha256_crypt.verify(request.form['password'], data):
session['logged_in'] = True
session['username'] = request.form['username']
flash("Welcome "+str(session['username'])+"! You are now logged in.")
return redirect(url_for("dashboard"))
else:
error = "Invalid credentials, try again."
gc.collect()
return render_template('login.html', error = error)
except Exception as e:
flash(e)
error = "Invalid credentials, try again."
return render_template('login.html', error = error)
And here is my login.html file:
{% extends "header.html" %}
{% block body %}
<body>
<div class="container">
<br>
<h4>Please Login:</h4>
<br>
<form action="" class="form-inline" method="post">
<input type="text" class="form-control" placeholder = "Username" name="username" value="{{request.form.username}}">
<input type="password" class="form-control" 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 class="container">
<br>
<p>No account? <a href='/register'>Register here</a>.</p>
<br>
{% for paragraph in Body_info %}
<p>{{ paragraph }}</p>
{% endfor %}
</div>
</div>
</body>
{% endblock %}

Flask Python submit button

I am trying to create a page to register users but the submit button in my bootstrap form isn't working. When I hit the submit button, I get a bad request error. Here is the code in my python file:
#app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
if not request.form['username']:
error = 'You have to enter a username'
elif not request.form['email'] or '#' not in request.form['email']:
error = 'You have to enter a valid email address'
elif not request.form['password']:
error = 'You have to enter a password'
elif get_user_id(request.form['username']) is not None:
error = 'The username is already taken'
else:
print(request.form['username'])
db = get_db()
db.execute('INSERT INTO user (username, email, pw_hash) VALUES (?, ?, ?)',
[request.form['username'], request.form['email'],
generate_password_hash(request.form['password'])])
db.commit()
flash('You were successfully registered and can login now')
return render_template('control.html')
return render_template('register.html')
also i have a html file register.html:
{% extends 'layout.html' %}
{% block title %}Sign-up{% endblock title %}
{% block body %}
<div class="container">
<form class="form-register" role="form" method="post" action="{{ url_for('register') }}">
<h2 class="form-register-heading">Please sign up</h2>
<label for="username" class="sr-only">Username</label>
<input type="username" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>
<label for="email" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" value="{{ request.form.email }}" placeholder="Email address" required autofocus>
<label for="password" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required >
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>
</form>
</div>
{% endblock body %}
I can't find where I did it wrong, I'm new to python and flask!
Your input fields have no name attribute. This will cause all of your checks to result in KeyErrors. The first step is to add the attribute to each input.
<input name="username" type="text" id="inputUsername" class="form-control" value="{{ request.form.username }}" placeholder="Username" required autofocus>
Note that I also checked the type attribute as there is no username type. email and password are valid values, email being added in HTML5.
The next step will be to change how you check for the fields. If you only care about the presence of the field, in is the way to go.
if 'username' not in request.form:
If, however, you also want a truty value, the get method is what you want.
if not request.form.get('username'):

Categories

Resources