Wednesday, February 13, 2013

Testing MathJax on Blogger

You should see the time-dependent Schroedinger Equation here:

   2 2 m 2 x 2 + V Ψ = i t Ψ

courtesy of a simple new line in the Blogger template. Right-clicking it will allow you to copy it in MathML, since it was written this way. The equation below was written in LaTeX, so I can be copied out as such. This is so cool!

This is a test for inline LaTeX: \(\frac{a}{b}\).
And here we have a nice limit as an equation: $$\lim_{x \to \infty} \exp(-x) = 0$$. This was written as LaTeX
$$\lim_{x \to \infty} \exp(-x) = 0$$
and must be entered with the $$ delimiters on Blogger's HTML tab, otherwise the Blogger formatter will mangle it.

Mongo, Django and the Admin View - work in progress

Once you switch Django to a MongDB backend with MongoEngine (see my previous posts), you loose Django's automatic admin view. This is a pity since it's such a nice web CRUD interface. There are some options though to get it back, among them mongoadmin Since I like working with Django 1.6 dev trunk, I needed to adapt mongoadmin in two spots: options.py and sites.py.

Here are the diffs of the changes I have made so far, without breaking backward compatibility, however surfing to the admin page still throws an error, so I will update this page when I get a chance and not commit (yet). Perhaps it's already useful for somebody - comments welcome!

For options.py
@@ -11,7 +11,11 @@
 from django.db import models, transaction, router
 from django.db.models.related import RelatedObject
 from django.db.models.fields import BLANK_CHOICE_DASH, FieldDoesNotExist
-from django.db.models.sql.constants import QUERY_TERMS, LOOKUP_SEP
+from django.db.models.sql.constants import QUERY_TERMS
+try:
+  from django.db.models.sql.constants import LOOKUP_SEP
+except ImportError:
+  from django.db.models.constants import LOOKUP_SEP
 from django.http import Http404, HttpResponse, HttpResponseRedirect
 from django.shortcuts import get_object_or_404, render_to_response
 from django.utils.decorators import method_decorator

For sites.py
@@ -207,7 +207,10 @@
         return update_wrapper(inner, view)

     def get_urls(self):
-        from django.conf.urls.defaults import patterns, url, include
+        try:
+            from django.conf.urls.defaults import patterns, url, include
+        except ImportError:
+            from django.conf.urls import patterns, url, include

         if settings.DEBUG:
             self.check_dependencies()


BTW, I've started to use SyntaxHighlighter for code. Thanks Alex!

Mongo and Django

Like I described in the last post, I installed mongo and its python API mongoengine. Now I wanted to see if I could connect it to my preferred Python Web framework, Django.  A very nice tutorial on IBM DeveloperWorks got me interested in trying this too.

I use Eclipse and the very nice PyDev Python plug-in for Django development. The latter offers a little bit of Django integration into Eclipse, so a had a bare-bones Django site in no time at all, with the standard settings.py file. At this point, the site was based on SqlLite, Django's default.

Now the first bit is to connect to MongoDB inside settings.py, following the Mongoengine tutorial, like so:


import mongoengine  

 
 DEBUG = True  
 TEMPLATE_DEBUG = DEBUG  
 ADMINS = (  
   # ('Your Name', 'your_email@example.com'),  
 )  
 MANAGERS = ADMINS  
 DATABASES = {  
   'default': {  
     'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.  
     'NAME': 'C:\\Users\\me\\src\\test\\django_mongo\\sqlite.db',           # Or path to database file if using sqlite3.  
     # The following settings are not used with sqlite3:  
     'USER': '',  
     'PASSWORD': '',  
     'HOST': '',           # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.  
     'PORT': '',           # Set to empty string for default.  
   }  
 }  


 print 'Connection to MongoDB...',  
 mongoengine.connect('test')  
 print 'connected.'  

