Malformed IP address error - python

I am trying to run a project but everytime I try loading a specific page it throws away the following stack of error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restplus/api.py", line 536, in error_router
return original_handler(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/nitin/Desktop/open-event-orga-server/app/views/users/events.py", line 91, in create_view
current_timezone = get_current_timezone()
File "/home/nitin/Desktop/open-event-orga-server/app/helpers/wizard/helpers.py", line 17, in get_current_timezone
match = geolite2.lookup(get_real_ip(True) or '127.0.0.1')
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 364, in lookup
return self._get_actual_db().lookup(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 204, in lookup
return self._lookup(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 249, in _lookup
packed_addr = pack_ip(ip_addr)
File "/usr/local/lib/python2.7/dist-packages/geoip.py", line 37, in pack_ip
raise ValueError('Malformed IP address')
ValueError: Malformed IP address
[2017-01-22 00:34:24 +0000] [6835] [ERROR] Error handling request /socket.io/?EIO=3&transport=websocket&sid=8bed14818d4046edb35bbc87f27d5164
And I am unable to figure out what exactly is a malformed IP address and the reason behind this error.
Following is the get_current_timezone() function:
def get_current_timezone():
match = geolite2.lookup(get_real_ip(True) or '127.0.0.1')
if match is not None:
return match.timezone
else:
return 'UTC'
And following is the get_real_ip() method:
def get_real_ip(local_correct=False):
try:
if 'X-Forwarded-For' in request.headers:
ip = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
else:
ip = request.remote_addr or None
if local_correct and (ip == '127.0.0.1' or ip == '0.0.0.0'):
ip = urlopen('http://ip.42.pl/raw').read() # On local test environments
except:
ip = None
return ip
And the following is the portion of create event view that is creating this problem.:
#events.route('/create/', defaults={'step': ''})
#events.route('/create/<step>')
def create_view(step):
if step != '':
return redirect(url_for('.create_view', step=''))
hash = get_random_hash()
if CallForPaper.query.filter_by(hash=hash).all():
hash = get_random_hash()
current_timezone = get_current_timezone()
return render_template(
'gentelella/admin/event/wizard/wizard.html',
current_date=datetime.datetime.now(),
event_types=DataGetter.get_event_types(),
event_licences=DataGetter.get_event_licences(),
event_topics=DataGetter.get_event_topics(),
event_sub_topics=DataGetter.get_event_subtopics(),
timezones=DataGetter.get_all_timezones(),
cfs_hash=hash,
current_timezone=current_timezone,
payment_countries=DataGetter.get_payment_countries(),
payment_currencies=DataGetter.get_payment_currencies(),
included_settings=get_module_settings())

Related

Flask dance Facebook login error on Google cloud run

I'm trying to add Facebook login using Flask-Dance on my website, but I'm having some issues. Locally, using ssl_context='adhoc', it works fine. But when I try to login on my app that is running on Google Cloud Run I'm getting into the following error:
Default
2021-04-07T02:16:12.738640ZTraceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python3.8/dist-packages/flask/_compat.py", line 39, in reraise raise value File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1936, in dispatch_request return self.view_functionsrule.endpoint File "/usr/local/lib/python3.8/dist-packages/flask_dance/consumer/oauth2.py", line 256, in authorized token = self.session.fetch_token( File "/usr/local/lib/python3.8/dist-packages/requests_oauthlib/oauth2_session.py", line 239, in fetch_token self._client.parse_request_uri_response( File "/usr/local/lib/python3.8/dist-packages/oauthlib/oauth2/rfc6749/clients/web_application.py", line 203, in parse_request_uri_response response = parse_authorization_code_response(uri, state=state) File "/usr/local/lib/python3.8/dist-packages/oauthlib/oauth2/rfc6749/parameters.py", line 262, in parse_authorization_code_response raise InsecureTransportError() oauthlib.oauth2.rfc6749.errors.InsecureTransportError: (insecure_transport) OAuth 2 MUST utilize https.
Here is the code I'm using:
facebook_blueprint = make_facebook_blueprint(scope='email', login_url='/facebook')
facebook_blueprint.backend = SQLAlchemyStorage(OAuth, db.session, user=current_user)
#users.route('/login-facebook')
def login_facebook():
if not facebook.authorized:
return redirect(url_for('facebook.login'))
account_info = facebook.get('/me?fields=name,email')
if account_info.ok:
account_info_json = account_info.json()
check_facebook_account(email = account_info_json['email'], name = account_info_json['name'])
return redirect(url_for('artes_e_telas.artes_finalizadas'))
#oauth_authorized.connect_via(facebook_blueprint)
def facebook_logged_in(blueprint, token):
account_info = blueprint.session.get('/me?fields=name,email')
if account_info.ok:
account_info_json = account_info.json()
check_facebook_account(email = account_info_json['email'], name = account_info_json['name'])
return redirect(url_for('artes_e_telas.artes_finalizadas'))
This "check_facebook_account" is just to commit the result on the database.
On Cloud Run log I can see that really exists a http request:
2021-04-06 22:17:26.728 BRT
GET
302
673 B
5 ms
https://rapiart.com.br/login-facebook
2021-04-06 22:17:26.900 BRT
GET
302
0 ms
http://rapiart.com.br/facebook
2021-04-06 22:17:27.068 BRT
GET
302
1.46 KiB
6 ms
https://rapiart.com.br/facebook
Can someone help me, please?

How do I route data from one page to other in flask?

I have a page index.html that has to send two values to main.html. From index.html, I send an ajax request to /api/session_load with a json object data. I call the redirect function to main
#app.route('/')
def index():
return render_template('index.html')
#app.route('/main')
def main(names):
print('Hello-main')
print('main', names, type(names))
return render_template('main.html', nomens = names)
#app.route('/api/session_load', methods=['GET', 'POST'])
def session_load():
if request.method == "POST":
data = json.loads(request.get_data())
global session_name
global file_name
session_name = data['session_name']
file_name = data['file_name']
print('sess', data, type(data))
return redirect(url_for('main', names = data))
This is the output
* Restarting with stat
* Debugger is active!
* Debugger PIN: 147-211-412
sess {'file_name': 'sample.txt', 'session_name': 'asfds'} <class 'dict'>
127.0.0.1 - - [09/May/2019 00:04:32] "POST /api/session_load HTTP/1.1" 302 -
127.0.0.1 - - [09/May/2019 00:04:32] "GET /main?names=%7B%27file_name%27%3A+%27sample.txt%27%2C+%27session_name%27%3A+%27asfds%27%7D HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/300041738/.arun-venv3/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
TypeError: main() missing 1 required positional argument: 'names'
main.html file has proper templating with {{ nomens }}. Both statements of main() don't print.
#app.route('/main') should be #app.route('/main/<string:names>'). You need to tell flask the url is expecting something else after your route name.

Python ldap function behaves differently when called in flask

So I'm trying get auto-complete to work with python-ldap and flask.
Here's a test script ldapA.py:
import ldap
#first you must open a connection to the server
def query():
try:
l = ldap.open("server.net")
## searching doesn't require a bind in LDAP V3. If you're using LDAP v2, set the next line appropriately
## and do a bind as shown in the above example.
# you can also set this to ldap.VERSION2 if you're using a v2 directory
# you should set the next option to ldap.VERSION2 if you're using a v2 directory
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
username="CN=user user,OU=bbbgbg,OU=bdbfd,DC=dsffd,DC=net"
passw="adsada"
l.simple_bind_s(username,passw)
except ldap.LDAPError, e:
print e
# handle error however you like
## The next lines will also need to be changed to support your search requirements and directory
baseDN = "ou=xds, ou=sd, dc=sd, dc=net"
searchScope = ldap.SCOPE_SUBTREE
## retrieve all attributes - again adjust to your needs - see documentation for more options
retrieveAttributes = ['name']
searchFilter = "name=*jace*"
try:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = l.result(ldap_result_id, 0)
if (result_data == []):
break
else:
## here you don't have to append to a list
## you could do whatever you want with the individual entry
## The appending to list is just for illustration.
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
res = result_set[0]
res1 = res[0]
res2 = res1[1]
res3 = res2["name"]
print res3[0]
except ldap.LDAPError, e:
print e
query()
It works as intended when I run it. It gives me my name from the AD.
Now when I call it from flask like this:
from flask import render_template
from app import app
from flask import request
from ldapA import query
#app.route('/')
#app.route('/index')
def index():
return render_template("index.html")
#app.route('/autocomplete', methods=['GET'])
def autocomplete():
return query()
I get:
127.0.0.1 - - [19/Jul/2017 14:08:58] "GET /autocomplete HTTP/1.1" 500 -
Traceback (most recent call last):
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/jgar/receptionsignin/app/views.py", line 13, in autocomplete
return query()
File "/home/jgar/receptionsignin/ldapA.py", line 36, in query
result_type, result_data = l.result(ldap_result_id, 0)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 703, in result
resp_type, resp_data, resp_msgid = self.result2(msgid,all,timeout)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 707, in result2
resp_type, resp_data, resp_msgid, resp_ctrls = self.result3(msgid,all,timeout)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 714, in result3
resp_ctrl_classes=resp_ctrl_classes
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 734, in result4
resp_data = self._bytesify_results(resp_data, with_ctrls=add_ctrls)
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 266, in _bytesify_results
for (dn, fields) in results
File "/home/jgar/receptionsignin/flask/lib/python2.7/site-packages/ldap/ldapobject.py", line 219, in _maybe_rebytesify_text
assert isinstance(value, text_type), "Should return text, got bytes instead (%r)" % (value,)
AssertionError: Should return text, got bytes instead ('CN=sdsddsc,OU=sds,OU=sds,DC=sdds,DC=net')
I know that this line causes the trouble:
ldap_result_id = l.search(baseDN, searchScope, searchFilter, retrieveAttributes)
But I'm stumped as to why it happens when called in flask and not when run with python ldapA.py.
It seems to be the ldap lib internal error, but why does it only happen in flask and how could I fix it?
Thanks guys!
Turns out it was a unicode problem, for anyone having the same error:
Go to ldpaobject.py(whererver you have python-ldap installed)
Change
if PY2:
text_type = unicode
else:
text_type = str
to just
text_type = str
python-ldap should now work in flask

Inexplicable KeyError in my flask code in the traceback

This bug is driving me nuts. I am trying to create the backend of a website in python using flask. I am getting the following error and traceback:
KeyError
KeyError: 'person_id'
Traceback (most recent call last)
This is the Copy/Paste friendly version of the traceback. You can also paste this traceback into a gist:
Traceback (most recent call last):
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/antonina/Desktop/ant/nic/blog/views.py", line 310, in family_tree
subject_id = session['person_id']
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/werkzeug/local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'person_id'
Also in other form of this traceback:
KeyError
KeyError: 'person_id'
Traceback (most recent call last)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1985, in wsgi_app
[Open an interactive python shell in this frame] response = self.handle_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/antonina/Desktop/ant/nic/blog/views.py", line 310, in family_tree
subject_id = session['person_id']
File "/home/antonina/Desktop/ant/neo4j-flask/lib/python2.7/site-packages/werkzeug/local.py", line 377, in <lambda>
__getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'person_id'
The relevant code is the following, specifically in 3rd line which in my code has line number 310:
#app.route('/family_tree', methods=['GET','POST'])
def family_tree():
subject_id = session['person_id']
if request.method == 'POST':
if request.form['Select'] != 'RETURN' :
subject_id = request.form['Select']
if(subject_id == 'Not_registered') :
subject_id = session['person_id']
else :
return redirect(url_for('person'))
father = mother = ['Not_registered','Not_registered','Not_registered','Not_registered','Not_registered','Not_registered']
siblings = []
mother_node, father_node = Person(subject_id).get_parents()
if (mother_node) :
mother_id = (mother_node[0]['mother.person_id'])
mother = mother_id.split(';')
mother.append(mother_id)
mother.append(get_prof_pic(mother_id))
for sibling in Person(mother_id).get_children_mother() :
if sibling not in siblings and sibling != None and sibling['person.person_id'] != subject_id :
siblings.append(sibling)
if (father_node) :
father_id = (father_node[0]['father.person_id'])
father = father_id.split(';')
father.append(father_id)
father.append(get_prof_pic(father_id))
for sibling in Person(father_id).get_children_father() :
if sibling not in siblings and sibling != None and sibling['person.person_id'] != subject_id :
siblings.append(sibling)
subject = subject_id.split(';')
subject.append(subject_id)
subject.append(get_prof_pic(subject_id))
sibling_list = []
for sibling in siblings :
tmp = sibling['person.person_id'].split(';')
tmp.append(sibling['person.person_id'])
tmp.append(get_prof_pic(sibling['person.person_id']))
sibling_list.append(tmp)
children_f = Person(subject_id).get_children_father()
children_m = Person(subject_id).get_children_mother()
child_list = []
children = []
for child in children_f:
if child not in children and child != None :
children.append(child)
for child in children_m:
if child not in children and child != None :
children.append(child)
for child in children :
tmp = child['person.person_id'].split(';')
tmp.append(child['person.person_id'])
tmp.append(get_prof_pic(child['person.person_id']))
child_list.append(tmp)
return render_template('family_tree.html',
subject=subject,
mother=mother,
father=father,
sibling_list=sibling_list,
child_list=child_list
)

GAE ndb put() argument error

I am trying to save an object to GAE's datastore. When doing this I am getting the error:
Traceback (most recent call last):
File "/Users/Soderstrom/google-cloud-sdk/.install/.backup/platform/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/Soderstrom/PycharmProjects/MyApp/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/Soderstrom/PycharmProjects/MyApp/main.py", line 559, in backends
db.save(v.getFastigheter(), '1')
TypeError: put() takes exactly 1 argument (2 given)
This is independent of the actual amount of arguments passed to the entity creator.
db.save(v.getSomeData(), '1') <- main.py, line 559
db.load('1')
This is the db module:
class ndbc(ndb.Model):
val = ndb.PickleProperty(compressed=True, indexed=False)
key_name = ndb.PickleProperty(indexed=True)
#classmethod
def set(cls, key_t, val_t):
entity = cls(val=val, key_name=key)
entity.put()
return val_t
def save(obj, name):
return ndbc.set(name, obj)
Don't you mean entity = cls(val=val_t, key_name=key_t)? Also, key_name is an old db property. For ndb, you should use id:
https://docs.google.com/document/d/1AefylbadN456_Z7BZOpZEXDq8cR8LYu7QgI7bt5V0Iw/mobilebasic
Not sure id can be a PickleProperty. Interested to see if this works.

Categories