Flask add DB entry using a form - python

I'm a beginner learning FLASK. I'm making an app and for it I've created a DB model User, and an HTML/ JS form that takes input. What I want is to use the form information to create a new entry in the database but I am unsure on how to do it. I tried to do this
#app.route('/add_to_db')
def add_to_db():
email = request.form['email']
activated = 0;
user = models.User(email= email, activated = 0)
db.session.add(user)
db.session.commit()
HTML Code:
<form onsubmit="return validateEmail(document.getElementById('email').value)" action="{{ url_for("add_to_db") }}" method="post">
Please input your email adress: <input id="email">
<input type="submit">
</form>
<script>
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return(re.test(email));
}
</script>
But this gave me a 405 Method not allowed error.

A 405 error means "method not allowed". As you are sending form data, you are using a POST request and need to allow POST requests. By default only GET requests are allowed. Change the line #app.route('/add_to_db') to #app.route('/add_to_db', methods=['POST']).

Related

Getting user data from flask request method [duplicate]

I have the code below in my Python script:
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)
#app.route('/tx/index/')
def index():
"""Load start page where you select your project folder
or load history projects from local DB."""
from txclib import get_version
txc_version = get_version()
prj = project.Project(path_to_tx)
# Let's create a resource list from our config file
res_list = []
prev_proj = ''
for idx, res in enumerate(prj.get_resource_list()):
hostname = prj.get_resource_host(res)
username, password = prj.getset_host_credentials(hostname)
return render_template('init.html', txc_version=txc_version, username=username)
Also, I have an HTML form in init.html:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
How can I pass the user input from "projectFilepath" when a user clicks "spotButton" on a variable in my python script?
I'm new in Python and Flask, so forgive me if I make any mistakes.
The form tag needs some attributes set:
action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.
The input tag needs a name parameter.
Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.
#app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action to that view's URL using url_for:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
#app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>

How to access user Input as GET request and output the responce in HTML page using Flask Python [duplicate]

I have the code below in my Python script:
def cmd_wui(argv, path_to_tx):
"""Run a web UI."""
from flask import Flask, flash, jsonify, render_template, request
import webbrowser
app = Flask(__name__)
#app.route('/tx/index/')
def index():
"""Load start page where you select your project folder
or load history projects from local DB."""
from txclib import get_version
txc_version = get_version()
prj = project.Project(path_to_tx)
# Let's create a resource list from our config file
res_list = []
prev_proj = ''
for idx, res in enumerate(prj.get_resource_list()):
hostname = prj.get_resource_host(res)
username, password = prj.getset_host_credentials(hostname)
return render_template('init.html', txc_version=txc_version, username=username)
Also, I have an HTML form in init.html:
<form>
<input type="text" id="projectFilepath" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
How can I pass the user input from "projectFilepath" when a user clicks "spotButton" on a variable in my python script?
I'm new in Python and Flask, so forgive me if I make any mistakes.
The form tag needs some attributes set:
action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.
The input tag needs a name parameter.
Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.
#app.route('/handle_data', methods=['POST'])
def handle_data():
projectpath = request.form['projectFilepath']
# your code
# return a response
Set the form's action to that view's URL using url_for:
<form action="{{ url_for('handle_data') }}" method="post">
<input type="text" name="projectFilepath">
<input type="submit">
</form>
You need a Flask view that will receive POST data and an HTML form that will send it.
from flask import request
#app.route('/addRegion', methods=['POST'])
def addRegion():
...
return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
Project file path: <input type="text" name="projectFilePath"><br>
<input type="submit" value="Submit">
</form>

Trying to pass two parameters from an html form in flask (in url) to then run in a python program

I'm pretty new to this and I have a python algorithm which I want to run with two parameters that I get from an html form. Here is my html code:
<form action="result/">
<p><input class="w3-input w3-padding-16" method = "post" type="text" placeholder="Playlist URI" required name="URI"></p>
<p><input class="w3-input w3-padding-16" method = "post" type="text" placeholder="Spotify Username" required name="Username"></p>
<p>
<button class="w3-button w3-light-grey w3-padding-large" type="submit">
<i class="fa fa-paper-plane"></i> Submit
</button>
</p>
</form>
It redirects me to http://127.0.0.1:5000/result/?URI=b&Username=c, when I input b and c into the form.
I can't figure out how to accept them as parameters though, and it just returns this error:
404 Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
My python code looks like this:
#app.route('/result.html/<URI>&<username>')
def result(URI,username):
return render_template("result.html", uri=URI, username=username)
you can access parameters in get request using request in flask
example:
from flask import Flask, request
app = Flask(__name__)
#app.route("/result.html")
def result():
uri = request.args.get("uri")
username = request.args.get("username")

