import simplejson
from urllib2 import urlopen
from simplejson import loads
from django.core import serializers
content = loads(urlopen('https://graph.facebook.com/1234676502/feed').read())
content = simplejson.dumps(content,sort_keys=True, indent=4)
print content
json_serializer = serializers.get_serializer("json")()
json_serializer.deserialize(content)
While running the above python code im getting the following error:
Traceback (most recent call last):
File "/var/www/youedo/test.py", line 22, in <module>
json_serializer = serializers.get_serializer("json")()
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 63, in get_serializer
_load_serializers()
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 109, in _load_serializers
register_serializer(format, BUILTIN_SERIALIZERS[format], serializers)
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/__init__.py", line 51, in register_serializer
module = importlib.import_module(serializer_module)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/xml_serializer.py", line 6, in <module>
from django.core.serializers import base
File "/usr/local/lib/python2.6/dist-packages/django/core/serializers/base.py", line 7, in <module>
from django.db import models
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
...and when I print the content it prints the JSON string correctly.
Edit:2
import simplejson
from urllib2 import urlopen
from simplejson import loads
from django.core import serializers
content = loads(urlopen('https://graph.facebook.com/1234676502/feed').read())
json_serializer = serializers.get_serializer("json")()
json_serializer.get_deserialize(content)
I put this code in my view.py then i got the following error:
AttributeError at /rss
'Serializer' object has no attribute 'get_deserialize'
Request Method: GET
Request URL: http://127.0.0.1:8000/rss
Django Version: 1.2.4
Exception Type: AttributeError
Exception Value:
'Serializer' object has no attribute 'get_deserialize'
Your error has nothing to with json per se, it clearly states that it cannot import DJANGO_SETTINGS which means that you do not have the django app context in place. The easiest way to go about this is install django extensions which provides the command ./manage.py runscript which runs your script with your django app context.
Django extensions can be found here
Edit:: looking at your second edit, I can see that you are using a method get_deserialize(), the right method should be deserialize(), AFAIK.
Related
I'm a Mac user and I'm trying to use the requests module get() here:
import requests
url = 'http://www.omdbapi.com/?t=star+wars&r=json'
response = requests.get(url)
dic = response.json()
for key in dic:
print key, ':', dic[key]
But I get this:
import requests
File "/Library/Python/2.7/site-packages/requests/__init__.py", line 63, in <module>
from . import utils
File "/Library/Python/2.7/site-packages/requests/utils.py", line 24, in <module>
from ._internal_utils import to_native_string
File "/Library/Python/2.7/site-packages/requests/_internal_utils.py", line 11, in <module>
from .compat import is_py2, builtin_str, str
File "/Library/Python/2.7/site-packages/requests/compat.py", line 33, in <module>
import json
File "/Users/miguel/Desktop/json.py", line 4, in <module>
response = requests.get(url)
AttributeError: 'module' object has no attribute 'get'
I've reinstalled the requests library using pip module but it doesn't fix.
Any idea? Thanks.
You've named your own script json.py which we can see in the last line of the traceback:
File "/Users/miguel/Desktop/json.py", line 4, in <module>
Don't do that, you're now masking the actual json module and that's going to do some damage to requests's ability to function. Equally, don't call a script requests.py. Just rename the file and it should fix the issue.
I have a xml parser that will store that data into a MySQL database, as part of a django app. The parser is intended to run daily, capturing some tests outputs:
`dbsync.py`:
1 #!/usr/bin/env python
2 import os
3 os.environ['DJANGO_SETTINGS_MODULE'] = 'autotester.settings'
4
5 import xml_parser
6 from models import *
The Django project is called autotester and the app is called autoreporter.
When I execute
python dbsync.py
I'm getting:
Traceback (most recent call last):
File "autoreporter/dbsync.py", line 6, in <module>
from models import *
File "/root/autotester/autoreporter/models.py", line 1, in <module>
from django.db import models
File "/usr/lib/python2.7/dist-packages/django/db/models/__init__.py", line 5, in <module>
from django.db.models.query import Q
File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 17, in <module>
from django.db.models.deletion import Collector
File "/usr/lib/python2.7/dist-packages/django/db/models/deletion.py", line 4, in <module>
from django.db.models import signals, sql
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/__init__.py", line 4, in <module>
from django.db.models.sql.subqueries import *
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/subqueries.py", line 12, in <module>
from django.db.models.sql.query import Query
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 22, in <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "/usr/lib/python2.7/dist-packages/django/db/models/sql/aggregates.py", line 9, in <module>
ordinal_aggregate_field = IntegerField()
File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 54, in __getattr__
self._setup(name)
File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 49, in _setup
self._wrapped = Settings(settings_module)
File "/usr/lib/python2.7/dist-packages/django/conf/__init__.py", line 132, in __init__
% (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'autotester.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named autotester.settings
How can I have DJANGO_SETTINGS_MODULE set, so I can execute the dbsync.py script properly?
Two issues
You need to import models from your app, so provided that your Django project is in the PYTHONPATH you can simply import the app models by:
from autoreporter.models import *
or do a relative import, if dbsync.py(looks from your traceback) is in the app directory.
from .models import *
Add Django project to PYTHONPATH. You need to have the Django project in the PYTHONPATH to it be accessed from your dbsync.py(provided it is in your django app directory), quick easy fix for this would be to do the following in your code to dbsync.py.
import sys
import os
##get project directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
##get project parent directory and add to python path using sys.path.append
SYS_PATH = os.path.dirname(BASE_DIR)
if SYS_PATH not in sys.path:
sys.path.append(SYS_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = 'autotester.settings'
I run a few scripts using the ORM without the rest of Django. I wouldn't set the environment in the script.
Since Django 1.7 you need to import your models, and run django setup.
I would set the environment as you do for the main Django application. Then at the start of your script add these lines. Those should set up the Django environment so it can access your models the same way a standard Django app will.
import django
django.setup()
import xml_parser
from .models import *
I want to run my first Django cassandra code in pyCharm.
My code is running smoothly in Django console but it's not working in a .py file. these are the errors:
C:\Python27\python.exe "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py"
Traceback (most recent call last):
File "D:/Developer Center/PyCharm/DJangoCassandra/MyApp/testFile.py", line 3, in <module>
from MyApp.models import Person
File "D:\Developer Center\PyCharm\DJangoCassandra\MyApp\models.py", line 1, in <module>
from django.db import models
File "C:\Python27\lib\site-packages\django\db\__init__.py", line 11, in <module>
if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Process finished with exit code 1
this is my .py file:
__author__ = 'ehsan'
from cqlengine import connection
from MyApp.models import Person
from cqlengine.management import sync_table,drop_table
def main():
connection.setup(['127.0.0.1:9160'])
sync_table(Person)
Person.create(id='2',name='Ali',family='Rezayee')
p = Person.objects.all()
for item in p:
print item.id
Person.filter(id='1')
this is my model:
from django.db import models
from cqlengine import Model, columns
# Create your models here.
class Person(Model):
id = columns.Text(primary_key=True)
name = columns.Text()
family = columns.Text()
If you'll write the following lines when starting the managy.py shell command, it should work:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zoo.settings")
I'm tring to launch simple code from the docs:
https://flask-superadmin.readthedocs.org/en/latest/quickstart.html
Here is the code:
from flask import Flask
from flask.ext.superadmin import Admin
app = Flask(__name__)
admin = Admin(app)
app.run()
but the following error occures:
Traceback (most recent call last):
File "test.py", line 2, in <module>
from flask.ext.superadmin import Admin
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask/exthook.py", line 62, in load_module
__import__(realname)
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/__init__.py", line 2, in <module>
from model import ModelAdmin
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/model/__init__.py", line 1, in <module>
from .base import ModelAdmin, AdminModelConverter
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/model/base.py", line 10, in <module>
from flask_superadmin.form import BaseForm, ChosenSelectWidget, DatePickerWidget, \
File "/home/un1t/workspace/dj/python/local/lib/python2.7/site-packages/flask_superadmin/form.py", line 115, in <module>
class FileField(wtf.FileField):
AttributeError: 'module' object has no attribute 'FileField'
I use the following versions of libraries:
Flask==0.10.1
Flask-Script==0.6.2
Flask-SuperAdmin==1.7
Flask-WTF==0.9.1
flask-mongoengine==0.7.0
WTForms==1.0.4
What is wrong, or where could I find working examples?
This is a bug in the import. I fixed it in my fork; clone from there and then try it again.
I am trying to call urllib2 simple code.
import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)
m getting this error
File "urllib.py", line 13, in <module>
import urllib2
File "/usr/lib/python2.7/urllib2.py", line 111, in <module>
from urllib import (unwrap, unquote, splittype, splithost, quote,
File "/home/vclub/vclubdev/vclubcms/urllib.py", line 14, in <module>
f = urllib2.urlopen('http://www.python.org/')
AttributeError: 'module' object has no attribute 'urlopen'
Please suggest what i need to do for solving this error .
You have a file called urllib.py in your working directory. It's confusing Python's import mechanism.
You should rename it.