Tuesday, 9 February 2016

Django MySQL settings

Due to the fact that I couldn't find anywhere that actually spelled it out explicitly, here's the minimum you need in your settings.py file if you're using a MySQL DB for your Django project and you're using an external DB server (ie, not localhost):

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'name',
        'HOST': '192.168.0.1',
        'PORT': '3306',
        'USER': 'user',
        'PASSWORD': 'password'
    }
}

It's probably obvious to everyone, but who knows - it might save someone some hassle some day.

Baby steps with Python and Django

I've neglected this blog lately, but I've decided to pick it up again.  I've started a new project for my self in Python and I want to keep a bit of a track of what I've learned.

I've basically been following the (rather excellent) Django tutorials so far, but today I wanted to start deviating.  Here's how I've gotten to where I am with the project so far:

Used Homebrew to install Python 3 (my Mac comes with Python 2.7 installed by default, but I wanted to go with the latest version):


$ brew install python3

Then it was time to set up a Virtual Environment for my project.  According to this Ask Ubuntu post, virtualenv isn't set up to run with Python3 yet, so I used pip3 rather than the normal pip.

$ sudo pip3 install virtualenv
...
$ virtualenv-3.3 project

I'm using PyCharm to manage my project, which comes with a built in Terminal window and Python Console.  Within the Terminal window, we need to use the virtualenv for the project:

$ source bin/activate

Then it's a case of installing Django

$ pip install django

Installing the MySQL connector

$ pip3 install mysqlclient

Oops - but that didn't work:  OSError: mysql_config not found.  Turns out the mysqlclient connector for Python needs MySQL (or at least the developer library) installed.  Despite it being about running on Linux, I found this Stack Overflow post quite useful.  Back to Homebrew to fetch MySQL:

$ brew install mysql

After that mysqlclient installed without a project.  Finally it's time to create a project:

$ django-admin startproject project

And there you go - all of the building blocks are in place to start things off!

Wednesday, 22 July 2015

Overcoming assembly binding problems with Web Roles running in Azure Cloud Services

I'd been having trouble getting a Web Role instance started in an Azure Cloud Service - the deployment would run successfully, but the application would constantly recycle.  It turns out that the problem was the Web Role entry point couldn't be created thanks to missing assembly bindings.

It took a lot of digging around, but I managed to find out that the Web Role runs completely independently of the normal website process, meaning it misses out on any assembly binding changes you've made in your web.config file.  According to this blog post from Microsoft:

with full IIS, the RoleEntryPoint runs under WaIISHost.exe, while the web site runs under a normal IIS w3wp.exe process.

The long and the short of this is that you need to include your assembly bindings in a new .config file that WaIISHost.exe will pay attention to.  To do this, do the following:

  • In the web project that forms your web role, create a new .config file
  • The file name should match your project's assembly, such as project.web.dll.config
  • In the file's properties, set Copy to output directory to Copy always

This will put the new .config file in the approot/bin folder when deployed, meaning WaIISHost.exe can read it.  Hooray!

There are lots of related SO questions and blog posts on this:

Thursday, 23 May 2013

Making sure Google Analytics is done before submitting a form

Want to track form submissions with Google Analytics, but losing the data because the form submits before the asynchronous GA code is done? Fear not, Google has added a callback event.

This StackOverflow post contains an answer that outlines (in a single onclick statement if that floats your boat) how to do it. In summary:

onclick="var _this=this;_gaq.push(['_set','hitCallback',function(){$(_this).parents('form').first().submit();}]);_gaq.push(['_trackEvent','My category','My action']);return !window._gat;"

Tuesday, 18 December 2012

Securing web fonts in IIS 7

Need to prevent leaching or hot-linking of your web fonts in IIS 7? I found not just one but two posts outlining how to achieve this. To sum up, put something like this in your web.config:

<system.webServer>
 <rewrite>
   <rules>
     <rule name="Prevent font hotlinking">
       <match url=".*\.(eot|svg|ttf|woff)$" />
       <conditions logicalGrouping="MatchAny">
         <add input="{HTTP_REFERER}" pattern="$^" /> <!-- No referrer -->
         <add input="{HTTP_REFERER}" pattern="^https?://(.*\.)?({local domain}|{dev domain}|{staging domain}|{live domain}).*$" negate="true" /> <!-- Not from your site -->
       </conditions>
       <action type="Rewrite" url="/font/no-hotlinking.txt" />
     </rule>
   </rules>
 </rewrite>
</system.webServer>

Of course, don't forget to change the {domains} in the above example for your own.

Monday, 12 November 2012

LINQ, Counts and Group By

After a particularly busy weekend full of late nights working remotely towards a looming deadline, I was having trouble with writing a LINQ query that would return me values based on a GROUP BY clause. What I basically wanted was:

SELECT COUNT(Id)
FROM Table
GROUP BY UserId

I had no idea what the LINQ GroupBy() method actually returned, but this article helped me figure it out.

Table
  .GroupBy(x => x.UserId)
  .Select(g => g.Count());

Or, even more handy:

Table
  .GroupBy(x => x.UserId)
  .Select(g => new { userId = g.Key, count = g.Count() });

Thursday, 8 November 2012

Application level error handling

On the project I've been working on, we've been asked to log any exceptions that are thrown by the site. There are packages out there (like ELMAH), but in case you want to add some form of custom logging (or extra handling), there's a useful chunk of sample code for doing just that. :)