Questions? Feedback? powered by Olark live chat software
Přeskočit navigaci

Using Django, Python, and MySQL on Windows Azure Web Sites: Creating a Blog Application

Publikováno dne 16 prosince, 2013

Program Manager, Azure App Service
Depending on the app you are writing, the basic Python stack on Windows Azure Web Sites might meet your needs as-is, or it might not include all the modules or libraries your application may need. Never fear, because in this blog post, I’ll take you through the steps to create a Python environment for your application by using Virtualenv and Python Tools for Visual Studio.  Along the way, I’ll show you how you can put your Django-based site on Windows Azure Web Sites.

Create a Windows Azure Web Site with a MySQL database

Next, log in to the Azure Management Portal  and create a new web site using the Custom create option. For more information, See How to Create Azure Websites .  We’ll create an empty website with a MySQL database. 5611.website1.jpg-550x0 Finally choose a region and, after you choose to accept the site Terms, you can complete the install.  As usual, it’s a good idea to put your database in the same Region as your web site to reduce costs. 4375.website2.jpg-550x0 Double click on your Website in the Management portal to view the website’s dashboard. Click on “Download publish profile”. This will download a .publishsettings file that can be used for deployment in Visual Studio. 2273.website3.jpg-550x0

Create a Django project

For this tutorial we will be using Visual Studio to build our Django Web Application. To build your application with Visual studio, install PTVS 2.0 . For more details, see How to build Django Apps with Visual Studio Open Visual Studio and create a New Project > Other Languages > Python > Django Project  0576.website4.jpg-550x0 In the solution explorer, create a new Django Application your Django Project by right clicking on DjangoProject > Add > DjangoApp 8176.website6.jpg-550x0

Enter the name of your Django application, say myblog 

2783.website7.jpg-400x0

Create a virtual environment

Simply put, virtualenv allows you to create custom, isolated Python environments.  That is, you can customize and install different packages without impacting the rest of your site.  This makes it useful for experimentation as well. In the Solution explorer, Right click on Python Environments in your Django Project and Select “Add Virtual Environment”

1323.website8.jpg-550x0

Enter the virtual environment name, say “env” . This will create a folder called “env” which will contain your virtual python environment without any python packages except for pip

4353.website9.jpg-550x0

Install MySQL-Python and Django packages in your virtual environment

In the solution explorer, Right-click on environment env and Install Python package: django 4810.website10.jpg-550x0 You can see the Output of the installation of Django in your virtual environment

0333.website11.jpg-550x0

Similarly, you need to install mysql-python, but use easy_install instead of pip as seen here 5707.website12.jpg-550x0 Now you have both Django and MySQL for Python installed in your virtual environment

Build your Database Models

A model in Django is a class that inherits from Django Model class and lets you specify all the attributes of a particular object.  Model class translates its properties into values stored in the database. Let’s create a simple model called Post with three fields: title, date and body to build a post table in my database. To create a model, include a models.py file under the myblog/ folder.

#import from Model class

from django.db import models

class Post(models.Model):

 #Create a title property

    title = models.CharField(max_length=64)

#Create a date property

    date = models.DateTimeField()   

#Create a body of content property

    body = models.TextField()

# This method is just like toString() function in .NET. Whenever Python needs to show a

#string representation of an object, it calls __str__

    def __str__(self):

        return "%s " % (self.title)

Installing the Models

We’ll need to tell Django to create the model in the database.  To do this, we need to do a few more things:
  • First, we’ll configure the application’s database in settings.py. Enter the MySQL database information associated with the Windows Azure Web Site.

DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'MYSQL-DATABASE-NAME',                     

        'USER': 'MYSQL-SERVER-USER-NAME',                     

        'PASSWORD': 'MYSQL-SERVER-USER-PASSWORD',                  

        'HOST': 'MySQL-SERVER-NAME',                     

        'PORT': '',

    }

}    

Next, add your application to your INSTALLED_APPS setting in settings.py.

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',

    'django.contrib.staticfiles',  

    'myblog',

    )

  • Once we’ve saved the settings in settings.py, we’ll create the schema in your Clear DB database for the models we’ve already added to models.py. This can be achieved  Run Django Sync DB
1778.website16.jpg-550x0 You can write your own code to manage creating, editing, deleting posts for your blog or you can use the administration module Django offers which provides an Admin site dashboard to create and manage posts.  Refer to this article on how to enable a Django admin site.

