from django.db import models
from djangosphinx.models import SphinxSearch
class MyModel(models.Model):
search = SphinxSearch() # optional: defaults to db_table
# If your index name does not match MyModel._meta.db_table
# Note: You can only generate automatic configurations from the ./manage.py script
# if your index name matches.
search = SphinxSearch('index_name')
# Or maybe we want to be more.. specific
searchdelta = SphinxSearch(
index='index_name delta_name',
weights={
'name': 100,
'description': 10,
'tags': 80,
},
mode='SPH_MATCH_ALL',
rankmode='SPH_RANK_NONE',
)
queryset = MyModel.search.query('query')
results1 = queryset.order_by('#weight', '#id', 'my_attribute')
results2 = queryset.filter(my_attribute=5)
results3 = queryset.filter(my_other_attribute=[5, 3,4])
results4 = queryset.exclude(my_attribute=5)[0:10]
results5 = queryset.count()
# as of 2.0 you can now access an attribute to get the weight and similar arguments
for result in results1:
print result, result._sphinx
# you can also access a similar set of meta data on the queryset itself (once it's been sliced or executed in any way)
print results1._sphinx
and
Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\models.py", line 1, in <module>
from django.db import models
File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module>
if not settings.DATABASE_ENGINE:
File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25\Lib\site-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.
I know what the problem is :)
You are trying to run this script as stand-alone. But since you use django models. all of them have to be imported in your namespace. This is what is the error. It clearly days ImportError.
To solve - go to your django-project directory & then type python manage.py shell. This imports all Django-env files. Now import your models & try out the search.
The error is about the environment. Django cannot find your settings file; Are you doing
python manage.py runserver
itself, or something else?
Related
I have recently changed my main flask app file from inputServer.py to app.py to increase ease of use.
My code that throws the error is as follows:
def readBackupPlayers(objectFile):
with open(objectFile, 'rb') as openedFile:
manager.playerList = pickle.load(openedFile)
print('Backup of players retrieved')
^
Function that read a custom pickle file used for backing up a list stored inside a custom object
class PlayerManager:
def __init__(self):
self.playerList = []
self.ID = len(self.playerList) + 1
self.currentGame = None
self.tournament = None
manager = PlayerManager()
^
Code that declares the class and creates an instance of it to use to store variables across the program.
Error message:
File "c:\users\simon\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\simon\OneDrive\Documents\AtomTesting\app.py", line 356, in setup
readBackupPlayers('Backups/playerBackup')
File "C:\Users\simon\OneDrive\Documents\AtomTesting\app.py", line 72, in readBackupPlayers
manager.playerList = pickle.load(openedFile)
ModuleNotFoundError: No module named 'inputServer'
Directory:
AtomTesting -
Backups -
playerBackup
tournamentBackup
Static -
static Flask files (not relevant)
templates -
Flask templates (not relevant)
app.py (renamed from inputServer.py)
config.py
README.md
Here's what's happening. Python's pickle module serializes and deserializes (dumps and loads) Python objects based on their name. Since the name of the module where your class lives changed, Pickle can't figure out how to re-instanciate those objects.
There is, however, a solution which is detailed on the Python wiki. It involves mapping old names to new names:
import pickle
renametable = {
'inputServer': 'app',
}
def mapname(name):
if name in renametable:
return renametable[name]
return name
def mapped_load_global(self):
module = mapname(self.readline()[:-1])
name = mapname(self.readline()[:-1])
klass = self.find_class(module, name)
self.append(klass)
def loads(str):
file = StringIO(str)
unpickler = pickle.Unpickler(file)
unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
return unpickler.load()
Alternatively, and this is probably a better approach, you shouldn't use pickle for any serious data store, especially when something might be used between versions of your app.
You might consider using an ORM with a lightweight database, like SQLite.
i have a python program that reads in NMEA sentences and writes them to my django database.
update = breadCrumbs2(deviceID= device[0], time = tdStamp , latitude = msg.latitude,
longitude = msg.longitude , fixQualty = int(msg.gps_qual),
numSat = int(msg.num_sats),hdop = msg.horizontal_dil,
altitude = msg.altitude, geoIdalSeparation = msg.geo_sep,
deltaLastUpdate = Decimal(0), diffRefStationID = int(1),
nmeaCheckSum = "")
update.save()
this works fine when run from eclipse. but when i try to run it from my linux box i get an error:
"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."
but when i go into the django shell to configure settings i get.
>>> from django.conf import settings
>>> settings.configure()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 93, in configure
raise RuntimeError('Settings already configured.')
RuntimeError: Settings already configured.
how to i correct this conflict. (i have restarted Django and Apache)
I am reading 'Head First Python'. I am on Chapter 10 where Google App Engine is introduced. The initial hello world of using Python and Google App Engine was successful but subsequent programs have all failed.
I have the following app.yaml file:
application: three
version: 1
runtime: python27
api_version: 1
threadsafe: false
handlers:
- url: /.*
script: page368b.py
libraries:
- name: django
version: "1.3"
With the following Python code (page368b.py):
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
#this line throws the error when accessing the web-page
from google.appengine.ext.db import djangoforms
import birthDB
class BirthDetailsForm(djangoforms.ModelForm):
class Meta:
model = birthDB.BirthDetails
class SimpleInput(webapp.RequestHandler):
def get(self):
html = template.render('templates/header.html', {'title': 'Provide your birth details'})
html = html + template.render('templates/form_start.html', {})
html = html + str(BirthDetailsForm(auto_id=False))
html = html + template.render('templates/form_end.html', {'sub_title': 'Submit Details'})
html = html + template.render('templates/footer.html', {'links': ''})
self.response.out.write(html)
def main():
app = webapp.WSGIApplication([('/.*', SimpleInput)], debug=True)
wsgiref.handlers.CGIHandler().run(app)
if __name__ == '__main__':
main()
Here is another Python module imported into the one above called birthDB.py:
from google.appengine.ext import db
class BirthDetails(db.Model):
name = db.StringProperty()
date_of_birth = db.DateProperty()
time_of_birth = db.TimeProperty()
There is a templates folder that the above Python module calls. They have HTML code in them with some Django code. Here is an example using the footer.html.
<p>
{{ links }}
</p>
</body>
</html>
The other HTML files are similar. I can start the Google App Engine with no problems using this command from BASH: python google_appengine/dev_appserver.py ~/Desktop/three The directory three contains the templates folder, the app.yaml file, the Python modules shown above.
My problem is when I access the web-page at http://localhost:8080 nothing is there and the BASH shell where the command is run to start this shows all the calls in the Python program that caused the problem and then finally says: ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
I have read in a few different places a few different things to try so I thought I would go ahead and make a new post and hope that some expert Python programmers would chime in and lend their assistance to a lost hobbit such as myself.
Also, the book says to install Python2.5 to use this code but Google App Engine now supports Python2.7 that was not available as of the time of the books writing. Also, I just checked and Python2.5 is not even an option to use with Google App Engine. Python2.5 deprecated
This is probably too complex to solve on here. I am surprised all of these different technologies are used in a Head First Python book. It is asking a lot of a Python noob. ^_^
Regards,
user_loser
UPDATE - I installed Django on my Ubuntu Operating System
When I change the line in the python module 368b.py from google.appengine.ext.db import djangoforms to from django import forms I receive the following error on the console when accessing the web-page on localhost:
loser#loser-basic-box:~/Desktop$ google_appengine/dev_appserver.py three
INFO 2014-09-06 21:08:36,669 api_server.py:171] Starting API server at: http://localhost:56044
INFO 2014-09-06 21:08:36,677 dispatcher.py:183] Starting module "default" running at: http://localhost:8080
INFO 2014-09-06 21:08:36,678 admin_server.py:117] Starting admin server at: http://localhost:8000
ERROR 2014-09-06 21:08:48,942 cgi.py:121] Traceback (most recent call last):
File "/home/loser/Desktop/three/page368b.py", line 13, in <module>
class BirthDetailsForm(forms.ModelForm):
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/models.py", line 205, in __new__
opts.exclude, opts.widgets, formfield_callback)
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/models.py", line 145, in fields_for_model
opts = model._meta
AttributeError: type object 'BirthDetails' has no attribute '_meta'
INFO 2014-09-06 21:08:48,953 module.py:652] default: "GET / HTTP/1.1" 500 -
ERROR 2014-09-06 21:08:49,031 cgi.py:121] Traceback (most recent call last):
File "/home/loser/Desktop/three/page368b.py", line 13, in <module>
class BirthDetailsForm(forms.ModelForm):
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/models.py", line 205, in __new__
opts.exclude, opts.widgets, formfield_callback)
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/models.py", line 145, in fields_for_model
opts = model._meta
AttributeError: type object 'BirthDetails' has no attribute '_meta'
Update Errors from running the program as is without making any changes:
loser#loser-basic-box:~/Desktop$ google_appengine/dev_appserver.py three/
INFO 2014-09-06 21:35:19,347 api_server.py:171] Starting API server at: http://localhost:60503
INFO 2014-09-06 21:35:19,356 dispatcher.py:183] Starting module "default" running at: http://localhost:8080
INFO 2014-09-06 21:35:19,358 admin_server.py:117] Starting admin server at: http://localhost:8000
ERROR 2014-09-06 21:35:25,011 cgi.py:121] Traceback (most recent call last):
File "/home/loser/Desktop/three/page368b.py", line 13, in <module>
class BirthDetailsForm(djangoforms.ModelForm):
File "/home/loser/Desktop/google_appengine/google/appengine/ext/db/djangoforms.py", line 772, in __new__
form_field = prop.get_form_field()
File "/home/loser/Desktop/google_appengine/google/appengine/ext/db/djangoforms.py", line 370, in get_form_field
return super(DateProperty, self).get_form_field(**defaults)
File "/home/loser/Desktop/google_appengine/google/appengine/ext/db/djangoforms.py", line 353, in get_form_field
return super(DateTimeProperty, self).get_form_field(**defaults)
File "/home/loser/Desktop/google_appengine/google/appengine/ext/db/djangoforms.py", line 200, in get_form_field
return form_class(**defaults)
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/fields.py", line 340, in __init__
super(DateField, self).__init__(*args, **kwargs)
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/fields.py", line 99, in __init__
widget = widget()
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/forms/widgets.py", line 382, in __init__
self.format = formats.get_format('DATE_INPUT_FORMATS')[0]
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/utils/formats.py", line 67, in get_format
if use_l10n or (use_l10n is None and settings.USE_L10N):
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/home/loser/Desktop/google_appengine/lib/django-1.3/django/conf/__init__.py", line 40, 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.
I assume you're working with the example code that accompanies the book, available from this website: http://examples.oreilly.com/0636920003434/
If you download and expand the chapter 10 archive (chapter10.zip), you'll see several example files, and also several .zip archives. The page368b.py file corresponds with the webapp-chapter10-simpleform.zip archive. Open that archive to create a webapp-chapter10-simpleform directory. This directory contains an app.yaml file, the simpleform.py file (identical to page368b.py), birthDB.py (an ext.db model class), and static and template file directories.
Unfortunately, as you may have already noticed, the example doesn't work out of the box with the latest SDK. (I'm using version 1.9.10 of the SDK, which was just released.) It reports "ImportError: No module named django.core.exceptions" when you attempt to load the page. Strictly speaking, this example is not a Django application, but is merely trying to use a library that depends on Django being present.
The Python 2.5 runtime environment, which is selected by the app.yaml file included with this example, is meant to include Django 0.96 by default. However, this behavior has changed in the SDK since Head First Python was written. The smallest fix to get this example to work is to add these lines to simpleform.py prior to the import of djangoforms:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '0.96')
Then create a file named settings.py in your application root directory (the webapp-chapter10-simpleform directory). This file can be empty in this case. (As other commenters have noted, there is a better way to generate this file when using the Django framework, but in this case we just need the import to succeed.)
To upgrade this example to use the Python 2.7 runtime environment, modify app.yaml as follows:
application: simpleform
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /static
static_dir: static
- url: /*.
script: simpleform.app
The changes:
runtime: is now python27
threadsafe: true is added
The reference to simpleform.py is now a Python object path to the global variable app.
Then modify simpleform.py so that everything following the definition of the SimpleInput class is replaced with:
app = webapp.WSGIApplication([('/.*', SimpleInput)], debug=True)
Instead of running the simpleform.py script, the Python 2.7 runtime environment imports it as a module, then looks for a WSGI application object in a global variable. The lines we removed executed the app, and that's now done for us by the runtime environment.
From here, you can use a libraries: clause as you have done to select a newer version of Django, if you wish. A quick test in a dev server shows that the modified example works with Django 1.5, which is the latest supported version.
I am trying to create a script that populates a database with test users. I am new to Django and Python. I keep on getting:
Runtime error: App registry isn't ready yet.
Here is the output and error:
starting population script
Traceback (most recent call last):
File "populate.py", line 32, in <module>
populate()
File "populate.py", line 22, in populate
i.save()
File "c:\Python27\lib\site-packages\django-1.7a2-py2.7.egg\django\db\models\base.py", line 603, in save
force_update=force_update, update_fields=update_fields)
...
...
...
File "c:\Python27\lib\site-packages\django-1.7a2-py2.7.egg\django\apps\registry.py", line 156, in get_models
self.check_ready()
File "c:\Python27\lib\site-packages\django-1.7a2-py2.7.egg\django\apps\registry.py", line 119, in check_ready
raise RuntimeError("App registry isn't ready yet.")
RuntimeError: App registry isn't ready yet.
Here is the code:
import os
import datetime
def populate():
freer = User.objects.create_user( 'joyyie', 'lolcats#gmail.com', 'e')
cat = User.objects.create_user( 'steve', 'l2olcats#gmail.com', 'e')
dog = User.objects.create_user( 'aasd', 'lo3lcats#gmail.com', 'ad')
cow = User.objects.create_user( 'sadsfa', 'lol4cats#gmail.com', 't' )
pig = User.objects.create_user( 'regibald', 'lolc5ats#gmail.com', '0')
donkey = User.objects.create_user( 'turnip', 'lolca6ts#gmail.com', 'pop')
human = User.objects.create_user( 'tutu', 'lolcat7s#gmail.com', 'pa')
a = [freer,cat,dog,cow,pig,donkey,human]
for i in a:
i.first_name= 'jackee'
i.is_superuser=True
i.is_staff=False
i.date_joined=datetime.datetime.today()
i.last_login=datetime.datetime.today()
i.save()
if __name__=='__main__':
print "starting population script"
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'infosmos.settings')
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
populate()
Is there a way to force the user profile creation to wait for the registry app by using a signal or something?
[django 1.7] The Standalone script you wish to run, import django and settings like below
import os
import django
[...]
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
django.setup()
This is a known and intended behaviour according to Django's 1.7 release notes, under the "startup sequence" clause:
Another common culprit is django.contrib.auth.get_user_model(). Use the AUTH_USER_MODEL setting to reference the User model at import time.
and that should do the trick
for reference:
https://docs.djangoproject.com/en/dev/releases/1.7/#app-loading-changes
I found out that if I run populate through the manage.py shell with the execfile() command then it runs properly. Everything needed to be setup before I start modifying the database or run outside code. Thanks to lanzz for the hint.
I'm running into a few problems with adding gae-sessions to a relatively mature GAE app. I followed the readme carefully and also looked at the demo.
First, just adding the gaesesions directory to my app causes the following error when running tests with nose and nose-gae:
Exception ImportError: 'No module named threading' in <bound method local.__del__ of <_threading_local.local object at 0x103e10628>> ignored
All the tests run fine so not a big problem but suggests that something isn't right.
Next, if I add the following two lines of code:
from gaesessions import get_current_session
session = get_current_session()
And run my tests, then I get the following error:
Traceback (most recent call last):
File "/Users/.../unit_tests.py", line 1421, in testParseFBRequest
data = tasks.parse_fb_request(sr)
File "/Users/.../tasks.py", line 220, in parse_fb_request
session = get_current_session()
File "/Users/.../gaesessions/__init__.py", line 36, in get_current_session
return _tls.current_session
File "/Library/.../python2.7/_threading_local.py", line 193, in __getattribute__
return object.__getattribute__(self, name)
AttributeError: 'local' object has no attribute 'current_session'
This error does not happen on the dev server.
Any suggestions on fixing the above would be greatly appreciated.
I ran into the same problem. The problem seems to be that the gae testbed behaves differently than the development server. I don't know the specifics but ended up solving it by adding
def setUp(self):
testbed.Testbed().activate()
# after activating the testbed:
from gaesessions import Session, set_current_session
set_current_session(Session())