Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, July 30, 2008

Sending an email with Google App Engine

When I first started learning, my application aim was a 'Mass Mailer' with Google App Engine. To start (as a newbie in this domain), I should start with the simplest operation: 'Sending an email using Google App Engine'.

To do this I was lost, I don't know anything about Python. But, how? Take a look around you'll probably find something, return always to the Google App Engine Documentation. Yes, the Send Mail section is available. Let's see it.

Mail Api docs, give you the sample from the overview! Here's what I found

from google.appengine.api import mail

class ConfirmUserSignup(webapp.RequestHandler):
def post(self):
user_address = self.request.get("email_address")

if not mail.is_email_valid(user_address):
# prompt user to enter a valid address

else:
confirmation_url = createNewUserConfirmation(self.request)
sender_address = "support@example.com"
subject = "Confirm your registration"
body = """
Thank you for creating an account! Please confirm your email address by
clicking on the link below:

%s
""" % confirmation_url

mail.send_mail(sender_address, user_address, subject, body)


Before doing anything! You need to know, that the Send mail function isn't included by default so when running your server, you should add the following command
dev_appserver.py --enable_sendmail
Or your mail won't be sent.
Then create a new Google App Engine Application. If you don't know how, here's a quick startup to create your Google App Engine application in minutes.

Trouble in manipulating this code? No, don't do, you don't need. First we are going simply to test the send_mail function, second we are going to use the Django Frameword and not the Google one.

Here's the code, that I use, simple and clean

from google.appengine.api import mail

print 'Content-Type: text/plain'
print ''
print 'I think the email was sent or going to!'
mail.send_mail("omar.abid2006@gmail.com", "omar.abid2006@gmail.com", "Google Coder", "Googler Coder Welcome")


Here's the list, don't be stupid!
  • Your application won't work on your Localhost, so upload it
  • To upload it, seek this article
  • Run your application 'name.appspot.com'
  • Check your inbox
  • Don't Send more than 2000, see quotas here
Ok, here's the first goal and it was done, more to come in the future.

Sunday, July 27, 2008

Python and Django code editors

Now we enter the development phase, so an editor is needed. We are going to focus on a Python editor, but we also prefer that it's a django one, so things will be more easier.
To not search the web, Python official website, published a list of editors. You can check this list of Python editors.

If we are going to search for a simple editor, so why not only use note pad. There's many editors on the Python editors list, some don't create .py files even; but the most are simple editors that just highlight your code and this is really stupid and won't help us.

What we need exactly is an IDE (Integrated Dev elopement Environment). It's possible to find a high quality and free IDE on the web, so the quest is to search. I find many, but no one was good and helpful. I don't really know how to find it.

Perhaps, because I'm searching a very advanced one, like Visual Studio. Ohh, I have read a thread in Reddit, the guy asks what text editor do you use with Django. The good users didn't give a link, so I had to search every term they put; I focus on the editors but they were awful!

Ok, you are searching for an advanced, professional, IDE for pyhton and Django. Don't search I already had done it.
Wing IDE is good, many features are in. It's advanced and for professional use. You can check out the screen shots. But what can I say, it's paying. And we are working Open Source for the community. It really sucks to pay $179 and additional $30 for a cover and also shipping costs :p

Waak, yet another Pyhton, ruby, php IDE. It's called Aptana Studio. It looks smart and pro, but sucks $99, oh no that's only for Pro edition. There's the community edition. (it's free).
It works on Mac, windows and linux. So joy for all Python programmers.
You should ask, why there's two version, one free and one not! Ok, those version aren't different, the pro just inlcude a support and pro plug-ins. Which may be not necessary so much. If it's then you must pay :)
Ok, let's quit those money suckers. Here's the Open Source IDE for Python and Django!
NetBeans, that's it! But I would prefer Aptana. Ok, download them both and decide what to choose.

Hope it helps! Know an IDE? Let me hear from you!

Django Platform for Google App Engine

I was surfing those days Google App Engine websites and found that the most popular and used platform to work with Google App Engine is Django. Luckily, it's already included on Google App Engine SDK in the lib folder. But I always give a hit for the official website and so you can do and visit the Django website.

The website documentation is so cool, more than that I found free book, you can get it here.
But what's Django and how it works?
As I said Django is a python Framework, written in pure python, then the matter is to know python and then Django will only accelerate your work
At its core, Django is simply a collection of libraries written in the Python programming language. To develop a site using Django, you write Python code that uses these libraries. Learning Django, then, is a matter of learning how to program in Python and understanding how the Django libraries work.
From the Django book
Ok, so we have to come back to Python, oh yes, here's a small comparision between python and django.
The example (found it in the django book) displays the ten most recently published books from a database.
The sample written in Pure Python