Setup a Django Admin site

The admin site will provide a dashboard to create and manage blog posts. First, we need to create a superuser who can access the admin site. To do this run this command if you haven’t created an admin user already.

Python manage.py createsuperuser

You can use the Django Shell to run this command. For more details on how to use Django Shell refer this article   8037.website17.jpg-550x0   The admin module is not enabled by default, so we would need to do the following few steps:
  • First we’ll add 'django.contrib.admin' to your INSTALLED_APPS setting in settings.py

INSTALLED_APPS = (

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.sites',

    'django.contrib.messages',

    'django.contrib.staticfiles',  

    'myblog',

    )

  • Now, we’ll update urls.py to process a request for the application to the admin site and to the home page view.

from django.conf.urls import patterns, include, url

#import admin module

from django.contrib import admin

admin.autodiscover()

#set url patterns to handle requests made to your application 

urlpatterns = patterns('',

     url(r'^$', 'DjangoApplication.views.home', name='home'),            

     url(r'^admin/', include(admin.site.urls)),

)

  • Next, we’ll create  an admin.py under the  myblog/ folder  to register Post model

from models import Post

from django.contrib import admin

#Register the database model so it will be visible in the Admin site

admin.site.register(Post)

Build a Page view

We’ll create a to list all the blog posts you have created. To create a page view, include a views.py file under the myblog/ folder

from django.shortcuts import render_to_response

from models import Post

#Creating a view for the home page

def home(request):

   posts = Post.objects.all()

   #Renders a given template with a given context dictionary and

returns an

   #HttpResponse object with that rendered text.

   return render_to_response('home.html', {'posts': posts} )

Displaying a Post object is not very helpful to the users and we need a more informative page to show a list of Posts. This is a case where a template is helpful. Usually, templates are used for producing HTML, but Django templates are equally capable of generating any text-based format. To create this template, first we’ll create a directory called templates under myblog/. To display the all the posts in views.py, create a home.html under the templates/ folder which loops through all the post objects and displays them.

<html>

 <head><title>My Blog</title></head>

 <body>

   <h1>My Blog</h1>

{% for post in posts %}

<h1>{{ post.title }}</h1>   

<em> <time datetime="{{ post.date.isoformat }}">

{{ post.date}}</time> <br/>

</em> 

<p>{{ post.body }}</p>

 {% endfor %} 

 </body>

</html>

Set static directory path

If you access the admin site now, you will noticed that the style sheets are broken. The reason for this is the static directory is not configured for the application. Let’s set the static Root folder path to D:\home\site\wwwroot\static from os import path PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__))) STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\','/')   STATIC_URL = '/static/' Once we’ve saved these changes in settings.py, run this command to collect all the static files in “static” folder for the Admin site using Django Shell

   Python manage.py collectstatic

Set Template Directory path

We’re nearly done!   Django requires the path to the templates directory and static folder directory to be configured in settings.py. There’s just a couple of steps needed to do that.
  • Let’s create a variable for  the path of the SITE_ROOT

import os.path

SITE_ROOT = os.path.dirname(__file__)

  • Then, we’ll set the path for Templates folder.  TEMPLATES_DIR informs Django where to look for templates for your application when a request is made.

TEMPLATE_DIRS = (

   os.path.join(SITE_ROOT, "templates"),)

Deploy the application We are now all set to deploy the application to Windows Azure website, mydjangoblog .Right click you’re DjangoProject and select “Publish” 7711.website19.jpg-550x0 You can validate the connection and then click on publish to initiate deployment. Once deployment is successfully completed, you can browse your website to create your first blog. 7360.website20.jpg-550x0

Create your blog post

To create your blog, login to the admin site http://mydjangoblog.azurewebsites.net/admin with the super user credentials we created earlier. 1018.website21.jpg-400x0 The Dashboard will include a Link for your model and will allow you to manage the content for the model used by your application. Click on Posts 2211.website22.jpg-550x0 Create your first blog post and Save 3771.website23.jpg-550x0 Let’s browse the site’s home page, to view the newly created post. 0184.website24.jpg-550x0 Now you have the basics for building just what you need in Python on Windows Azure Web Sites. Happy coding :)

Further Reading

Django Project Python Tools for Visual Studio Wiki Video tutorials for Python Tools for Visual Studio Windows Azure Websites (WAWS)  
Web