Struggling to get data from POST request data from a HTML form with flask

I've been working on a website back-end using the python library flask but whenever I try and get the form data from a POST request (as it needs to be sent securely) I always get a 405 - Method not allowed error. After the submission of a user's email and password at the moment its just meant to send them to a very basic html page with their name and email on it (it's easier to explain with the code).
python code:
# reroutes user to login page html file
#app.route("/")
#app.route("/login", methods=["GET", "POST"])
def reroute_login():
return flask.render_template("login.html")
# returns the login page html file
#app.route("/login", methods=["GET", "POST"])
def login():
if flask.request.method == "POST":
print("Reached")
email = flask.request.form["email"]
password = flask.request.form["password"]
print(email, password)
return flask.redirect(flask.url_for("user", usr=email))
else:
return flask.render_template("login.html")
#app.route("/<usr>")
def user(usr):
return f"<h1>{usr}</h1>" # here is that very basic html page I mentioned but it won't reroute to this page
login.html:
<form action="#" method="post">
<h1>Login</h1>
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
Forgot Your Password
<input type="submit" class="button1" value="submit" />
</form>
Please just know I'm very new to Flask and back-end web dev as a whole but any kind of help would be much appreciated :)
Try changing action in login.html from # to /login .
And you have defined multiple routes with same name.
Remove the first route to login.

Passing Variable from HTML to Python/Flask

Let me try this again. I want to enter a variable into my HTML form to submit, so far from reading the link here How to display a variable in HTML I've tried the following code, which is inside of main.html
<form>
Asset Tag:<br>
<input type="text" name="Asset Tag"><br>
<input type="submit" value="Submit">
<form action="{{ asset_tag }}" method="get">
</form>
I then have a python script that goes like this,
from flask import Flask, render_template
app = Flask('server')
#app.route('/py')
def server():
return render_template('main.html')
#API URL
JSS_API = 'https://apiresource.com'
#Pre-Defined username and password
username = 'username'
password = 'password'
#Ask User for the Asset tag
asset_tag = {{ }}
After the asset tag is entered it just searches through a JSON file for match, the rest doesn't matter so much so I didn't include the next piece of the script.
So Flask renders my HTML just fine and I can submit a value but it's not being passed back to the script, which makes sense as I'm doing the opposite of the link I provided, but I just can't not think of how it's done. Any suggestions?
You have a few issues that I've outlined below. Overall though, the frontend is passing the variable to the backend, it's just that the variables are only accessible via the request object from within the route to which the data is passed.
I am not sure why you have a <form> nested within a <form> here, but you'll want to remove the inner one since it's not doing anything.
You want to setup your form to POST the data to your backend when submitted. If you don't specify an action, then it will POST to the same page the same page that you're currently viewing.
<form method="POST">
Asset Tag:<br>
<input type="text" name="tag"><br>
<input type="submit" value="Submit">
</form>
You need to setup your route to accept a POST request so that it can receive data from the form on your page. See here for more information on HTTP methods.
#app.route('/py', methods=['GET', 'POST'])
Inside of your route, you'll want to check whether it was a GET request (and load a normal page) or whether it was a POST (form data was sent so we should use it)
from flask import request
#app.route('/py', methods=['GET', 'POST'])
def server():
if request.method == 'POST':
# Then get the data from the form
tag = request.form['tag']
# Get the username/password associated with this tag
user, password = tag_lookup(tag)
# Generate just a boring response
return 'The credentials for %s are %s and %s' % (tag, user, password)
# Or you could have a custom template for displaying the info
# return render_template('asset_information.html',
# username=user,
# password=password)
# Otherwise this was a normal GET request
else:
return render_template('main.html')

Categories