Insert data into with pymongo and flask - python

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')

Related

Problem getting html form data through Flask and Python

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

Flask - Obtain Input from HTML page and pass input into a function in another Python file

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

Linking Flask to PostgresQL

I am having issues linking my flask program to Postgre SQL
import os
from flask import Flask, session
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from flask import Flask, render_template, request
from models import db
app = Flask(__name__)
POSTGRES = {
'user': 'user',
'pw': 'password',
'db': 'database',
'host': '127.0.0.1',
'port': '5432',
}
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set")
# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))
#app.route("/")
def index():
return render_template("index.html")
#app.route("/register",methods=['GET','POST'])
def register():
return render_template("register.html")
if request.method=='POST':
name=request.form['username']
password=request.form['password']
connection = mysql.get_db()
cursor = connection.cursor()
query="INSERT INTO 'userdetails'(username,password) VALUES(%s,%s)"
cursor.execute(query,(username,password))
connection.commit()
#app.route("/login")
def login():
return render_template("login.html")
Register.html
<html>
<head>
<title>Project1</title>
</head>
<form method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Register">
</form>
</html>
I have already specified the DATABASE_URl when setting up with the credentials given by Heroku. I cannot manage to store the username and password into the database. The register.html page contains a form with username input field and password input field. Help will be appreciated.
P.S I know I left postgre details, they have nothing important. Just help me out.
Thanks
Within the form element you should define the action attribute
e.g. <form method="POST" action="/register">
action attribute specifies where the data gets sent (source MDN Web Docs)
In order to simplify using SQLAlchemy with Flask you can use the Flask-SQLAlchemy extension.
You can link PostgreSQL and Python by using a PostgreSQL adapter. A popular choice is psycopg2.

Cloud 9 and Flask issue with localhost

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

Beginner Pythonanywhere Query

Edit 3:
I am trying to display info from a csv file on pythonanywhere, prompted from a user input into a form.
I have loaded the client_db.csv onto my files on pythonanywhere here:'/home/myusername/mydirectory/client_db.csv'.
Essentially, the user would 'Enter an address: (form)', and values for 'name', 'shack', 'status' and 'payments' would display.
Here is my attempt so far (v3), but I am not getting it to work. I suspect there is something wrong with the html input?
from flask import Flask
import os
import sys
import csv
import numpy as np
app = Flask(__name__)
app.config["DEBUG"] = True
path = '/home/myusername/ishack'
if path not in sys.path:
sys.path.append(path)
client_db = np.genfromtxt('/home/myusername/ishack/client_db.csv', delimiter=',',dtype=None, names=True)
#app.route('/')
def form()
return """
<html>
<body>
<h1>Enter a Shack Number</h1>
<form action="/address" method="POST">
<textarea class="form-control" name="address" placeholder="Enter a Shack Number"></textarea>
<input type="submit" />
</form>
</body>
</html>
"""
#app.route('/address', methods=["POST"])
def display_info(address):
ind = np.where(client_db['Shack']==address)[0]
return {'Name': client_db['Name'][ind],
'Shack': client_db['Shack'][ind],
'Status': client_db['Status'][ind],
'Payments': client_db['Payments'][ind]}
display_info(address)
You are having minor problems in the code just posted:
There are minor errors like missing colons and so
Additionally, note you are indexing wrongly the matrix, putting first the column and later the row, when it is exactly the opposite. The correct sentence is (note ind is before Name for example):
return {'Name': client_db[ind]['Name'][0],
'Shack': client_db[ind]['Shack'][0],
'Status': client_db[ind]['Status'][0],
'Payments': client_db[ind]['Payments'][0]}
The last problem is related to the POST of the form. To grab the address data you must use: address = request.form["address"]
For finishing your code, this example returns a JSON data with the fields found in the CSV file:
from flask import Flask, request, Response
from flask import request
import json
import os
import sys
import csv
import numpy as np
app = Flask(__name__)
app.config["DEBUG"] = True
path = '/home/myusername/ishack'
if path not in sys.path:
sys.path.append(path)
client_db = np.genfromtxt('/home/myusername/ishack/client_db.csv', delimiter=',', dtype=None, names=True)
#app.route('/')
def form():
return """
<html>
<body>
<h1>Enter a Shack Number</h1>
<form action="/address" method="POST">
<textarea class="form-control" name="address" placeholder="Enter a Shack Number"></textarea>
<input type="submit" />
</form>
</body>
</html>
"""
#app.route('/address', methods=["POST"])
def display_info():
address = request.form["address"]
ind = np.where(client_db['Shack'] == address)[0]
res = {'Name': client_db[ind]['Name'][0],
'Shack': client_db[ind]['Shack'][0],
'Status': client_db[ind]['Status'][0],
'Payments': client_db[ind]['Payments'][0]}
return Response(json.dumps(res), mimetype='application/json')
app.run(host="0.0.0.0", port=5000)

Categories