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
Related
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.
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?
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
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)
The below code successfully generates a token and sends a link to the user's inbox for confirmation. But when the user clicks on it, Flask is not recognizing the token it just created. Here is the error message:
"Got exception from ts.loads: 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."
The bottom line is that this is what should execute if I could make the confirmation procedure work properly:
return redirect(url_for('tutorials'))
But, as you can piece together by noting the error message that is coming out of #app.errorhandler(404), something is going wrong. I'm really stuck. These tests are being done way before the max_age of 86400 seconds is reached. Any help would be much appreciated!!!
from itsdangerous import URLSafeTimedSerializer
ts = URLSafeTimedSerializer(SECRET_KEY, salt='email-confirm-key')
#app.route('/signup', methods=['GET', 'POST'])
def signup():
#skipping unrelated lines of code
token = ts.dumps(form.email.data, salt='email-confirm-key')
subject = 'subject goes here'
msg = Message(subject=subject, sender='name#email.com', recipients=form.email.data.split())
link = url_for('confirm_email', token=token, _external=True)
msg.html = render_template("email_confirmationemail.html", link=link, name=request.form['first_name'])
with app.app_context():
mail.send(msg)
return redirect(url_for('checkyouremail'))
#app.route('/confirmemail/<token>')
def confirm_email(token):
try:
email = ts.loads(token, salt='email-confirm-key', max_age=86400)
#skipping unrelated lines of code
return redirect(url_for('tutorials'))
#app.errorhandler(404)
def not_found(e):
print('Got exception from ts.loads: {}'.format(e))
return render_template('404.html')
In models.py, my __init__ method for the User class has this line:
self.email = email.lower()
When users create a profile on a phone, their email address often starts with an uppercase letter.
So I just needed to change
token = ts.dumps(form.email.data, salt='email-confirm-key')
to
token = ts.dumps(form.email.data.lower(), salt='email-confirm-key')
so that the email held in the token matched with the email in the database when the user clicked on the confirmation link I sent them. (In short, adding .lower() as shown above in my call do dumps solved my problem).