Python Django sqlite connection - python

I would like to create a simple dynamic Sudoku game. Idea is to create new "puzzle" every hour then put it to database and let users solve it. Each solve attempt is compared with database for verification. For that purpose I would like to create python script that generates puzzle and puts it to the database. My database set in models looks like this:
from django.db import models
class user(models.Model):
name = models.CharField(max_length=30)
password = models.CharField(max_length=30)
time_registered=models.DateTimeField()
time_uploaded=models.DateTimeField()
points=models.IntegerField()
saved_sudoku=models.CommaSeparatedIntegerField(max_length=81)
solved=models.BooleanField()
def __str__(self):
return self.name
class server_sudoku(models.Model):
time_uploaded=models.DateTimeField()
generated_sudoku=models.CommaSeparatedIntegerField(max_length=81)
Now, when I use :
name1=request.POST["name"]
pass1=request.POST["password"]
newuser=user(name=name1,password=pass1,time_registered=datetime.datetime.now(),time_uploaded=datetime.datetime.now(),points=0,saved_sudoku="",solved=False)
newuser.save()
in views.py it creates new user. So to verify my idea I created application "generate_sudoku.py". To test its connection to database I just try to add user. Code looks as follows:
#!/usr/bin/env python
from db_interface.models import user
import random
import datetime
newuser=user(name="name", password="pass", time_registered=datetime.datetime.now() ,time_uploaded=datetime.datetime.now(), points=0, saved_sudoku="", solved=False)
newuser.save()
This simple app gives me this error:
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.
Hope I made it clear, I would like to run this application by windows scheduler so that it is automatically run every hour...

Use a custom manage.py command.

First link on google : http://eliasbland.wordpress.com/2010/01/25/importerror-settings-cannot-be-imported-because-environment-variable-django_settings_module-is-undefined/ ;)
This works for me (in a lambda script, not _ _init _ _.py file) :
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.contrib.auth.models import User #import django stuff after
print User.objects.all()

Related

Error adding new models to database Django

