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.
Related
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 am working with rasa(latest version),but not able to send response to chatbot just because of handle_channel method,right now i am getting following error
"error": "Object of type coroutine is not JSON serializable"
Here is my code,where i am wrong ?
#app.route('/api/v1/<sender_id>/respond', methods=['GET', 'POST'])
def respond(self, request, sender_id):
request.setHeader('Content-Type', 'application/json')
request.setHeader('Access-Control-Allow-Origin', '*')
request_params = request_parameters(request)
if 'query' in request_params:
message = request_params.pop('query')
elif 'q' in request_params:
message = request_params.pop('q')
else:
request.setResponseCode(400)
return json.dumps({"error": "Invalid parse parameter specified"})
try:
out = CollectingOutputChannel()
response = self.agent.handle_message(message, output_channel=out, sender_id=sender_id)
request.setResponseCode(200)
return json.dumps(response)
except Exception as e:
request.setResponseCode(500)
logger.error("Caught an exception during "
"parse: {}".format(e), exc_info=1)
return json.dumps({"error": "{}".format(e)})
are you sure that you are not mixing methods up here? According to the documentation, you might either want to try:
handle_message(message, message_preprocessor=None, **kwargs)
or
handle_text(text_message, message_preprocessor=None, output_channel=None, sender_id='default')
Keep in mind to import the right libraries since there was a renaming since 1.0, just in case.
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)
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
Here is the code:
import urllib2 as URL
def get_unread_msgs(user, passwd):
auth = URL.HTTPBasicAuthHandler()
auth.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s'%user,
passwd=passwd
)
opener = URL.build_opener(auth)
URL.install_opener(opener)
try:
feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
return feed.read()
except:
return None
It works just fine. The only problem is that when a wrong username or password is used, it takes forever to open to url #
feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
It doesn't throw up any errors, just keep executing the urlopen statement forever.
How can i know if username/password is incorrect.
I thought of a timeout for the function but then that would turn all error and even slow internet into a authentication error.
It should throw an error, more precisely an urllib2.HTTPError, with the code field set to 401, you can see some adapted code below. I left your general try/except structure, but really, do not use general except statements, catch only what you expect that could happen!
def get_unread_msgs(user, passwd):
auth = URL.HTTPBasicAuthHandler()
auth.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%s'%user,
passwd=passwd
)
opener = URL.build_opener(auth)
URL.install_opener(opener)
try:
feed= URL.urlopen('https://mail.google.com/mail/feed/atom')
return feed.read()
except HTTPError, e:
if e.code == 401:
print "authorization failed"
else:
raise e # or do something else
except: #A general except clause is discouraged, I let it in because you had it already
return None
I just tested it here, works perfectly