Firestore get() fetches no data in Flask - python

I'm unable to get data from the firebase cloud firestore on my production server. I have the following code:
#app.route('/forgot-password', methods=['GET','POST'])
def forgotpassword():
if 'email' in session:
return redirect(url_for('profile'))
form = ForgotPasswordForm()
if form.validate_on_submit():
try:
user_ref = db.collection(u'users').document(form.email.data)
user = user_ref.get()
except Exception as e:
print(e)
if user.exists:
try:
auth.send_password_reset_email(form.email.data)
print(form.email.data)
flash('A link to reset your password has been sent to your mail.', 'success')
except Exception as e:
print(e)
flash('There was an error while sending the email.', 'danger')
else:
print("not registerd")
flash('This email is not registered.', 'danger')
print(form.errors)
return render_template('forgotPasswordPage.html', form=form)
I am not getting any output for the exception since none seems to be thrown. The same code works on my localhost but not on the production server.
db.collection(u'users').document(form.email.data) succesfully returns a firestore document object but the get() function is the one causing the problem. What could be the problem?

Related

Python-lunch Syntax Error: except ImportError , e: [duplicate]

I have this code:
#app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
session['username'] = request.form['username']
session['password'] = request.form['password']
try:
# use reddit_api's login
r.login(user=session['username'], password=session['password'])
except InvalidUserPass, e:
error = 'Incorrect username or password. '
if not error:
subreddits = r.user.get_my_reddits(limit=25)
my_reddits = []
for i in range(25):
my_reddits.append(subreddits.next().display_name)
session['my_reddits'] = my_reddits
return redirect(url_for('index'))
return render_template('login.html', error=error)
In 2.x, it worked fine, but in 3.x I get an error message like:
File "app.py", line 101
except InvalidUserPass, e:
^
SyntaxError: invalid syntax
Why does this occur, and how can I fix it?
Change
except InvalidUserPass, e:
to
except InvalidUserPass as e:
See this for more info.
Simply except InvalidUserPass as e:. And for heaven's sake, let's get rid of the ugly error thing:
#app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
session['password'] = request.form['password']
try:
# use reddit_api's login
r.login(user=session['username'], password=session['password'])
except InvalidUserPass as e:
return render_template('login.html',
error='Incorrect username or password.')
subreddits = r.user.get_my_reddits(limit=25)
my_reddits = []
for i in range(25):
my_reddits.append(subreddits.next().display_name)
session['my_reddits'] = my_reddits
return redirect(url_for('index'))
return render_template('login.html')
In python3 it's:
except InvalidUserPass as e:
In Python 2.x, the syntax except ExampleError, e: means that exceptions of the type ExampleError will be caught, and the name e will be used for that exception inside the except block.
In 3.x, the closest equivalent syntax is except ExampleError as e:. (This will also explicitly delete the name e after the except block has ended, unlike in 2.x where it will remain defined.)
If this error occurs in your own code, simply fix it accordingly.
If this error occurs in library code (example, example), this indicates that either the library does not support modern versions of Python, or else the installation is out of date and upgrading to a newer library version is necessary. Please read the documentation for the library in order to check version compatibility, and do not try to fix it yourself (unless you intend to take over the entire project.)
When getting the error
file /usr/libexec/urlgrabber-ext-down line 28
except oserror, e:
invalid syntax
modify /usr/bin/yum and /usr/libexec/urlgrabber-ext-dow files by changing #!/usr/bin/python to #!/usr/bin/python2.
issue would be resolved.

Arresting Flask Mail delivery failure

I have the following code that I believed would help me check if email is provided is valid and would be accepted for delivery:
#app.route("/email_send/<email>")
def email_send(email=None):
return_message=None
msg = Message('Online Enquiry', sender='sender#gmail.com', recipients=[email])
msg.body ='We have received your message. We shall be communicating with you'
try:
mail.send(msg)
return_message='SUCCESS'
except Exception as e:
return_message='FAILED'
return json.dumps(str(return_message))
The problem is that it is always returning 'SUCCESS' even when I get address not found in gmail

