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

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.

Related

Problem trying to add entry in db TypeError: __init__() error [duplicate]

This question already has answers here:
Flask-SQLAlchemy Constructor
(3 answers)
Closed 4 years ago.
I've searched for this and usually people have identation issues. I don't think the route should be in the class? But I've tried that and got the same error:
TypeError: __init__() takes exactly 1 argument (2 given)
class entry(db.Model):
id = db.Column(db.Integer, primary_key=True)
url = db.Column(db.String(100), unique=True, nullable=False)
def __repr__(self):
return '<entry %r>' % self.url
#app.route('/new', methods = ['POST'])
def new():
if request.method == 'POST':
if not request.args.get('url'):
flash('Please provide at least a url', 'error')
else:
entry2 = entry("hey") #error on this line, I put "hey" just to debug
db.session.add(entry2)
db.session.commit()
flash('Record was successfully added')
return redirect(url_for('show_all'))
return render_template('index2.html')
Complete error:
127.0.0.1 - - [10/Feb/2019 13:27:14] "POST /new?url=http://google.com
HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/dk9/code/prj/app2.py", line 41, in new
entry2 = entry("hey")
TypeError: __init__() takes exactly 1 argument (2 given)
You should not override the __init__ method in your entry model. Remove that method completely.
Edit
Models expect keyword arguments only. So you should do:
entry2 = entry(url="hey")

TypeError: decorator() missing 1 required positional argument: 'func'

I'm trying to use python huey (https://github.com/coleifer/huey/blob/master/huey/api.py) to allow usage of a task queue with flask.
Starting with a function:
def some_long_calculation():
driver = create_chromedriver(True)
print(driver.capabilities['version'])
driver.get("https://www.yahoo.com/news/")
I import it into the tasks.py file and turn into into a task function with:
from . import my_huey
some_long_calculation_task = my_huey.task(some_long_calculation)
I then import some_long_calculation_task into main/views.py and try to run it with:
#main.route('/sanity_check')
def sanity_check():
png = some_long_calculation_task()
return send_file(io.BytesIO(png),mimetype='image/png')
but I get:
traceback (most recent call last):
File "...lib\site-packages\flask\app.py", line 1994, in __call__
return self.wsgi_app(environ, start_response)
File "...lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "...lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "...lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "...lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "...lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "...lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "...lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "...lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "...lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "...app\main\views.py", line 123, in sanity_check
png = some_long_calculation_task()
TypeError: decorator() missing 1 required positional argument: 'func'
>>> some_long_calculation_task
<function Huey.task.<locals>.decorator at 0x0000028CF8CF2BF8>
How can I fix this?
Based on the error message, task returns a decorator (usually used with # as a syntax sugar).
Try this code instead:
from . import my_huey
some_long_calculation_task = my_huey.task()(some_long_calculation)
The "normal" usage from this would be something like
#my_huey.task()
def my_function(...):
...

Malformed IP address error

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

Issues with getting JSON data from AJAX POST

The AJAX call looks like this:
json_dictionary = {url : url, profile_dict: dictionary, final_dict : final_dictionary}
$.ajax({
url: "https://localhost:8090/add_profile_data",
type: "POST",
data: JSON.stringify(json_dictionary),
contentType:'application/json',
success:function() {
console.log('added profile data')
}
})
The client side looks like this:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(type(data))
That works, and the result from print is <type 'dict'>
Also, when I print the data object, everything is there.
However, when I try:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(data.keys())
I get an error: AttributeError: 'NoneType' object has no attribute 'keys'
I don't understand why this is happening? Any thoughts?
Update:
Changed the server to this, and now seeing NoneType for print(type(data))
Server:
#app.route('/add_profile_data', methods=['POST', 'GET', 'OPTIONS'])
def add():
data = request.json
print(type(data))
print(data.keys())
Response:
<type 'NoneType'>
127.0.0.1 - - [04/Jan/2017 09:13:47] "OPTIONS /add_profile_data HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/morganallen/Dropbox/Coding_Projects/Prediction_Server/prediction_v2.py", line 172, in add
print(data.keys())
AttributeError: 'NoneType' object has no attribute 'keys'
Any reason why I am seeing NoneType?
127.0.0.1 - - [04/Jan/2017 09:13:47] "OPTIONS /add_profile_data HTTP/1.1" 500
An OPTIONS request will not include JSON.
Edit your code to only check the JSON if the method is POST.
For example:
#app.route('/add_profile_data', methods=['POST', 'GET'])
def add():
if request.method == 'POST':
data = request.json
print(type(data))
print(data.keys())

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