Rectangle 27 5

While it's ok to return a string from a Flask handler with json.dumps, the preferred way is to use jsonify, which adds the correct Content-Type and accepts a variety of arguments, e.g. you can just call:

return jsonify(user=100)

Hi when I try to run the correct code it's not returning any output, return jsonify(user=user_id)1 it doesn't return anything. However return jsonify(user='text') returns the value

@rksh I presume that the trailing 1 in your commend is a typo?

flask - Python 'dict' object not callable? - Stack Overflow

python flask
Rectangle 27 3

Simply use jsonify() from flask package. This method takes any serializable data type (for example I have used data in the following example).

from flask import jsonify

@app.route('/login', methods=['POST'])
def login():
    data = {'name': 'nabin khadka'}
    return jsonify(data)

To return a status code, simply return it at the end of the return as below:

return jsonify(data), 200

json - Sending data through a Response object in Python Flask - Stack ...

json flask response
Rectangle 27 2

I am using Flask on python 2.7 and I want to return a value as a json value

You are not returning a JSON string

You are returning a python object. When Flask sees a python object, it tries to call it. When you return a dictionary, it assumes it is a callable and tries to call it.

import json

def your_function(..):
    ...
    return json.dumps(return_id)

PS: As correctly pointed out by @bereal in his answer, the above approach wont add Content-Type: application/json header in the response. You'd want to use jsonify(..) as shown in his answer.

flask - Python 'dict' object not callable? - Stack Overflow

python flask
Rectangle 27 3

Use the following syntax instead to parse the data:

data = request.get_json(force=True)

This will keep the original structure of the JSON object.

request.form.to_dict()

python - Can't turn my data object into nested dicts when working in f...

python json flask
Rectangle 27 1

from flask import jsonify
def myMethod():
    ....
    response = jsonify(data)
    response.status_code = 200 # or 400 or whatever
    return response

python - Flask API TypeError: Object of type 'Response' is not JSON se...

python rest flask flask-restful
Rectangle 27 1

The API description for flask.json.jsonify indicates it's expecting keyword parameters. What you actually want to do seems to be serialize a list object containing dictionaries, have you tried flask.json.dumps instead? Assuming you've got the dumps symbol imported, instead of your jsonify call you can try:

return dumps(results)

Hello, when I try dumps. I am not getting anything to the DOM, but I can see under "network", that it is getting the JSON object.

In the .getJSON callback, I think you're still looking for the result attribute in the inbound JSON (back from when you were using jsonify). Maybe try $("#result").text(data); instead?

Thanks @rchang, but it seems that I am getting the same error as with jsonify. Still getting [object Object]

As an alternative, maybe try Python's built-in json module. It too provides a dumps method that accepts an object. I know I've successfully used this before to serialize a list of dictionaries (although that was not on a Flask project). Docs at docs.python.org/2/library/json.html for Python 2.7 and docs.python.org/3.3/library/json.html for Python 3.3

python - Return JSON object to View with Flask and Ajax - Stack Overfl...

python ajax json flask
Rectangle 27 1

{result: [{course_id: 'xxx', course_name: 'xxx'}]}
data.result
$("#result").text()
[object Object]

You should iterate over the array to construct a string, then set the string in DOM, like:

courseStr = data.result.map(function(course) {return course.course_id + '-' +   course.course_name; }).join(',');
$("#result").text(courseStr);

That was exactly what I needed thank you!

python - Return JSON object to View with Flask and Ajax - Stack Overfl...

python ajax json flask
Rectangle 27 0

This is due to Python's scoping rules (as @johnthexiii pointed out) - testfun->aaa is bound to the global scope because there is no variable named aaa declared anywhere inside of testfun and there is no enclosing scope (i. e. testfun is not declared inside another function or class).

You'll want to pass aaa as an argument to testfun:

testfun(aaa)

If testfun requires too many params there are several ways you can DRY up the code:

  • Use multiple functions: If testfun is doing a lot of work then break it up into multiple functions that return intermediate transformations of the data: def start_test(arg1, arg2, arg3): # do stuff with args return result_stage_1 def continue_test(arg3, arg4, arg5): # do stuff with args return result_stage_2 def finalize_test(arg7, arg8): # do stuff with args return real_result
  • Use keyword arguments: If a variable number of arguments are needed and testfun cannot be broken up you can use keyword arguments to simplify the calling of the function: def testfun(arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, arg6=None, arg7=None, arg8=None): # do stuff with args # call it as so args = {"arg1": "some args", "arg5": "have defaults"} if complex_condition: args["arg3"] = 17 elif another_condition: args["arg7"] = 10 testfun(**args)