#!/usr/bin/python

import MySQLdb

print "Content-Type: text/html"
print
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"

connection = MySQLdb.connect(user='me', passwd='letmein', db='my_db')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")
for row in cursor.fetchall():
print "<li>%s</li>" % row[0]

print "</ul>"
print "</body></html>"

connection.close()

The sample written in Django

# models.py (the database tables)

from django.db import models

class Book(models.Model):
name = models.CharField(maxlength=50)
pub_date = models.DateField()


# views.py (the business logic)

from django.shortcuts import render_to_response
from models import Book

def latest_books(request):
book_list = Book.objects.order_by('-pub_date')[:10]
return render_to_response('latest_books.html', {'book_list': book_list})


# urls.py (the URL configuration)

from django.conf.urls.defaults import *
import views

urlpatterns = patterns('',
(r'latest/$', views.latest_books),
)


# latest_books.html (the template)

<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<ul>
{% for book in book_list %}
<li>{{ book.name }}</li>
{% endfor %}
</ul>
</body></html>


I know that most of you will see that the django code is harder. Yes, it's longer and harder but smarter to use. I will prefer to use long code, then easily type book.name to display the latest books. The framework aims to make easy long and big application development.

Wednesday, July 16, 2008

Working with Google App Engine Framework

Every language or platform should have frameworks, those are library that just accelerate development speed and better your work.
For example, the Dot Net Framework, try just to compare it with the dot net assembly language. So here's a simple and easy to use example!

While typing huge lines of code to shut down a computer...
'calling windows api
'if..then..end if
and some lines of code
You replace the work with
Windows.shutdown

Framework are huge libraries that replace ALL the code, so you don't have to work with the simple python now. This is an important step if you are going to work with Google App Engine and build secure application and long lines of code.

Google App Engine accept FrameWorks, (it's better to say Python!).
I was in this page and noticed that Google SDK have already a framework included; however if you want to include another framework, you simply have to include its' code in a folder on your project. Like Pear with PHP.

Google App Engine include a simple Framework of its' own, called Webapp

The test application will become then...


import wsgiref.handlers

from google.appengine.ext import webapp

class MainPage(webapp.RequestHandler):
def get(self):
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write('Test')

def main():
application = webapp.WSGIApplication(
[('/', MainPage)],
debug=True)
wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
main()


A first look on the code.. that's too long! Yes but easy to understand, if you can't learn it, then you should find a code editor like the Visual Studio editor for .net

Saturday, July 12, 2008

Register your Google App Engine Application

Then we should run. I click the button and decided to create my application. The first step was to identify myself. This will help Google prevent SPAM! I didn't tried but I think 1 phone number can register you one time.

I'm in Tunisia and the process was ultra fast. The assistant told me that I should wait 10 minutes or more but it didn't take even 1 second. I was really shocked because if i was sending the sms to another number and of the same network, this will take longer than 2 minutes to wait. Any way, how you can explain it, I got the code and arrived to the creating page of the application.

I enter the "application name" and it said that it's available, but when I click on Save, that tell me that the ID is not available.

No way, I must try another way. So I started with the Getting Started documentation.

First step is to download Python and install it. Which will be another story!
Python wasn't that lite, it wieght more than 10 mb. One thing that I don't have answer, why should I install Python? Why Google need python? Is it just needed for developer?

I first started by reading the stupid Python introduction
Python is a dynamic object-oriented programming language that can be used for many kinds of software development. It offers strong support for integration with other languages and tools, comes with extensive standard libraries, and can be learned in a few days. Many Python programmers report substantial productivity gains and feel the language encourages the development of higher quality, more maintainable code.
Here's what you could read on the main page of Python. But still not clear for me what this thing will do!
I found in the side bar, a widget that shows category where this Python can help and I got interested on the Web Programming one but really didn't find something attracting especially when I saw that the download completed.

Ok the installation with the msi package was too easy but using it... may not, so I got a look on the program menu. I found the documentation, so I opened it and it starts a real server! (like the dot net help).

The help is so big! And Python seems clearly now a group of library, that we'll use perhaps. So I returned to Google App engine.

The next step is to download the Google App engine SDK. I found also some buttons for websites powered by Google App Engine. I decided to use one in the blog when fixing a custom template to it.

The SDK was light, only 2.5 mb, and It was msi package also. That was an important point for me because the Google Desktop SDK for Windows was a zip file, with very stupid files inside.
But 2.5 mb wasn't that impressive for me, if I compare it to Visual Basic .net, this would be 30 times bigger. But bigger don't mean better, but so bigger may mean it!

I found it now boring and won't become interesting unless I see and react with some samples that I'm going to show later.
Interested on Microsoft Technologies? Read Visual Studio Dot Net