Creating users in text or json file and use it to the login to the python web

I've made simple web. This is the method which I use to basic login to the web:
#app.route('/signin/', methods=['GET', 'POST'])
def signin_page():
error = None
try:
if request.method == "POST":
attempted_email= request.form['email']
attempted_password = request.form['password']
flash(attempted_email)
flash(attempted_password)
if attempted_email == "admin#gmail.com" and attempted_password == "admin":
return redirect(url_for('homepage'))
else:
error = "Invalid credentials. Try again."
except Exception as e:
flash(e)
return render_template("signin.html", error = error)
How can I modify that code if I want to take the users data from txt or json file (I want to make it using basic editor txt), which contains information about users (email, password, etc.) ?
How can I compare typed string in login form with content of the file ?
I assume you have a text file with the content username:password. You can now do something like:
PW_FILE = 'path/to/file/'
def check_credentials(username: str, password: str) -> bool:
# load content of file
with open(PW_FILE) as fh:
content = fh.read().strip('\n') # and remove newlines
credentials = content.split(':', 1) # get credentials as list `[username, password]`
return credentials == [username, password]
#app.route('/signin/', methods=['GET', 'POST'])
def signin_page():
...
if check_credentials(attempted_email, attempted_password):
return redirect(url_for('homepage'))
else:
error = "Invalid credentials. Try again."
...
In general, you should not catch an unspecific exception, as you might swallow some unexpected behaviour. I am not familiar with the framework you are using, but I would suggest changing your error handling to be more specific, something like
#app.route('/signin/', methods=['GET', 'POST'])
def signin_page():
error = None
if request.method == "POST":
try:
attempted_email= request.form['email']
attempted_password = request.form['password']
except KeyError:
error = "Missing form data"
else:
if check_credentials(attempted_email, attempted_password):
return redirect(url_for('homepage'))
else:
error = "Invalid credentials. Try again."
return render_template("signin.html", error = error)

Python Flask Mailchimp signup

I'm trying to use PostMonkey & Flask to HTTP GET an email address (from a from on my website) and then subscribe this to the specified list.
It works and sends the email requesting the user to confirm the subscription, but either server error 500's or when debug mode is on it comes up with
TypeError: signup() takes no arguments (2 given)
Here's my code:
#app.route("/signup", methods=['GET'])
def signup():
try:
email = request.args.get('email')
pm.listSubscribe(id="cdc2ba625c", email_address=email)
except MailChimpException, e:
print e.code
print e.error
return redirect("/")
return signup
I'm not sure what's causing it and it's been bugging me for a while!
If anyone is interested the problem was related to my 'Return' statement, turns out flask doesn't like returning nothing.
#app.route('/signup', methods=['POST'])
def signup():
try:
email = request.form['email']
#email = request.args.get('email')
pm.listSubscribe(id="cdc2ba625c", email_address=email, double_optin=False)
except MailChimpException, e:
print e.code
print e.error
return redirect("/")
return render_template('index.html')
Thanks to all those that commented back

Exception Handling in google app engine

i am raising exception using
if UserId == '' and Password == '':
raise Exception.MyException , "wrong userId or password"
but i want print the error message on same page
class MyException(Exception):
def __init__(self,msg):
Exception.__init__(self,msg)
You are not using the Users API? Assuming you are handling a POST request, how about this:
class LoginError(Exception):
CODES = { 'mismatch': 'Wrong credentials', 'disabled': 'Account disabled' }
...
try:
// your authentication code
raise LoginError('mismatch')
...
raise LoginError('disabled')
except LoginError as e:
self.redirect(your_login_url + '?err=' + e)
# In login page you must not print arbitrary GET parameter directly
err_reason = LoginError.CODES[self.request.get('err')]`
(Login request should be using POST method because it changes the server's state, and it's good habit to redirect after a POST, thus a redirect.)
Why raising an exception instead of just stop function execution and redirect to new page using return statement

Categories