Encapsulate state and behavior with classes (or closures): If neither of the above will work for you then you probably need to leave the realm of stateless functions and create classes or closure-creating functions to preserve your state and enable you to modify behavior as needed.

python - objects not being passed to function in flask route - Stack O...

python function flask decorator routes
Rectangle 27 0

As mentioned in the comments for the previous answer, that code isn't supported on Flask 0.8, and would require 0.9 or higher. If you need to support Flask 0.8, here is a compatible version that assigns the "status_code" instead:

@app.errorhandler(404)
def not_found(error):
    resp = jsonify({'error':'not found'})
    resp.status_code = 404
    return resp

This is wonderful! Thanks for taking the time to provide a compatible snippet for those of us lagging behind with an older version!!

python - Flask error handling: "Response object is not iterable" - Sta...

python rest curl flask
Rectangle 27 0

The problem is that your endpoint is returning a list. Flask only likes certain return types. The two that are probably the most common are

Response
  • a str (along with unicode in Python 2.x)

You can also return any callable, such as a function.

If you want to return a list of devices you have a couple of options. You can return the list as a string

@server.route('/devices')
def status():
    return ','.join(app.statusOfDevices())

or you if you want to be able to treat each device as a separate value, you can return a JSON response

from flask.json import jsonify

@server.route('/devices')
def status():
    return jsonify({'devices': app.statusOfDevices()})

python - "TypeError": 'list' object is not callable flask - Stack Over...

python flask
Rectangle 27 0

You can use Flask-Cache (flask.ext.cache)'s SimpleCache (which is really werkzeug.contrib.cache.SimpleCache) to store the data in-memory in your application. The only issue is that you will have one instance of the cache per server process (if you are behind uwsgi, or running on mod_wsgi you will most likely have more than one process handling requests). So it is possible for a user to hit one endpoint of your application, pay the price to fetch the data, and then on the next request, hit a different process and have to pay that cost again (because while Process A has the data cached, Process B does not).

The only way to get around that is to use an out-of-process store (either a cache on the parent process or a separate Python process that acts as a cache server or some persistence store [Redis, PostGres, etc.])

python - How to pass complex objects across view functions/sessions in...

python flask
Rectangle 27 0

What about just writing a wrapper function? I would probably do something like:

@app.route('/api/blah/')
 def my_route():
     results = calculate_my_results()
     return jsonify(format_api_result(results))

 def format_api_result(data):
     # add in your extra metadata here, return a dictionary

A function seems to me to be the most straightforward and most flexible way to do what you want. It's a little extra code, but so's a decorator. And while you can certainly do this in a decorator, I don't think it adds much here except complexity.

If you do want to go the decorator route, check out this:

for a good explanation of how decorators work and how you control exactly when the wrapped function gets called.

python - How can I return a common JSON object in my flask API? - Stac...

python json flask decorator
Rectangle 27 0

The easiest way I've found of doing this is to fill the form fields on a get request.

@decorator_authorized_user  # This decorator should make sure the user is authorized, like @login_required from flask-login
def editprofile(nickname = None):
    # Prepare the form and user
    form = EditProfile()
    form_action = url_for('profile.editprofile')
    my_user = Users.get(...)  # get your user object or whatever you need
    if request.method == 'GET':
        form.username.data = my_user.username
        form.email.data = my_user.email
        # and on
    if form.validate_on_submit():
        # This section needs to be reworked.
        # You'll want to take the user object and set the appropriate attributes
        # to the appropriate values from the form.
        if form.username.data == nickname: 
            query = EditProfile(form.username.data,
                                form.email.data,
                                form.about.data,
                                form.website.data,
                                )
            print query #debug
            db.session.add(query)
            db.session.commit()
            flash('User Updated')
            print "added"
            return(url_for('profile.editprofile'))
    return render_template('profile/add.html', form=form,
                           form_action=form_action, title="Update Profile")

