Pylons, MSSQL, SQL Alchemy

By kipb7

We wanted to have JavaScript pass JSON notation {“such”:”as”,”this”:["example",2],”here”:{}} to Pylons and then have Pylons interpret it as a Python object.  Django includes a serializer but Pylons did not seem to (see note below.)  TurboGears has the @jsonify decorator.  There are several json packages out there we could use.  I typed easy_install jsonlib and it was ready to use.  import jsonlib and then either python_object = jsonlib.read(“”"{“some”:”json”}”"”) or string_output = jsonlib.write(python_obj). 

Note: it seems Pylons also has the @jsonify decorator (you put it in front of your action function) also see decorators/__init__.py, which uses simplejson, but I didn’t find it when I was looking for json and pylons!  I believe the default 0.9.6 Pylons also includes simplejson, so I didn’t need to get jsonlib.

Anyway, jsonlib works fine and it won’t be hard to switch if needed later on.

Next problem: We wanted to connect to a Microsoft SQL Server (MSSQL) using a “Trusted Connection” instead of username/password.  We were using PyMssql.py which worked fine up until then.  We struggled to figure out how to pass the “TrustedConnection=Yes” bit and not the UID=sa etc.  It turns out that pymssql is not capable of that, so we switched to pyodbc which does the trick.  There are yet other alternatives including a commercial one (mxodbc for $140) but this works for now.

Next problem: Some of our tables have integer primary keys, which properly should be auto-incrementing.  Due to issues when moving back and forth between SQL Servers, we made those tables NOT have auto-increment primary keys.  We would do Declare @x int  Select @x = 1+max([ID]) from Table_name and then Insert into Table_name Values (@x, …) which is risky in the case of two simultaneous inserts (2nd attempt may get a duplicate key error.)  In SQL Alchemy we used, in the Table and Column declaration, default=text (“1+(select max([ID]) from Table_name)”) but MS SQL won’t allow a Select in the value of an Insert.  Fortunately, SQL Alchemy (SA) lets you put preexecute_pk_sequences=True up at the top of class MSSQLDialect_pyodbc and that did the trick.  That makes it do the Select 1+Max… first and then use its result value in the Insert.  It seems that SA is doing a round-trip here as opposed to the @x variable approach above which doesn’t require an extra round trip.  This means it’s slower and more likely to have a collision but we’ll switch to true auto-increment someday!

Leave a Reply