I apologize for any misinformation from the title but I'm really not sure what the issue is. I'm creating a demo project that receives a user's name and age from an HTML form. Then, there are two buttons. One adds the information to an sqlite3 database called people.db. The other retrieves one person randomly from the database and displays it.
Here is my code:
import os
import sqlite3
from flask import Flask
from flask import request
from flask import render_template
from flask import g
app = Flask(__name__)
#app.route('/', methods=['POST', 'GET'])
def hello():
error = None
if request.form.get('submit', None) == "add":
if request.form['name'] and request.form['age']:
name = request.form['name']
age = request.form['age']
database = connect_db()
cursor = database.cursor()
sql = "INSERT INTO person (name, age) VALUES ({0}, {1});".format(name, age)
cursor.execute(sql)
database.commit()
return render_template("index.html")
else:
error = "Name or age not provided."
return render_template('index.html', error=error)
elif request.form.get('submit', None) == "retrieve":
database = connect_db()
cursor = database.cursor()
sql = "SELECT * FROM person ORDER BY RANDOM() LIMIT 1;"
cursor.execute(sql)
result = cursor.fetchone()
return render_template("index.html")
return render_template("index.html")
if __name__ == "__main__":
app.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))
So, the issue is that when I run the program on Cloud 9's c9users.io platform, it attempts to go to http://project-username.c9users.io:8080/localhost/?name=name&age=22&submit=add. I don't understand why it's trying to access localhost here. My program's structure is as follows:
\website-test
\templates
index.html
hello.py
people.db
So, I suppose it should be returning to the root of the website while performing the desired functionality. How do I achieve that?
Thank you!
Here, also, is my index.html:
<!DOCTYPE html>
<html>
<head>
<title>WEBSITES</title>
</head>
<body>
<h2>Please enter your name and age.</h2>
<form action="localhost/">
<input type="text" name="name" placeholder="name">
<input type="text" name="age" placeholder="age">
<input type="submit" name="submit" value="add">
<input type="submit" name="submit" value="retrieve">
</form>
</body>
</html>
By default Flask run your application on localhost. Add below lines of code to end of the file.
if __name__ == "__main__":
app.run(host='0.0.0.0')
0.0.0.0 here means, the app will take the host as your ip and will be accessible publically. For further reference read here in documentation.
What is in your index.html? Sounds like you have action="localhost/" on the form element
Related
I'm hoping someone can help me, i am a complete beginner with Flask and Postgres.
Basically, I created a python file, that takes user input to query the existing postgres database, this works perfectly. However, now I want to create a flask web app to do the exact same.
Accept the user will input the name on the html text box, and once the user hits submit, it needs to query the Postgresql database and return the requested columns for that specific row, exactly like the db_test.py file does.
Below is my python file that works and give me the expected results, but when I tried to create the app.py file with the html file, I am not able to get it to work, and I'm sure I'm missing something simple, but I don't know what.
This is the db_connect.py file that works - now I want to create the same results using flask and html.
# This is the db_test.py file which works as expected.
import psycopg2
# This section will try to create a Database Connection
try:
db_connection = psycopg2.connect(
host="localhost",
database="my_db",
user="postgres",
password="password",
port=5432
)
# This section will test Database Connection and return an exception if the connection fails.
print("Connected to server successfully")
except psycopg2.DatabaseError as Error:
print(f"Connection failed to server {Error}")
# This is the user input for that will be used to query the database table.
name = input("What is the name? ").title()
# This is the cursor for querying the Database table for the name that the user input and prints out the title, name and email
cursor.execute(
"SELECT id, name, email FROM details WHERE name = %s", (name,))
details = cursor.fetchall()
for d in details:
print(d)
# This Cursor closes the database connection and an If Statement to check and confirm that the database connection is closed.
cursor.close()
# This closes the connection to the Database
if db_connection:
db_connection.close()
print("Disconnected from server")
This is the second part of the project, with flask and html, but I can't get it to work.
This is the app.py file:
import creds
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
# initialising the app
app = Flask(__name__)
app.config['SECRET_KEY'] = f"{creds.thisisasecret}"
# This is the Database URI
app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://{creds.username}:{creds.password}#localhost:5432/{creds.database}"
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = True
db = SQLAlchemy(app)
class Details(db.Model):
__tablename__ = 'details'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(length=50))
email = db.Column(db.String(length=30))
#app.route("/")
def show_details():
return render_template("index.html", details=details.query.all())
app.run(debug=True, host="127.0.0.1", port=3000)
And this is the index.html file which also displays the text box with a submit button, but when i enter the name, nothing happens.
<body>
<div>
DB Search
</div>
<div>
<form action="{{url_for('show_details')}}" method="GET">
<input type="text" name="title" placeholder="Name">
<button type="submit">Submit</button>
</form>
</div>
<hr/>
</body>
I have re-written the app.py and html file, I believe it's a lack of knowledge but all the research I'm doing online is not helping me fix this problem.
Basically when I type the name in the text box on the html page and click on submit, it should return the id, name and email on the html page.
Can someone please point me in the right direction?
Generally, to process form input with Flask, you'd define the form as below:
<form method="POST">
then, to process it in Flask:
#app.route("/", methods=["GET", "POST"])
def show_details():
if request.method == "POST":
form_data = request.form
name_entered_in_form = form_data["title"] # Access form field by `name=` parameter
new_details = ... # populate data based on name entered
return render_template("index.html", details=new_details)
return render_template("index.html", details=details.query.all())
this code provides details about all fields in the database by default, and when a name is passed in and submitted, it passes in just those details to the exact same page. Note how the same app route ("/") is able to handle both types of requests - GET requests for displaying data and POST requests for handling submitted data.
from flask import Flask, request, redirect
app = Flask(__name__)
#app.route('/signup', methods=['POST'])
def signup():
email = request.form['email']
print("Adresa de email este: " + email)
return redirect('/')
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="/signup" method = "post">
<input type = "text" name = "email"></input>
<input type = "submit" value = "Signup"></input>
</form>
</body>
</html>
So I m trying to print the email that I m writing in the html form but I get the following error:
" Your file couldn’t be accessed.
It may have been moved, edited, or deleted.
ERR_FILE_NOT_FOUND ".
The html file is in the specific PyCharm directory, near the main.py file.
You redirect('/') after processing the POST data. But / is not a route that you defined in your flask app. Therefore when your browser follows that redirect I assume it shows the ERR_FILE_NOT_FOUND error, which is a simple 404 error page generated by it (Chrome?).
That's not an error on the Python/Flask server though. There in the stdout print you should see the email value just fine.
If you assumed to see the email in the browser instead, you should have done something like
def signup():
email = request.form['email']
return email # DEBUG return
I am attempting to gain user input from a html file and pass it into a function that is located in another python file within the same directory.
The user should input their username and password into the html webpage and the inputs will be passed into another a python file to run numerous validation functions.
Some help or guidance would be much appreciated :)
Thank you
form.html file
<form action="{{ url_for("gfg")}}" method="post">
<label for="username">username:</label>
<input type="text" id="username" name="username" placeholder="username">
<label for="password">password:</label>
<input type="text" id="password" name="password" placeholder="password">
<button type="submit">Login</button>
app.py file
# importing Flask and other modules
from flask import Flask, request, render_template
# Flask constructor
app = Flask(__name__)
# A decorator used to tell the application
# which URL is associated function
#app.route('/', methods=["GET", "POST"])
def gfg():
if request.method == "POST":
# getting input with name = fname in HTML form
username = request.form.get("username")
# getting input with name = lname in HTML form
password = request.form.get("password")
return username + password
return render_template("form.html")
if __name__ == '__main__':
app.run()
main python file (where functions are located)
def main():
username = app.gfg()[0]
password = app.gfg()[1]
TestLogin(username, password)
if __name__ == "__main__":
main()
You need to use the request context.
RuntimeError: Working outside of request context.
This typically means that you attempted to use functionality that
needed an active HTTP request. Consult the documentation on testing
for information about how to avoid this problem.
[...]
with app.test_request_context(
'/url/', data={'format': 'short'}):
username = app.gfg()[0]
password = app.gfg()[1]
TestLogin(username, password)
[...]
You can have a look at the docs
I got an error when trying to run my Flask app of: BuildError: Could not build url for endpoint 'result' with values ['resultFound']. Did you mean 'menu' instead?
The problem has to do with the calling of POST. I have attached the code for 4 files that relate to this error, but I left out the import packages and other parts of the files. I would greatly appreciate your help. Thanks a lot. If you would like any other code I could add it.
This is my main python function that is running the flask app.
#app.route("/search", methods=["POST", "GET"])
def search():
if request.method == "POST":
user = request.form["searching"]
return redirect(url_for('result', resultFound = user))
else:
return render_template("search.html")
app.route("/<resultFound>")
def result(resultFound):
return render_template('result.html', nameartist = artistName(resultFound), numfollowers = artistfollower(resultFound))
This is the python file that is getting the information for the results.html with the input value from the search.html.
def artists(searchinput):
searchResults = spotifyObject.search(searchinput,1,0,"artist")
artist = searchResults['artists']['items'][0]
return artist
def artistname(inputvalue):
value = artists(inputvalue)
artistName = value['name']
return artistName
def artistfollower(inputvalue):
value = artists(inputvalue)
artistfollowers = value['followers']['total']
return artistfollowers
This is the search.html that gets the input value.
<form action="#" method="post">
<input type="text" id="myText" name="searching" value="input artist">
<p><input type="submit" value="submit" /></p>
</form>
This is the result.html that is using the input value from search.html and getting data with the help of the python file.
<p>The artist {{ nameartist }} has {{ numfollowers }} followers.</p>
BuildError: Could not build url for endpoint 'result' with values ['resultFound'].
because you are missing # in result route decorator (#app and not app)
#app.route("/<resultFound>")
def result(resultFound):
[..]
when i click on submit button i get an error which says:
"TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Database' object it is failing because no such method exists."
here is my signin.py code :
from flask import Flask, request, render_template
from pymongo import MongoClient
#app = Flask(__name__)
connection = MongoClient()
db = connection.project #database name.
collection = connection.signup # collection name.
#app.route('/signin/')
def index_show():
return render_template('signin.html')
#app.route('/signin/', methods = ['POST'])
def signup_form():
username = request.form['user']
passowrd = request.form['pass']
collection.insert({'user': username, 'passoword': passowrd})
if __name__ == '__main__':
app.run(debug = True)
my html file code is here :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action=".">
<input type="text" name="user" /><br/><br/>
<input type="password" name="pass" /><br/><br/>
<input type="submit" name="submit" /><br/><br/>
</form>
</body>
The method has been deprecated and is changed to .insert_one() in the pymongo 3.x driver, there is also .insert_many() for multiple document creation:
collection.insert_one({'user': username, 'passoword': passowrd})
The .insert() method is now only supported in the 2.x and lower series.
I think, the root cause is in this line:
collection = connection.signup # collection name.
Contrary to the comment, you're getting a DB named signup. That should rather be:
collection = db.signup
please do make sure that you do this to an existing database,object has been returned successfully.
here is my code:
from pymongo import MongoClient
client=MongoClient()
db=client.testdb
new={"shopclues":1234,"rating":3}
result=db.testdb.insert_one(new)
result.inserted_id
ObjectId('59e2f0f2031b4b0b27ecfa09')