This sets up the function to return a prefilled form on a get request. You'll have to rework the section under form.validate_on_submit. Dirn's answer suggests a few of the right things to do.

python - Pre-Populate a WTforms in flask, with data from a SQLAlchemy ...

python flask flask-sqlalchemy flask-wtforms
Rectangle 27 0

manage.py
sched/
  __init__.py

in __init__.py you can do the following:

from flask import Flask
def create_app():
  app = Flask(__name__)
  app.config['DEBUG'] = True
  return app
manage.py
from app import create_app
from flask.ext.script import Manager
app = create_app()
manager = Manager(app)
if __name__ == '__main__':
  manager.run()

This tends to be an extensible solution for larger application structures.

python - Object is not imported properly in a Flask structure - Stack ...

python flask
Rectangle 27 0

That means that self.view_functions[rule.endpoint] is a string, not a function, thus cannot be called (with (...) operator). That said, it is difficult to tell what the issue without your code: Flask expects a function to be called and it gets a string. Did you use the @app.route decorator?

self.view_functions[rule.endpoint]

The routes are built outside of a route decorator from a different config within the blueprint that gets built and registered with the the application factory I built...when making a second application I did the route method notation as strings without thinking.

python - Flask : TypeError: 'str' object is not callable - Stack Overf...

python flask
Rectangle 27 0

If you want to use classes you can also consider pluggable views

Object Oriented Python with Flask Server? - Stack Overflow

python flask
Rectangle 27 0

One way is to create an overall package and adding a __init__.py file under that where you declare all global variables. In your case for example, you can create something like:

myapplication/
    *        __init__.py
    *        myviews/
        *         __init__.py
        *         view.py
        *         tags.py

Now you add the following code in the __init__.py file:

app = Flask(__name__)

You can now use this app variable anywhere as long as you import the package myapplication.

import myapplication.myviews.view

I have opened the views.py file from above in ipython. When I type import myapplication at the prompt, I get this error - ImportError: No module named myapplication. What am I doing wrong ?

This seems an elegant way to do it, thank you! @murtaza52: you probably haven't added the package to the search path yet. Read this section in the docs for a good explanation.

python - How to share the global app object in flask? - Stack Overflow

python flask
Rectangle 27 0

menumaster_project/
 menumaster/
    __init__.py
    sqltables.py
    my_subpackage/
       __init__.py
       my_submodule.py
 other_project_file.txt
menumaster_project
menumaster_project/menumaster/__init__.py

@Giri Yes, but you now have a different problem. This question has been answered. Ask a different question with enough detail to reproduce that problem (for example you don't show any routes registered on the app, so there's no non-404 urls right now).

sqltables.py
menumaster_app.py
from menumaster import app as application

@Giri they should contain whatever you need access to, I have no idea what those modules are.

python - Reuse app object in Flask - Stack Overflow

python flask
Rectangle 27 0

You have to create a custom JSONEncoder class and tell Flask to use this for JSON serialization/deserialization.

Here is how it would roughly work:

from flask.json import JSONEncoder

class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Passport):
            # Implement code to convert Passport object to a dict
            return passport_dict
        else:
            JSONEncoder.default(self, obj)

# Now tell Flask to use the custom class
app.json_encoder = CustomJSONEncoder

Thanks, this does one half of it. However, for complete solution, I need to hook also decoding. I've found some example how to do it, but it's not Flask-related. I've already found that doing app.json_decoder = CustomJSONDecoder doesn't do the trick.

I haven't done that myself, but according to the Flask API docs setting app.json_decoder to a sublass of flask.json.JSONDecoder should do the trick. What's the precise problem that you have with that?

I get "itsdangerous.BadPayload" error (BadPayload: Could not load the payload because an exception occurred on unserializing the data). It doesn't help too much in understanding what's wrong.

Put an import pdb; pdb.set_trace() inside your deserialization code to find out what is going wrong, looks like you have an error in your deserializer. Maybe also enable debug logging.

That didn't cause any change in the debug output. The error is not triggered in my code, it's somewhere deeper, in itsdangerous.py. I am starting to feel that hooking up custom JSONEncoder and JSONDecoder is not the right way to live. I think I'll put the code that wraps the passport data encoding/decoding in session variable in a separate class that lives in the application scope and connects to the session when necessary.

python - Fixing the class to enable object storing in Flask session - ...

python flask