Additional lines that go to the bottom of settings.py are

 
AUTHENTICATION_BACKENDS = (  
   'mongoengine.django.auth.MongoEngineBackend',  
 )  
 SESSION_ENGINE = 'mongoengine.django.sessions'  

At this point I was able to run the Django shell, but of course had no models to play with. So I made an app with the standard Django manage.py startapp replicated the ones from the tutorial, except for the User model, which I imported from the mongoengine auth backend:

 from mongoengine import *  
 from mongoengine.django.auth import User  
   
 # Create your models here.  
 class Comment(EmbeddedDocument):  
   content = StringField()  
   name = StringField(max_length=120)  
   
 class Post(Document):  
   title = StringField(max_length=120, required=True)  
   author = ReferenceField(User, reverse_delete_rule=CASCADE)  
   tags = ListField(StringField(max_length=30))  
   comments = ListField(EmbeddedDocumentField(Comment))  
   
 class TextPost(Post):  
   content = StringField()  
   
 class ImagePost(Post):  
   image_path = StringField()  
   
 class LinkPost(Post):  
   link_url = StringField()  
   

Back in the Django shell, I got some FutureWarnings regarding inheritance soon defaulting to off, but I successfully tested
 In [2]: c=Comment(content='lala', name='Useful comment')  
 In [3]: u=User()  
 In [4]: u.username='me'  
 ...  
 In [30]: u  
 Out[30]: <User: me>  
   
 In [31]: User.objects.all()  
 Out[31]: []  
   
 In [32]: u.save()  
 Out[32]: <User: me>  
   
 In [33]: User.objects.all()  
 Out[33]: [<User: me>]  
   
 In [35]: p=Post(title='T', author=u, tags=['t1','t2'], comments=[c])  
   
 In [36]: p.save()  
 Out[36]: <Post: Post object>  
   
 In [38]: Post.objects.all()  
 Out[38]: [<Post: Post object>]  
   
 In [39]: Post.objects.all()[0]  
 Out[39]: <Post: Post object>  
   
 In [40]: Post.objects.all()[0].comments  
 Out[40]: [<Comment: Comment object>]  
   
 In [41]: Post.objects.filter(title='A')  
 Out[41]: []  
   
 In [42]: Post.objects.filter(title='T')  
 Out[42]: [<Post: Post object>]  
   
 In [43]: Post.objects.filter(title__in=['A','T'])  
 Out[43]: [<Post: Post object>]  

But I did get stuck at joins that span relations:
 In [54]: Post.objects.filter(author__username='me')  
 Out[54]: ---------------------------------------------------------------------------  
 InvalidQueryError             Traceback (most recent call last)  

Either I got something wrong or a bug tripped me! I will definitely crosspost this at Mongoengine and StackOverflow.

BTW, this was done with Django 1.6 20130110 dev trunk and Mongoengine 0.7.9 .

Tuesday, February 12, 2013

MongoDB on Windows

We just had a very nice overview talk on MongoDB, so I wanted to give it a shot, especially its Python interface Mongoengine and installed it on my notebook. Turns out installing is just as easy as the docu said. Unzip the package from Mongo's download page into the directory of your choice, create a cfg file with two entries,
dbpath pointing to the directory where Mongo will place its DB files and logpath pointing to the log file.

Then install it as a service in a shell with administrator rights:


D:\>d:\packages\mongodb-win32-x86_64-2008plus-2.2.3\bin\mongod.exe --config c:\U
sers\me\mongodb.cfg --install
all output going to: D:\logs\mongo.log

D:\>net start MongoDB

The Mongo DB service was started successfully.

D:\>


The installation can be immediately tested with mongo.exe:


C:\Users\usd22492>d:\packages\mongodb-win32-x86_64-2008plus-2.2.3\bin\mongo.exe
MongoDB shell version: 2.2.3
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user


Now on to the even simpler installation of MongoEngine (provided Python and pip are already onboard):

pip install -U mongoengine

Just like the docu says.


'via Blog this'