models.py
class Genre(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
Genres.py
from MyVideoGames.models import Genre
from ClientIGDB import ClientIGDB
genres = ClientIGDB.api_call("genres", ["name"], 50)
for genre in genres:
g = Genre.objects.create(name=genre["name"])
g.save()
When I'm trying to add some models to sqlite db i'm not able to do this import:
from myproj.models import Genre. I don't know why...
When I do it this error is shown:
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
If someone can help me I'll be really gratefull
Whenever you run a script that uses python models you need to tell python that django exists first. Try this at the beginning of your script:
import os
import sys
import django
sys.path.append("/path/to/your/project")
os.environ["DJANGO_SETTINGS_MODULE"] = "yourProjectName.settings"
django.setup()
It's like a mini settings.py. You are not running something 'inside' django, so you need to start things up first. I wonder if anybody else could refine this to a solution that we don't need to hard code this every time we write a new script.

How to import a class from ndb.Model?

I'm working with Google App Engine and I want to use my ndb model in another .py file but I couldn't import it.
Here is my main.py;
from google.appengine.ext import ndb
class User(ndb.Model):
username = ndb.StringProperty()
created_date = ndb.DateTimeProperty(auto_now=True)
follower_list = ndb.StringProperty(repeated=True)
And this is some code from my cron.py file:
from google.appengine.ext import ndb
save_user = User.query().filter(User.username == username)
But I'm getting:
ImportError: No module named User
How can I import the User class?
When you create the model you're just instantiating a class and assigning it to the variable named User. In python those variables are bound to the module they were declared in, and there are no implicit globals, so if you want to use it in another module you would need to import it:
from google.appengine.ext import ndb
import main
save_user = main.User.query().filter(main.User.username == username)
However the best practice would be to create the models in a models.py file, and import that anytime you need them.
BTW, your error hints that you're trying to import User earlier in your cron file, is that so? Either way I think you should get the idea now :)

flask peewee not working on web server

im unable to get access to the peewee database from a python script other than the one writing the data (but weirdly in the interactive shell). I'm developing a data mining application with python,flask,and peewee. I'm going to cut it up into a byte size problem here, but it is large in scope than what im presenting. all python files are located in the same folder
the basic process is a python command line operation that goes out and grabs some information from the new york times and instagram and stores them into Peewee (sqllite) database. I then use a flask application to explore the data.
heres one of the models from database.py:
from peewee import *
class Story(Model):
title = CharField()
story = TextField()
date = DateField()
class Meta:
database = SqliteDatabase("newsalmost.db",threadlocals = True)
newsalmost looks something like this:
from database import *
class NewsAlmost(object):
def __init__(self):
self.db = SqliteDatabase("newsalmost.db",threadlocals = True)
if does stuff like this:
story = Story.create(title = self.feed.stories[key]["title"], story = self.feed.stories[key],date = datetime.datetime.now(), is_relative = True)
i can then run:
"python newslamost.py -g"
and it will go gather stuff and write them to the database
i then have a file called webapp.py, which is a flask app
import newsalmost
from flask import Flask
from flask import send_file
import subprocess
app = Flask(__name__)
import os
import json
from database import *
#app.route("/")
def index():
r = []
for i in Image.select():
r.append(str(i))
return json.dumps(r)
"python webapp.py"
I've tried to strip it down to the core problem. The flask app never sees anything in the database.. ever..
i KNOW its logging them correctly, because i can actually run "python" in that folder, import database and i get many stories from Stories.select()
the WEIRDER thing is that i initially had architected this in a more desirable way where the flask app merely creates a new instance of the newsalmost instance then calls functions on that to return stuff from the database and this worked.. IN DEV MODE. But when i deployed it to my web faction server (and got everything up there running), i am again greeted always with an empty response from the database. this is my attempt to try and directly reference the database in flask, thinking that maybe it was newsalmost fucking things up.. but nope.
I'm just bewildered why an sqllite database would perform exactly as expected locally, but not once deployed to a webserver, but also... why does the flask code i provided not get anything from the database, but running the same database query in the interactive shell work?
any ideas?
I don’t know if that would solve your problem, but you should use the same database object in both modules:
database.py:
from peewee import *
db = SqliteDatabase("newsalmost.db",threadlocals = True)
class Story(Model):
title = CharField()
story = TextField()
date = DateField()
class Meta:
database = db
newsalmost.py:
from database import *
class NewsAlmost(object):
def __init__(self):
self.db = db

ReferenceField in mongoengine

I use mongoengine with django. I have two applications with models.
app1/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model1(Document):
name = fields.StringField()
lists = fields.ListField(fields.ReferenceField("Model2", dbref=False))
app2/models.py:
from mongoengine import fields
from mongoengine.document import Document
class Model2(Document):
name = fields.StringField()
All applications were added to INSTALLED_APPS. When I use the django dev-server, everything is fine. But using this code with uwsgi-server there is an error:
Model2 has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
What I should do?
You should import app2.models somewhere. Put a comment by the import saying why it's there, so nobody removes the useless-looking import in the future.
When the django dev server starts up it imports the models from all installed apps and validates them. You'll see
Validating models...
0 errors found
This does not happen in a production environment. It is just a nicety of the dev server.

Python import problem with Django management commands

For whatever reason, when I was new to Python and Django, I wrote some import statements like this at the top of a models.py file:
from django.contrib import auth
And I'd use it like this:
class MyModel(models.Model):
user = models.ForeignKey(auth.models.User)
# ...
This worked fine. A long time later, I wrote a custom management command, and it would do this:
from myapp.models import MyModel
When I ran my custom command (python manage.py my_command) this would result in Python complaining that the module auth had no attribute models on the line declaring the ForeignKey in models.py.
To work around this problem, I changed my models.py to the more usual:
from django.contrib.auth.models import User
class MyModel(models.Model):
user = models.ForeignKey(User)
# ...
Can someone explain to me what I am missing? Is there something different in the environment when you run a management command? Or was I just doing it wrong the whole time? Thanks!
Edit: Following dmitko's hunch about circular imports, here are the imports used in my models.py file. I'm showing the original import of auth commented out, along with the only model that has a foreign key to the auth user model:
import datetime
from django.db import models
# from django.contrib import auth
from django.contrib.auth.models import User
class UserLastVisit(models.Model):
# user = models.ForeignKey(auth.models.User, unique=True)
# ^^^^^^^^^^^^^^^^
# after adding mgmt command, error occurred here; change to the line below
user = models.ForeignKey(User, unique=True)
last_visit = models.DateTimeField(db_index=True)
And here are the imports of the management command that uncovered the problem:
import datetime
from django.core.management.base import NoArgsCommand
from core.models import UserLastVisit, AnonLastVisit, Statistic
Was this setting up a circular import type situation?
If some random module ever imports module x.y.z, then a later person who imports just x.y will see a z in the x.y namespace.
The reason this happens is that import x.y.z is actually three import statements in one. It works something like this:
x = __internal_import('x')
x.y = __internal_import('x/y')
x.y.z = __internal_import('x/y/z')
Next time someone does __internal_import('x/y'), they'll get the same object, because python is smart enough not to import the same one twice. That object already has its z member assigned to the z module.
In your full app, probably you had a module that did import django.contrib.auth.models. But your minimal standalone program didn't import that module, so the name was never assigned.
(Note: there's no such thing as __internal_import. It's just an illustration. The real function has some other name that you would have to look up.)
I guess that if you do from django.contrib import auth that means you're importing auth package as a module and what it exports is driven by __init__.py in the auth folder:
>>> from django.contrib import auth
>>> dir(auth)
['BACKEND_SESSION_KEY', 'ImproperlyConfigured', 'REDIRECT_FIELD_NAME', 'SESSION_
KEY', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'authentica
te', 'datetime', 'get_backends', 'get_user', 'import_module', 'load_backend', 'l
ogin', 'logout']
You can check __init__.py in django\contrib\auth and see the same function list. When you import from django.contrib.auth.models import User that means that you're importing a submodule from the auth package and it works.
BTW. I was unable to use auth.models.User in any case - whether I run from console or from my django app.
It's hard to say exactly what's going on without seeing the new manage.py command that you added. However, I often see the " has no attribute " in cases with circular imports, and it's almost always fixed by changing the module-level imports to function- or class-level imports, as you did here. You might check if anything like that is going on here.

Categories