Having the following error AttributeError: 'NoneType' object has no attribute 'sa_engine'
on this line in model/init.py
Session = scoped_session(sessionmaker(autoflush=True, autocommit=False,
bind=config['pylons.g'].sa_engine))
When printing config dictionary, it has 'pylons.g' key but value at this key is None.
I do not understand why it is None, config['pylons.g'] is initialized in environment.py as
config['pylons.g'] = app_globals.Globals()
Any ideas?
By the way, initially there no config['pylons.g'] code in the project. It was config['pylons.app_globals'] but when I tried to use it, it was not in dictionary at all.
I would recommend against binding the session at import time. Do it inside init_model() instead:
def init_model(engine):
meta.Session.configure(bind=engine)
Related
I get the response of a server:
r = requests.get(my_url)
print(r.text)
json_response = json.loads(r.text)
print(type(json_response))
I am using json.loads() to convert the string into json. However, the response has this format:
[{"element_info":{"data":201863539001,......]
I want to access element_info.data. I tried accessing it with json_response.element_info.data but i got AttributeError: 'list' object has no attribute 'bkdn_elem_info'.
I also tried content = r.read() and i got AttributeError: 'Response' object has no attribute 'read'.
You cannot access the elements of a dictionary in python with '.' operator as in javascript. You have to use the square bracket notation as below to access the elements
json_response[0]["element_info"]["data"]
The type of json_response is list. So, you can iterate on it and access each element in it. Each element is a dictionary. So, you can use the keys:
for each_element in json_response:
print(each_element["element_info"]["data"])
If you are not sure that these keys are available in all elements, you can use the get() method with a default value to avoid errors when the key does not exist. Here, the first operand is the key that you want to read, and the second operand can be used to define a default value:
for each_element in json_response:
print(each_element.get("element_info", {}).get("data", ""))
In access to data from a list, you must specify the element with index first and then get the property of the object
objectOfList =json_response[0];
value = objectOfList["element_info"]["data"];
I am getting an error when trying to parse and stringify some JSON data.
On this line:
this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns)));
Here is the entire #Input (using Angular 4):
#Input()
set gridColumns(gridColumnsArr: Array<object>) {
console.log('gridColumnsArr');
console.log(gridColumnsArr);
this.columns = this.sortActiveAndInactiveColumns(gridColumnsArr);
console.log('this.columns');
console.log(this.columns);
this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns)));
console.log('this.copyOfColumns');
console.log(this.copyOfColumns);
}
Here is the data logged to the console (this.columns)...and the error(s) following:
I assume you want to deep copy the array by using JSON.parse(JSON.stringify()). Apparently your data structure has circular references which fails the JSON.stringify().
Either you should sanitize your data to not contain ciruclar references or you could try using a library like flatted
Folks,
I just spent a good amount of time trying to look this up -- I ought to be missing something basic.
I have a python object, all I want to do is to insert this object in mondodb.
This is what I have:
from pymongo import Connection
import json
conn = Connection()
db = conn.cl_database
postings = db.postings_collection
class Posting(object):
def __init__(self, link, found=None, expired=None):
self.link = link
self.found = found
self.expired = expired
posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
postings.insert(value)
throws this error:
Traceback (most recent call last):
File "./mongotry.py", line 21, in <module>
postings.insert(value)
File "build/bdist.macosx-10.7-intel/egg/pymongo/collection.py", line 302, in insert
File "build/bdist.macosx-10.7-intel/egg/pymongo/database.py", line 252, in _fix_incoming
File "build/bdist.macosx-10.7-intel/egg/pymongo/son_manipulator.py", line 73, in transform_incoming
TypeError: 'str' object does not support item assignment
Seems like it is because json.dumps() returns a string.
Now if I do do a loads of the value before inserting it works fine:
posting = Posting('objectlink1')
value = json.dumps(posting, default=lambda x:x.__dict__)
value = json.loads(value)
postings.insert(value)
What is the most straight-forward to do this?
Thanks!
What is value in your initial code?
It should be dict not class instance
This should work:
postings.insert(posting.__dict__)
You are misusing the insert method for the collection. Review here: http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert
What you need to be inserting is a document. It should be a dict with keys and values. Simply trying to insert a string is not appropriate. json.dumps returns a string in json format. If you are just dumping it to get a dict then the json step is not necessary.
Insert exactly how your documents should look:
postings.insert({"key":"value"})
Or convert your class instance directly into the dict you want to store as a doc and then insert it. It works with your json.dumps.loads() because that ultimately does give you a dict.
I have a WS using Flask/python 2.7. I have 1 JSON object passed to the WS. I have been successful in capturing the object and returning the whole JSON.
I have looked all over for examples (many use print of test dataset in python) and have tried json.dumps, json.loads, json.dump, json.load, for loops, etc.
What I would like to do seems simple and I know it is me, but I get errors no matter what I try. I am trying to parse the JSON, put the values in to variables, and do "stuff".
This works:
#app.route('/v1/test', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json, separators=(',',':'))
else:
return "415 Unsupported Media Type"
This does not (and many variations of this using different things):
jsonobject = json.dumps(request.json)
pstring = json.loads(jsonobject)
for key, value in pstring.iteritems():
return value
What I want to do (pseudo code):
for each JSON
get the name value pairs in to a place where I can do something like this (which was done on a flat file)
input_data = pd.read_csv(sio, delimiter=',', names=columns)
probs = model.predict_proba(input_data)
I am sure I didn't make this as clear as I could but it is a challenge because I get errors like below (examples -- not all at once of course) with all the different things I try:
AttributeError: 'dict' object has no attribute 'translate'
TypeError: 'dict' object is not callable
AttributeError: 'str' object has no attribute 'iteritems'
So after all that, what is the right way to do this?
Im not able to serialize a ValuesQuerySet object to json data, i´ve found multiple solutions to this gap, but this case is different because i need to follow the Foreign Keys values.
from task_manager.models import UserTasks
data=UserTasks.objects.filter(user__username="root",server_id=2).values("server_id__mnemonic")
The previous query returns something like this:
>>> print data
[{'server_id__mnemonic': u'lol'}, {'server_id__mnemonic': u'lol'}, {'server_id__mnemonic': u'lol'},.......]
But when I try to serialize it to JSON format raises the next exception:
>>> json_data = serializers.serialize('json',data)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django\core\serializers\__init__.py", line 122, in serialize
s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 45, in serialize
concrete_model = obj._meta.concrete_model
AttributeError: 'dict' object has no attribute '_meta'
>>> type(data)
<class 'django.db.models.query.ValuesQuerySet'>
I´ve found in the official Django manual a solution that says: If you only want a subset of fields to be serialized, you can specify a fields argument to the serializer:
from django.core import serializers
data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
But with this code, i cannot get the foreign keys values i want.
Thanks
values() gives you a ValuesQuerySet which you can serialize by converting it to a list and using json module, no need to involve Django serializers here:
import json
from task_manager.models import UserTasks
data = UserTasks.objects.filter(user__username="root",server_id=2).values("server_id__mnemonic")
print json.dumps(list(data))
Another option would to be use serializers.serialize() with specifying fields argument:
data = UserTasks.objects.filter(user__username="root",server_id=2)
print serializers.serialize('json', data, fields=('server_id__mnemonic', ))